This is an automated email from the ASF dual-hosted git repository.

vatsrahul1001 pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git


The following commit(s) were added to refs/heads/main by this push:
     new 7a5b6a3bab2 Fix false triggerer deadlock reports when the supervisor 
loop is slow (#76885)
7a5b6a3bab2 is described below

commit 7a5b6a3bab27e1ba4468cc8924b9ebe6fead6589
Author: buhuipao <[email protected]>
AuthorDate: Tue Dec 1 03:38:59 2026 +0800

    Fix false triggerer deadlock reports when the supervisor loop is slow 
(#76885)
    
    The triggerer supervisor skips its heartbeat and logs "TriggerRunner
    subprocess event loop appears deadlocked" when it has not handled a
    message from the runner for `runner_health_check_threshold` seconds.
    
    That time also included the supervisor's own work: the database work
    of the loop after it read the runner's sockets, and the work on a
    request before the reply is sent, such as uploading the logs of
    finished triggers. When either took longer than the threshold, a
    healthy runner was reported as deadlocked and the heartbeat was
    skipped, although the runner's next request was already waiting to be
    read, or the runner was still waiting for the reply.
---
 .../src/airflow/jobs/triggerer_job_runner.py       | 26 +++++---
 airflow-core/tests/unit/jobs/test_triggerer_job.py | 70 ++++++++++++++++++++++
 2 files changed, 89 insertions(+), 7 deletions(-)

diff --git a/airflow-core/src/airflow/jobs/triggerer_job_runner.py 
b/airflow-core/src/airflow/jobs/triggerer_job_runner.py
index 5e8ad57b8e5..15260eb4c3a 100644
--- a/airflow-core/src/airflow/jobs/triggerer_job_runner.py
+++ b/airflow-core/src/airflow/jobs/triggerer_job_runner.py
@@ -695,11 +695,11 @@ class TriggerRunnerSupervisor(WatchedSubprocess):
     runner: TriggerRunner | None = None
     stop: bool = False
 
-    # Timestamp of the last message received from the TriggerRunner 
subprocess.  Updated on
-    # every message; if it goes silent for longer than 
runner_health_check_threshold the
-    # subprocess's async event loop has likely deadlocked.  Initialised to 
+inf so the watchdog
-    # stays silent until the first message arrives — avoids false positives on 
slow/cold-start
-    # hosts where startup can exceed the threshold.
+    # Timestamp of the last handled message from the TriggerRunner subprocess. 
 Updated when
+    # the handling of a message ends; if the subprocess goes silent for longer 
than
+    # runner_health_check_threshold its async event loop has likely 
deadlocked.  Initialised to
+    # +inf so the watchdog stays silent until the first message is handled — 
avoids false
+    # positives on slow/cold-start hosts where startup can exceed the 
threshold.
     _last_runner_comms: float = attrs.field(init=False, default=math.inf)
     _runner_comms_silence_logged: bool = attrs.field(init=False, default=False)
 
@@ -814,12 +814,14 @@ class TriggerRunnerSupervisor(WatchedSubprocess):
             yield
         finally:
             _handling_trigger_ti_id.reset(token)
+            # Set when the request is done, not when it arrives: the runner 
waits for the reply, so
+            # the time spent on the request is not its silence.
+            self._last_runner_comms = time.monotonic()
 
     def _handle_request(self, msg: ToTriggerSupervisor, log: 
FilteringBoundLogger, req_id: int) -> None:
 
         resp: BaseModel | None = None
         dump_opts: dict[str, bool] = {}
-        self._last_runner_comms = time.monotonic()
 
         if isinstance(msg, messages.TriggerStateChanges):
             # Events before failures: a trigger that fired and then failed 
starts a new count.
@@ -1009,7 +1011,13 @@ class TriggerRunnerSupervisor(WatchedSubprocess):
                 "subclasses without a metadata-DB Job must override this 
method."
             )
         elapsed = time.monotonic() - self._last_runner_comms
-        if self.runner_health_check_threshold > 0 and elapsed > 
self.runner_health_check_threshold:
+        if (
+            self.runner_health_check_threshold > 0
+            and elapsed > self.runner_health_check_threshold
+            # The work of this loop since the sockets were last read can 
outlast the threshold on its
+            # own. The runner is not silent while a request from it is still 
waiting to be read.
+            and not self._has_unread_runner_request()
+        ):
             if not self._runner_comms_silence_logged:
                 log.error(
                     "TriggerRunner subprocess event loop appears deadlocked: 
no communication received "
@@ -1023,6 +1031,10 @@ class TriggerRunnerSupervisor(WatchedSubprocess):
         self._runner_comms_silence_logged = False
         perform_heartbeat(self.job, 
heartbeat_callback=self.heartbeat_callback, only_if_necessary=True)
 
+    def _has_unread_runner_request(self) -> bool:
+        """Return whether data from the runner is waiting unread on the 
request socket."""
+        return any(key.fileobj is self.stdin for key, _ in 
self.selector.select(timeout=0))
+
     def heartbeat_callback(self, session: Session | None = None) -> None:
         stats.incr("triggerer_heartbeat", 1, 1, tags=prune_dict({"team_name": 
self.team_name}))
         # On heartbeat rather than every loop, as thousands of watchers may 
have left for other triggerers.
diff --git a/airflow-core/tests/unit/jobs/test_triggerer_job.py 
b/airflow-core/tests/unit/jobs/test_triggerer_job.py
index af58fa23f20..28217121f67 100644
--- a/airflow-core/tests/unit/jobs/test_triggerer_job.py
+++ b/airflow-core/tests/unit/jobs/test_triggerer_job.py
@@ -762,6 +762,76 @@ def 
test_heartbeat_watchdog_disabled_when_threshold_is_zero(supervisor_builder,
     perform_heartbeat_mock.assert_called_once()
 
 
[email protected](
+    ("unread_socket", "heartbeat_expected"),
+    [
+        pytest.param("requests", True, id="unread-request"),
+        pytest.param("logs", False, id="unread-logs-only"),
+    ],
+)
+def test_heartbeat_watchdog_counts_unread_runner_request(
+    supervisor_builder, mocker, unread_socket, heartbeat_expected
+):
+    """A request the runner sent while the loop was busy with other work shows 
that the runner is alive."""
+    supervisor = supervisor_builder()
+    perform_heartbeat_mock = mocker.patch(
+        "airflow.jobs.triggerer_job_runner.perform_heartbeat", autospec=True
+    )
+    runner_requests, requests = socketpair()
+    runner_logs, logs = socketpair()
+
+    with runner_requests, requests, runner_logs, logs, 
selectors.DefaultSelector() as selector:
+        selector.register(requests, selectors.EVENT_READ)
+        selector.register(logs, selectors.EVENT_READ)
+        supervisor.selector = selector
+        supervisor.stdin = requests
+        # The work after the last read of the sockets took longer than the 
threshold.
+        supervisor._last_runner_comms = time.monotonic() - 31.0
+        {"requests": runner_requests, "logs": 
runner_logs}[unread_socket].sendall(b"sent in that time")
+
+        supervisor.heartbeat()
+
+    assert perform_heartbeat_mock.called is heartbeat_expected
+
+
[email protected]("request_fails", [False, True], ids=["answered", 
"failed"])
+def test_heartbeat_watchdog_does_not_count_time_spent_on_runner_request(
+    supervisor_builder, mocker, request_fails
+):
+    """The runner waits for the reply to its request, so that time says 
nothing about its event loop."""
+    supervisor = supervisor_builder()
+    perform_heartbeat_mock = mocker.patch(
+        "airflow.jobs.triggerer_job_runner.perform_heartbeat", autospec=True
+    )
+    monotonic = mocker.patch(
+        "airflow.jobs.triggerer_job_runner.time.monotonic", autospec=True, 
return_value=0.0
+    )
+    mocker.patch.object(TriggerRunnerSupervisor, "make_client", autospec=True)
+
+    def get_xcom_for_longer_than_threshold(client, msg):
+        monotonic.return_value += 31.0
+        if request_fails:
+            raise RuntimeError("API server did not answer")
+        return OKResponse(ok=True), {}
+
+    mocker.patch(
+        "airflow.jobs.triggerer_job_runner.handle_get_xcom",
+        autospec=True,
+        side_effect=get_xcom_for_longer_than_threshold,
+    )
+    requests = 
supervisor.handle_requests(log=mocker.Mock(spec=FilteringBoundLogger))
+    next(requests)
+    # The runner's previous request was handled just before this one arrived.
+    supervisor._last_runner_comms = monotonic.return_value
+
+    requests.send(
+        _RequestFrame(id=1, body=GetXCom(key="k", dag_id="d", run_id="r", 
task_id="t").model_dump())
+    )
+    supervisor.heartbeat()
+
+    perform_heartbeat_mock.assert_called_once()
+
+
 def _is_trigger_delete(statement: str) -> bool:
     return "delete from trigger" in " ".join(statement.lower().replace('"', 
"").replace("`", "").split())
 

Reply via email to