kaxil commented on code in PR #74279:
URL: https://github.com/apache/airflow/pull/74279#discussion_r4688748811
##########
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:
This `__dict__` lookup was my suggestion, and it skips `get_db_hook()`, the
documented override point: a subclass that returns its own hook from
`get_db_hook()` never sets `_hook`, so `on_kill` logs that no statement ran
while one is running. Keeping the hook `execute()` actually used (say
`self._running_hook = hook`) and reading that here covers both cases and still
builds nothing in the signal handler.
##########
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:
The Snowflake change only covers future releases. Snowflake 6.17.0 through
6.21.0 still set `self.cancel_on_kill` before `super().__init__()` and allow
`common-sql>=1.32.0`, so upgrading only common-sql turns a user's
`cancel_on_kill=False` back into `True`, for both `on_kill` and the trigger it
defers to. My earlier suggestion had the same gap. Could this line keep a value
a subclass already set, e.g. assign only when `"cancel_on_kill" not in
self.__dict__`?
##########
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:
Since the default flipped to `False`, this test no longer pins the `except
Exception: raise` in `_track_running_cursor`: drop that clause and it still
passes, because the `BaseException` branch doesn't cancel with the flag off.
Setting `hook.cancel_on_interrupt = True` here would make
`cancel.assert_not_called()` check something again.
##########
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:
I missed this earlier, sorry. On Trino, cancelling from `on_kill` doesn't
fail the task. `Cursor.cancel()` only sets a flag, so `execute()` returns
normally, and `_on_term` doesn't raise either. With `do_xcom_push=False`
there's no handler to trip over it, so `run()` goes on to the next statement
and the commit. In a breeze run against a real Trino, an `INSERT` killed 2s in
returned normally and left 466,036 rows in the table. Could the hook remember
it sent a cancel and raise once the tracked block exits normally? A test where
`execute` returns after `cancel()` would cover it.
--
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]