DG47 commented on code in PR #74279:
URL: https://github.com/apache/airflow/pull/74279#discussion_r4698385467


##########
providers/common/sql/src/airflow/providers/common/sql/hooks/sql.py:
##########
@@ -881,6 +903,84 @@ def _run_command(self, cur, sql_statement, parameters):
         if (row_count := handlers.get_row_count(cur)) is not None:
             self.log.info("Rows affected: %s", row_count)
 
+    @contextmanager
+    def _track_running_cursor(self, cur) -> Generator[None, None, None]:
+        """
+        Make ``cur`` the cursor that ``cancel_query`` cancels while the block 
runs.
+
+        When ``cancel_on_interrupt`` is ``True`` (it is ``False`` by default), 
an interruption that is not an
+        ``Exception`` (``AirflowTaskTimeout`` raised from ``SIGALRM`` when the 
``execution_timeout`` of the
+        task elapses, ``KeyboardInterrupt``) cancels the statement before it 
propagates: ``on_kill`` is only
+        called after it has unwound through ``run``, which closes the cursor 
and the connection on the way,
+        so cancelling there would be too late.
+
+        Nested blocks for the same cursor leave the tracking to the outermost 
one, so that ``run`` keeps the
+        cursor tracked from ``_run_command`` through the result handler.
+        """
+        if self._running_cursor is cur:
+            yield
+            return
+        self._running_cursor = cur
+        try:
+            yield
+        except Exception:
+            raise
+        except BaseException:
+            if self.cancel_on_interrupt:
+                try:
+                    self.cancel_query()
+                except Exception:
+                    self.log.exception("Failed to cancel the running SQL 
statement")
+            raise
+        finally:
+            self._running_cursor = None
+
+    def cancel_query(self) -> bool:
+        """
+        Cancel the SQL statement that this hook is currently executing, if 
there is one.
+
+        
:class:`~airflow.providers.common.sql.operators.sql.SQLExecuteQueryOperator` 
calls this method from
+        ``on_kill`` when the task instance is killed while a statement is 
still running, so that the
+        database stops working on a query whose result nobody is waiting for 
anymore.
+
+        A statement is tracked from the moment ``run`` executes it until its 
result handler returns, in
+        hooks that execute statements through ``run`` or ``_run_command``. 
Hooks that execute statements
+        in another way can override this method.
+
+        The default implementation relies on the cancellation extensions 
offered by many DB-API drivers:
+        ``cursor.cancel()`` is used when the cursor provides it (e.g. 
``trino``), otherwise
+        ``connection.cancel()`` is used when the cursor exposes its connection 
and the connection provides
+        it (e.g. ``psycopg`` or ``oracledb`` in its default thin mode). This 
only helps with drivers that
+        return to Python to handle signals while a statement is running. 
Drivers that block in C until the statement completes (e.g.
+        ``psycopg2``, ``sqlite3``, ``mysqlclient`` or 
``mysql-connector-python``) never let the signal
+        handlers run during the statement: ``on_kill`` is not called before 
the task process is killed,
+        and the ``execution_timeout`` is only raised once the statement has 
returned. Hooks for such
+        databases can override this method and cancel the statement in a 
database specific way, for
+        example by issuing a ``KILL QUERY`` command on a separate connection.
+
+        :return: ``True`` if a cancellation request was sent to the database, 
``False`` if no running
+            statement is tracked or the driver does not support cancelling a 
running statement.
+        """
+        cur = self._running_cursor
+        if cur is None:
+            # Not a problem: the statement has already completed, or was 
cancelled when it was interrupted
+            self.log.info(
+                "No SQL statement is running in %s, there is nothing to 
cancel.", type(self).__name__
+            )
+            return False
+        for name, target in (("cursor", cur), ("connection", getattr(cur, 
"connection", None))):
+            cancel = getattr(target, "cancel", None)
+            if callable(cancel):
+                self.log.info("Cancelling the running SQL statement through 
%s.cancel()", name)
+                cancel()

Review Comment:
   ## kaxil: Trino `cancel()` does not fail the task
   
   Thread: https://github.com/apache/airflow/pull/74279#discussion_r4688748803 
(comment id 4688748803)
   
   Fixed in 14dcf4e08e. `cancel_query()` now records the request on the hook. 
When the tracked statement returns normally after it, `_track_running_cursor` 
raises `RuntimeError` instead of returning, so `run()` doesn't start the next 
statement or commit. 
`test_statement_that_returns_normally_after_cancel_stops_the_run` makes 
`execute` return after `cancel()` and checks that the second statement isn't 
executed and `commit()` isn't called. It fails on 1f0d888b25. I checked this 
against the `trino` 0.339 client code, where `TrinoQuery.cancel()` sets 
`_cancelled` and the fetch loops in `execute()` exit normally, but not against 
a running Trino.
   



##########
providers/common/sql/src/airflow/providers/common/sql/operators/sql.py:
##########
@@ -546,6 +552,7 @@ def __init__(
         self.return_last = return_last
         self.show_return_value_in_logs = show_return_value_in_logs
         self.requires_result_fetch = requires_result_fetch
+        self.cancel_on_kill = cancel_on_kill

Review Comment:
   ## kaxil: released Snowflake versions set `cancel_on_kill` before 
`super().__init__()`
   
   Thread: https://github.com/apache/airflow/pull/74279#discussion_r4688748806 
(comment id 4688748806)
   
   I moved this into common.sql instead (cdb20a8238): 
`SQLExecuteQueryOperator.__init__` now assigns `cancel_on_kill` only when it 
isn't already in `self.__dict__`. That makes the order released in Snowflake 
6.17.0 to 6.21.0 work with any common-sql, so I reverted the Snowflake change 
from 368d447284 and 1f0d888b25, and the PR no longer touches that provider. 
`test_cancel_on_kill_set_by_a_subclass_before_init_is_kept` covers it in 
common.sql and fails on 1f0d888b25. With the Snowflake operator back to its 
released code, `test_snowflake_sql_api_on_kill_respects_cancel_on_kill_false` 
fails without the common-sql change and passes with it (Snowflake operator 
tests: 74 passed).
   



##########
providers/common/sql/src/airflow/providers/common/sql/operators/sql.py:
##########
@@ -601,6 +610,32 @@ def execute(self, context):
         self.log.info("result: %s", result)
         return result
 
+    def on_kill(self) -> None:
+        """
+        Cancel the SQL statement that is still running when the task instance 
is killed.
+
+        Airflow calls this method from the ``SIGTERM`` handler of the task 
process, i.e. while ``execute``
+        may still be waiting in the database driver for the statement to 
finish (with drivers that return to
+        Python to handle signals during a statement, see 
``DbApiHook.cancel_query``). Cancellation is
+        delegated to 
:meth:`~airflow.providers.common.sql.hooks.sql.DbApiHook.cancel_query`, so every
+        database hook can use the mechanism its driver offers. It is best 
effort and never raises. A
+        statement interrupted by the ``execution_timeout`` of the task is 
already cancelled by the hook
+        before this method is called.
+        """
+        if not self.cancel_on_kill:
+            return
+        # Only the hook that ``execute`` ran on holds the running statement. 
``get_db_hook()`` could build a
+        # new hook here, with a connection lookup inside the signal handler, 
that has nothing to cancel.
+        hook = self.__dict__.get("_hook")

Review Comment:
   ## kaxil: the `__dict__` lookup skips `get_db_hook()`
   
   Thread: https://github.com/apache/airflow/pull/74279#discussion_r4688748811 
(comment id 4688748811)
   
   Right, that bypasses the override. In 606a1aba24 `execute()` keeps the hook 
it got from `get_db_hook()` in `self._running_hook`, and `on_kill()` reads 
that. `execute()` clears it once `run()` returns, so the `on_kill()` call the 
task runner makes after an `execution_timeout` finds no hook. 
`test_on_kill_cancels_through_the_hook_returned_by_get_db_hook` uses a subclass 
whose `get_db_hook()` returns its own hook, like DuckDB's, and fails on 
1f0d888b25. The other `on_kill` tests now go through `execute()`, because the 
reference only exists while `run()` is running.
   



##########
providers/common/sql/tests/unit/common/sql/hooks/test_sql.py:
##########
@@ -503,3 +504,144 @@ def 
get_sqlalchemy_engine_with_listeners(engine_kwargs=None):
     assert table_names == ["users"]
     assert opened
     assert closed == opened
+
+
+CURSOR_SPEC = ["execute", "fetchall", "close", "description", "rowcount"]
+
+
+class TestDbApiHookCancelQuery:
+    @staticmethod
+    def _hook_with_cursor(cursor: MagicMock) -> DbApiHook:
+        hook = mock_db_hook(DbApiHook)
+        hook.get_conn().cursor.return_value = cursor
+        return hook
+
+    @staticmethod
+    def _cancel_during(hook: DbApiHook, cursor_method: MagicMock) -> 
list[bool]:
+        """Record what ``cancel_query`` returns when it is called from inside 
``cursor_method``."""
+        outcome: list[bool] = []
+
+        def cancel(*args, **kwargs):
+            outcome.append(hook.cancel_query())
+            return []
+
+        cursor_method.side_effect = cancel
+        return outcome
+
+    def test_nothing_to_cancel_when_no_statement_is_running(self, caplog):
+        cursor = MagicMock(spec=[*CURSOR_SPEC, "cancel"])
+        hook = self._hook_with_cursor(cursor)
+
+        with caplog.at_level(logging.INFO):
+            assert hook.cancel_query() is False
+
+        assert "there is nothing to cancel" in caplog.text
+        assert not [r for r in caplog.records if r.levelno >= logging.WARNING]
+        cursor.cancel.assert_not_called()
+
+    def test_cancel_through_cursor(self):
+        cursor = MagicMock(spec=[*CURSOR_SPEC, "cancel", "connection"])
+        hook = self._hook_with_cursor(cursor)
+        outcome = self._cancel_during(hook, cursor.execute)
+
+        hook.run("select pg_sleep(600)")
+
+        assert outcome == [True]
+        cursor.cancel.assert_called_once_with()
+        cursor.connection.cancel.assert_not_called()
+        assert hook._running_cursor is None
+
+    def test_cancel_falls_back_to_connection(self):
+        cursor = MagicMock(spec=[*CURSOR_SPEC, "connection"])
+        hook = self._hook_with_cursor(cursor)
+        outcome = self._cancel_during(hook, cursor.execute)
+
+        hook.run("select pg_sleep(600)")
+
+        assert outcome == [True]
+        cursor.connection.cancel.assert_called_once_with()
+        assert hook._running_cursor is None
+
+    def test_cancel_not_supported_by_driver(self, caplog):
+        cursor = MagicMock(spec=[*CURSOR_SPEC, "connection"])
+        cursor.connection = MagicMock(spec=["commit", "close"])
+        hook = self._hook_with_cursor(cursor)
+        outcome = self._cancel_during(hook, cursor.execute)
+
+        with caplog.at_level(logging.WARNING):
+            hook.run("select pg_sleep(600)")
+
+        assert outcome == [False]
+        assert "does not support cancelling a running SQL statement" in 
caplog.text
+
+    def test_cancel_while_handler_fetches_results(self):
+        cursor = MagicMock(spec=[*CURSOR_SPEC, "cancel"])
+        hook = self._hook_with_cursor(cursor)
+        outcome = self._cancel_during(hook, cursor.fetchall)
+
+        hook.run("select * from big_table", handler=fetch_all_handler)
+
+        assert outcome == [True]
+        cursor.cancel.assert_called_once_with()
+        assert hook._running_cursor is None
+
+    def test_cancel_when_run_command_is_called_directly(self):
+        # Hooks with their own ``run`` (e.g. ``DatabricksSqlHook``) only call 
``_run_command``
+        cursor = MagicMock(spec=[*CURSOR_SPEC, "cancel"])
+        hook = self._hook_with_cursor(cursor)
+        outcome = self._cancel_during(hook, cursor.execute)
+
+        hook._run_command(cursor, "select pg_sleep(600)", None)
+
+        assert outcome == [True]
+        assert hook._running_cursor is None
+
+    def test_running_cursor_is_cleared_when_statement_fails(self):
+        cursor = MagicMock(spec=[*CURSOR_SPEC, "cancel"])
+        cursor.execute.side_effect = RuntimeError("boom")
+        hook = self._hook_with_cursor(cursor)

Review Comment:
   ## kaxil: no test pins `except Exception: raise`
   
   Thread: https://github.com/apache/airflow/pull/74279#discussion_r4688748813 
(comment id 4688748813)
   
   5973215c11 sets `hook.cancel_on_interrupt = True` in that test. Now it fails 
with the `except Exception: raise` clause removed, because `cancel` gets 
called, and passes with it.
   



##########
providers/common/sql/src/airflow/providers/common/sql/hooks/sql.py:
##########
@@ -881,6 +903,84 @@ def _run_command(self, cur, sql_statement, parameters):
         if (row_count := handlers.get_row_count(cur)) is not None:
             self.log.info("Rows affected: %s", row_count)
 
+    @contextmanager
+    def _track_running_cursor(self, cur) -> Generator[None, None, None]:
+        """
+        Make ``cur`` the cursor that ``cancel_query`` cancels while the block 
runs.
+
+        When ``cancel_on_interrupt`` is ``True`` (it is ``False`` by default), 
an interruption that is not an
+        ``Exception`` (``AirflowTaskTimeout`` raised from ``SIGALRM`` when the 
``execution_timeout`` of the
+        task elapses, ``KeyboardInterrupt``) cancels the statement before it 
propagates: ``on_kill`` is only
+        called after it has unwound through ``run``, which closes the cursor 
and the connection on the way,
+        so cancelling there would be too late.
+
+        Nested blocks for the same cursor leave the tracking to the outermost 
one, so that ``run`` keeps the
+        cursor tracked from ``_run_command`` through the result handler.
+        """
+        if self._running_cursor is cur:
+            yield
+            return
+        self._running_cursor = cur
+        try:
+            yield
+        except Exception:
+            raise
+        except BaseException:
+            if self.cancel_on_interrupt:
+                try:
+                    self.cancel_query()
+                except Exception:
+                    self.log.exception("Failed to cancel the running SQL 
statement")
+            raise
+        finally:
+            self._running_cursor = None
+
+    def cancel_query(self) -> bool:
+        """
+        Cancel the SQL statement that this hook is currently executing, if 
there is one.
+
+        
:class:`~airflow.providers.common.sql.operators.sql.SQLExecuteQueryOperator` 
calls this method from
+        ``on_kill`` when the task instance is killed while a statement is 
still running, so that the
+        database stops working on a query whose result nobody is waiting for 
anymore.
+
+        A statement is tracked from the moment ``run`` executes it until its 
result handler returns, in
+        hooks that execute statements through ``run`` or ``_run_command``. 
Hooks that execute statements
+        in another way can override this method.
+
+        The default implementation relies on the cancellation extensions 
offered by many DB-API drivers:
+        ``cursor.cancel()`` is used when the cursor provides it (e.g. 
``trino``), otherwise
+        ``connection.cancel()`` is used when the cursor exposes its connection 
and the connection provides
+        it (e.g. ``psycopg`` or ``oracledb`` in its default thin mode). This 
only helps with drivers that
+        return to Python to handle signals while a statement is running. 
Drivers that block in C until the statement completes (e.g.
+        ``psycopg2``, ``sqlite3``, ``mysqlclient`` or 
``mysql-connector-python``) never let the signal
+        handlers run during the statement: ``on_kill`` is not called before 
the task process is killed,
+        and the ``execution_timeout`` is only raised once the statement has 
returned. Hooks for such
+        databases can override this method and cancel the statement in a 
database specific way, for
+        example by issuing a ``KILL QUERY`` command on a separate connection.
+
+        :return: ``True`` if a cancellation request was sent to the database, 
``False`` if no running
+            statement is tracked or the driver does not support cancelling a 
running statement.
+        """
+        cur = self._running_cursor
+        if cur is None:

Review Comment:
   ## dabla: a kill with no tracked cursor lets the following statements run
   
   Thread: https://github.com/apache/airflow/pull/74279#discussion_r4691846460 
(comment id 4691846460, review 6053670648)
   
   Fixed in 14dcf4e08e, the way you suggested. `cancel_query()` records the 
request whether or not a cursor is tracked. `_track_running_cursor` raises 
`RuntimeError` on entry when the request is set, so the statement doesn't 
start, and on a normal exit, which is the Trino case. The request is cleared 
when `run()` returns. It is also cleared when the tracked statement ends, for 
hooks like `DatabricksSqlHook` that call `_run_command()` from their own 
`run()`.
   
   For the operator: when no hook is stored yet, `on_kill()` sets 
`self._killed`. Right after storing the hook, `execute()` passes that on with 
`hook.cancel_query()`, so a kill during `get_db_hook()` keeps the statement 
from starting. `execute()` resets `_killed` when it starts and drops the hook 
once `run()` returns (606a1aba24), so the `on_kill()` call after an 
`execution_timeout` doesn't stop a later run.
   
   Tests that fail on 1f0d888b25 and check the next `cursor.execute` isn't 
called:
   - `test_statement_is_not_started_after_cancel_before_run`
   - `test_next_statement_is_not_started_after_cancel_between_statements`
   - `test_kill_while_the_hook_is_created_keeps_the_statement_from_starting`
   
   Tests that run the same hook or operator again after a cancelled run and 
check it isn't stopped:
   - `test_cancel_does_not_stop_the_next_run`, for a statement that returns, a 
statement that fails, and a cancel during `commit()`
   - `test_cancel_before_run_command_only_stops_one_statement`
   - `test_on_kill_after_execution_timeout_does_not_stop_the_next_run`
   
   The existing cancel tests now expect `RuntimeError`, because their cursor 
returns normally after `cancel()`, as Trino's does.
   
   Two windows are still open. A kill before `execute()` starts, for example 
while `@task.sql` runs its callable, is lost because `execute()` resets 
`_killed`. A kill after the last statement but before the commit lets the 
commit go through.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to