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


##########
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:
   **[warning]** A kill that lands while no cursor is tracked cancels nothing, 
and the statements that start afterwards are never cancelled.
   
   On Airflow 3 the SIGTERM handler only calls `on_kill()` and raises nothing 
([`_on_term`](https://github.com/apache/airflow/blob/1f0d888b25c6fb8496d34c44525b7bf1148b58f3/task-sdk/src/airflow/sdk/execution_time/task_runner.py#L1651-L1656)),
 so `execute()` carries on after it. When `_running_cursor` is `None` at that 
moment, this branch logs "nothing to cancel" and returns, and `run()` goes on 
to start the next statement. That statement runs until the supervisor kills the 
process, and with drivers such as psycopg it keeps running on the server after 
that, which is the situation this PR set out to remove.
   
   The cursor is untracked in more places than between two statements:
   
   - while `_create_autocommit_connection()` is still connecting, before the 
first statement (a slow login or a pool wait makes this a window of seconds),
   - between the statements of a split or list `sql`,
   - in the operator, before `_hook` is cached: `on_kill()` logs that the task 
was killed before a statement was run, and `execute()` then runs it.
   
   This sits next to the [Trino 
thread](https://github.com/apache/airflow/pull/74279#discussion_r4688748803) 
and one mechanism can close both: let `cancel_query()` record that a cancel was 
requested whether or not a cursor is tracked, and let `_track_running_cursor` 
raise when that is set, on entry (do not start the statement) as well as on a 
normal exit (the Trino case). The record has to be cleared when the run ends, 
because the task runner calls `on_kill()` again after an `execution_timeout`, 
and `dag.test()` and the tests run one operator object several times in a 
process: a request left over from a killed run must not fail the next one.
   
   Two tests would pin it: `cancel_query()` called before `run()` and between 
two statements, each asserting that the next `cursor.execute` is not called, 
and a rerun of the same hook after a cancelled run that executes normally.



-- 
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