Skip to content

Commit eebf253

Browse files
authored
Skip on_kill() for triggers reassigned to another triggerer (#73454)
When a triggerer's heartbeat lapsed and its triggers were handed to another triggerer, the recovering triggerer treated every trigger missing from its assignment list as a user action and called on_kill(), cancelling remote work the new owner had just started polling. The supervisor now checks whether the trigger row still exists (and who owns it) before deciding: a surviving row is released locally without on_kill(); only a deleted row takes the user-action path.
1 parent 389b4e1 commit eebf253

4 files changed

Lines changed: 239 additions & 22 deletions

File tree

‎airflow-core/src/airflow/jobs/triggerer_job_runner.py‎

Lines changed: 62 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,9 @@
150150
tracer = trace.get_tracer(__name__)
151151
# Private sentinel passed as the cancel message when a trigger is cancelled by user action
152152
_USER_ACTION_CANCEL_MSG = "__airflow_user_action__"
153+
# Private sentinel passed as the cancel message when a trigger's row moved to another triggerer, so
154+
# run_trigger() drops it locally without invoking on_kill()
155+
_REASSIGNED_CANCEL_MSG = "__airflow_reassigned__"
153156

154157
_ON_CANCEL_TIMEOUT: int = conf.getint("triggerer", "on_kill_timeout", fallback=30)
155158

@@ -336,7 +339,10 @@ class TriggerStateSync(BaseModel):
336339
type: Literal["TriggerStateSync"] = "TriggerStateSync"
337340

338341
to_create: list[workloads.RunTrigger]
342+
# Triggers whose row is gone (task no longer deferred on it); the runner invokes on_kill()
339343
to_cancel: set[int]
344+
# Triggers whose row now belongs to another triggerer; the runner drops them without on_kill()
345+
to_release: set[int] = Field(default_factory=set)
340346
# Seqs of shared-stream trigger events the supervisor has persisted
341347
# since the previous sync; the runner releases the matching broker
342348
# advances on receipt.
@@ -513,6 +519,8 @@ class TriggerRunnerSupervisor(WatchedSubprocess):
513519
# FinishedTriggers message
514520
cancelling_triggers: set[int] = attrs.field(factory=set, init=False)
515521

522+
releasing_triggers: set[int] = attrs.field(factory=set, init=False)
523+
516524
# A list of RunTrigger workloads to send to the async process when it next checks in. We can't send it
517525
# directly as all comms has to be initiated by the subprocess
518526
creating_triggers: deque[workloads.RunTrigger] = attrs.field(factory=deque, init=False)
@@ -592,6 +600,7 @@ def _handle_request(self, msg: ToTriggerSupervisor, log: FilteringBoundLogger, r
592600
for id in msg.finished or ():
593601
self.running_triggers.discard(id)
594602
self.cancelling_triggers.discard(id)
603+
self.releasing_triggers.discard(id)
595604
if factory := self.logger_cache.pop(id, None):
596605
try:
597606
factory.upload_to_remote()
@@ -610,6 +619,7 @@ def _handle_request(self, msg: ToTriggerSupervisor, log: FilteringBoundLogger, r
610619
response = messages.TriggerStateSync(
611620
to_create=[],
612621
to_cancel=self.cancelling_triggers,
622+
to_release=self.releasing_triggers,
613623
events_persisted=events_persisted or None,
614624
)
615625

@@ -923,6 +933,16 @@ def fetch_non_task_trigger_ids(self, *, session: Session) -> set[int]:
923933
"""Fetch trigger IDs associated with non-task entities."""
924934
return Trigger.fetch_trigger_ids_with_non_task_associations(session=session)
925935

936+
def fetch_trigger_assignments(self, trigger_ids: set[int]) -> dict[int, int | None]:
937+
"""
938+
Map each trigger ID whose row still exists to the triggerer that owns it now.
939+
940+
Owns its own session so that ``update_triggers`` stays a pure diff/enqueue step that
941+
subclasses without a metadata DB can keep calling after overriding this hook.
942+
"""
943+
with create_session() as session:
944+
return Trigger.fetch_assignments(trigger_ids, session=session)
945+
926946
def build_trigger_workloads(self, new_trigger_ids: set[int]) -> list[workloads.RunTrigger]:
927947
"""Build workloads for new trigger IDs."""
928948
dag_bag = DBDagBag()
@@ -977,12 +997,16 @@ def update_triggers(self, requested_trigger_ids: set[int]):
977997
known_trigger_ids = self.running_triggers.union(
978998
(x[0] for x in self.events),
979999
self.cancelling_triggers,
1000+
self.releasing_triggers,
9801001
(trigger[0] for trigger in self.failed_triggers),
9811002
(trigger.id for trigger in self.creating_triggers),
9821003
)
983-
# Work out the two difference sets
1004+
# Work out the two difference sets. Triggers already queued for cancellation or release stay
1005+
# in running_triggers until the runner reports them finished; don't classify them again.
9841006
new_trigger_ids = requested_trigger_ids - known_trigger_ids
985-
cancel_trigger_ids = self.running_triggers - requested_trigger_ids
1007+
cancel_trigger_ids = (
1008+
self.running_triggers - requested_trigger_ids - self.cancelling_triggers - self.releasing_triggers
1009+
)
9861010

9871011
if new_trigger_ids:
9881012
workloads_to_create = self.build_trigger_workloads(new_trigger_ids)
@@ -995,8 +1019,17 @@ def update_triggers(self, requested_trigger_ids: set[int]):
9951019
self.creating_triggers.extend(workloads_to_create)
9961020

9971021
if cancel_trigger_ids:
998-
# Enqueue orphaned triggers for cancellation
999-
self.cancelling_triggers.update(cancel_trigger_ids)
1022+
# Only the DB tells the two cases apart: a gone row means the task left the
1023+
# deferred state (user action), a surviving row means assign_unassigned handed
1024+
# the trigger to a triggerer that is now polling the remote work.
1025+
assignments = self.fetch_trigger_assignments(cancel_trigger_ids)
1026+
if assignments:
1027+
log.info(
1028+
"Triggers were reassigned to another triggerer, releasing them without on_kill",
1029+
new_owners=assignments,
1030+
)
1031+
self.releasing_triggers.update(assignments)
1032+
self.cancelling_triggers.update(cancel_trigger_ids - assignments.keys())
10001033

10011034
def _register_pipe_readers(
10021035
self,
@@ -1180,9 +1213,12 @@ class TriggerRunner:
11801213
# Inbound queue of new triggers
11811214
to_create: deque[workloads.RunTrigger]
11821215

1183-
# Inbound queue of deleted triggers
1216+
# Inbound queue of deleted triggers (user acted on the task; on_kill() runs)
11841217
to_cancel: deque[int]
11851218

1219+
# Inbound queue of triggers reassigned to another triggerer (dropped locally; on_kill() skipped)
1220+
to_release: deque[int]
1221+
11861222
# Outbound queue of events
11871223
events: deque[TriggerEventEntry]
11881224

@@ -1207,6 +1243,7 @@ def __init__(self):
12071243
self.trigger_cache = {}
12081244
self.to_create = deque()
12091245
self.to_cancel = deque()
1246+
self.to_release = deque()
12101247
self.events = deque()
12111248
self.failed_triggers = deque()
12121249
self.team_name = None
@@ -1441,20 +1478,16 @@ async def create_triggers(self):
14411478
)
14421479

14431480
async def cancel_triggers(self):
1444-
"""
1445-
Drain the to_cancel queue and ensure all triggers that are not in the DB are cancelled.
1446-
1447-
This allows the cleanup job to delete them.
1448-
Passes "user-action" as the cancel message so that run_trigger() knows to invoke
1449-
on_kill(). Triggers in this queue are always removed because this is the path in which
1450-
the user performed some action on the task. Trigger redistribution goes through a separate
1451-
path.
1452-
"""
1453-
while self.to_cancel:
1454-
trigger_id = self.to_cancel.popleft()
1455-
if trigger_id in self.triggers:
1456-
self.triggers[trigger_id]["task"].cancel(_USER_ACTION_CANCEL_MSG)
1457-
await asyncio.sleep(0)
1481+
"""Drain to_cancel and to_release; the cancel message tells run_trigger() if on_kill() applies."""
1482+
for queue, cancel_msg in (
1483+
(self.to_cancel, _USER_ACTION_CANCEL_MSG),
1484+
(self.to_release, _REASSIGNED_CANCEL_MSG),
1485+
):
1486+
while queue:
1487+
trigger_id = queue.popleft()
1488+
if trigger_id in self.triggers:
1489+
self.triggers[trigger_id]["task"].cancel(cancel_msg)
1490+
await asyncio.sleep(0)
14581491

14591492
async def cleanup_finished_triggers(self) -> list[int]:
14601493
"""
@@ -1564,6 +1597,7 @@ async def sync_state_to_supervisor(self, finished_ids: list[int]) -> None:
15641597
if resp:
15651598
self.to_create.extend(resp.to_create)
15661599
self.to_cancel.extend(resp.to_cancel)
1600+
self.to_release.extend(resp.to_release)
15671601
if resp.events_persisted:
15681602
self._shared_streams.confirm_persisted(resp.events_persisted)
15691603

@@ -1692,11 +1726,13 @@ async def run_trigger(
16921726
self.events.append(TriggerEventEntry(trigger_id=trigger_id, event=event, persist_seq=seq))
16931727
span.set_status(Status(StatusCode.OK))
16941728
except asyncio.CancelledError as e:
1695-
# A trigger can be cancelled for two reasons:
1729+
# A trigger can be cancelled for three reasons:
16961730
# - The user acted on the task (mark failed / clear / mark succeeded).
1731+
# - The trigger was reassigned to another triggerer (see
1732+
# TriggerRunnerSupervisor.update_triggers); the new owner keeps running it.
16971733
# - The triggerer is shutting down, here cancel_triggers() is not
16981734
# involved — the shutdown path cancels tasks directly without a message.
1699-
# Only first case should invoke on_kill().
1735+
# Only the first case should invoke on_kill().
17001736
#
17011737
# For timeout, raise immediately without calling on_kill().
17021738
if timeout := timeout_after:
@@ -1705,7 +1741,11 @@ async def run_trigger(
17051741
await self.log.aerror("Trigger cancelled due to timeout")
17061742
span.set_status(Status(StatusCode.ERROR), description=str(e))
17071743
raise
1708-
if e.args and e.args[0] == _USER_ACTION_CANCEL_MSG:
1744+
if e.args and e.args[0] == _REASSIGNED_CANCEL_MSG:
1745+
await self.log.ainfo(
1746+
"Trigger reassigned to another triggerer, dropping it without on_kill", name=name
1747+
)
1748+
elif e.args and e.args[0] == _USER_ACTION_CANCEL_MSG:
17091749
await self.log.ainfo("Trigger cancelled by user action, invoking on_kill", name=name)
17101750
try:
17111751
await asyncio.wait_for(trigger.on_kill(), timeout=_ON_CANCEL_TIMEOUT)

‎airflow-core/src/airflow/models/trigger.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -368,6 +368,15 @@ def ids_for_triggerer(
368368

369369
return list(session.scalars(query).all())
370370

371+
@classmethod
372+
@provide_session
373+
def fetch_assignments(
374+
cls, ids: Iterable[int], *, session: Session = NEW_SESSION
375+
) -> dict[int, int | None]:
376+
"""Map each of ``ids`` that still has a trigger row to its current ``triggerer_id``."""
377+
rows = session.execute(select(cls.id, cls.triggerer_id).where(cls.id.in_(ids)))
378+
return {trigger_id: triggerer_id for trigger_id, triggerer_id in rows}
379+
371380
@classmethod
372381
@provide_session
373382
def assign_unassigned(

‎airflow-core/tests/unit/jobs/test_triggerer_job.py‎

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
4747
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
4848
from pydantic import TypeAdapter
49+
from sqlalchemy import delete, update
4950
from structlog.typing import FilteringBoundLogger
5051

5152
from airflow._shared.timezones import timezone
@@ -54,6 +55,7 @@
5455
from airflow.executors.workloads.trigger import RunTrigger
5556
from airflow.jobs.job import Job
5657
from airflow.jobs.triggerer_job_runner import (
58+
_REASSIGNED_CANCEL_MSG,
5759
_USER_ACTION_CANCEL_MSG,
5860
ToTriggerRunner,
5961
ToTriggerSupervisor,
@@ -71,6 +73,7 @@
7173
from airflow.models.dagbag import DBDagBag
7274
from airflow.models.dagbundle import DagBundleModel
7375
from airflow.models.serialized_dag import SerializedDagModel
76+
from airflow.models.taskinstance import TaskInstance
7477
from airflow.models.xcom import XComModel
7578
from airflow.providers.standard.operators.empty import EmptyOperator
7679
from airflow.providers.standard.operators.python import PythonOperator
@@ -1476,6 +1479,63 @@ def test_run_trigger_skips_on_kill_without_user_action_message(self, session) ->
14761479

14771480
mock_trigger.on_kill.assert_not_called()
14781481

1482+
def test_run_trigger_skips_on_kill_when_trigger_reassigned(self, session, cap_structlog) -> None:
1483+
"""on_kill() is not called when the trigger was handed to another triggerer."""
1484+
trigger_runner = TriggerRunner()
1485+
trigger_runner.triggers = {
1486+
1: {"task": MagicMock(spec=asyncio.Task), "is_watcher": False, "name": "mock_name", "events": 0}
1487+
}
1488+
mock_trigger = MagicMock(spec=BaseTrigger)
1489+
mock_trigger.run.side_effect = asyncio.CancelledError(_REASSIGNED_CANCEL_MSG)
1490+
mock_trigger.task_instance = MagicMock()
1491+
mock_trigger.task_instance.map_index = -1
1492+
mock_trigger.on_kill = AsyncMock()
1493+
1494+
with pytest.raises(asyncio.CancelledError):
1495+
asyncio.run(trigger_runner.run_trigger(1, mock_trigger))
1496+
1497+
mock_trigger.on_kill.assert_not_called()
1498+
assert {
1499+
"event": "Trigger reassigned to another triggerer, dropping it without on_kill",
1500+
"log_level": "info",
1501+
"name": "mock_name",
1502+
} in cap_structlog
1503+
1504+
@pytest.mark.asyncio
1505+
async def test_cancel_triggers_uses_distinct_messages_for_user_action_and_reassignment(self) -> None:
1506+
trigger_runner = TriggerRunner()
1507+
user_task = MagicMock(spec=asyncio.Task)
1508+
reassigned_task = MagicMock(spec=asyncio.Task)
1509+
trigger_runner.triggers = {
1510+
1: {"task": user_task, "is_watcher": False, "name": "user", "events": 0},
1511+
2: {"task": reassigned_task, "is_watcher": False, "name": "moved", "events": 0},
1512+
}
1513+
trigger_runner.to_cancel.append(1)
1514+
trigger_runner.to_release.append(2)
1515+
# An id the runner no longer knows about is ignored on both queues.
1516+
trigger_runner.to_cancel.append(3)
1517+
trigger_runner.to_release.append(4)
1518+
1519+
await trigger_runner.cancel_triggers()
1520+
1521+
user_task.cancel.assert_called_once_with(_USER_ACTION_CANCEL_MSG)
1522+
reassigned_task.cancel.assert_called_once_with(_REASSIGNED_CANCEL_MSG)
1523+
assert not trigger_runner.to_cancel
1524+
assert not trigger_runner.to_release
1525+
1526+
@pytest.mark.asyncio
1527+
async def test_sync_state_to_supervisor_queues_released_triggers(self) -> None:
1528+
trigger_runner = TriggerRunner()
1529+
trigger_runner.comms_decoder = AsyncMock(spec=TriggerCommsDecoder)
1530+
trigger_runner.comms_decoder.asend.return_value = messages.TriggerStateSync(
1531+
to_create=[], to_cancel={1}, to_release={2}
1532+
)
1533+
1534+
await trigger_runner.sync_state_to_supervisor([])
1535+
1536+
assert list(trigger_runner.to_cancel) == [1]
1537+
assert list(trigger_runner.to_release) == [2]
1538+
14791539
def test_run_trigger_on_kill_exception_does_not_swallow_cancelled_error(self, session) -> None:
14801540
"""CancelledError propagates even if on_kill() raises."""
14811541
trigger_runner = TriggerRunner()
@@ -2779,6 +2839,97 @@ def test_update_triggers_skips_when_ti_has_no_dag_version(session, supervisor_bu
27792839
supervisor.stdin.write.assert_not_called()
27802840

27812841

2842+
def _alive_triggerer_job(session) -> Job:
2843+
other_job = Job(job_type="TriggererJob")
2844+
other_job.latest_heartbeat = timezone.utcnow()
2845+
session.add(other_job)
2846+
session.flush()
2847+
return other_job
2848+
2849+
2850+
def test_load_triggers_releases_reassigned_trigger_without_user_action_cancel(session, supervisor_builder):
2851+
"""
2852+
A trigger whose row moved to another triggerer must be dropped locally, not queued
2853+
as a user-action cancel (which would fire ``on_kill()`` and cancel remote work the new
2854+
owner is still polling).
2855+
"""
2856+
trigger = TimeDeltaTrigger(datetime.timedelta(days=7))
2857+
_, _, trigger_orm, _ = create_trigger_in_db(session, trigger)
2858+
supervisor = supervisor_builder()
2859+
supervisor.running_triggers = {trigger_orm.id}
2860+
2861+
# Our heartbeat lapsed and another (alive) triggerer took the trigger over.
2862+
other_job = _alive_triggerer_job(session)
2863+
session.execute(update(Trigger).where(Trigger.id == trigger_orm.id).values(triggerer_id=other_job.id))
2864+
session.flush()
2865+
2866+
supervisor.load_triggers()
2867+
2868+
assert supervisor.cancelling_triggers == set()
2869+
assert supervisor.releasing_triggers == {trigger_orm.id}
2870+
2871+
2872+
def test_load_triggers_cancels_deleted_trigger_as_user_action(session, supervisor_builder):
2873+
"""A trigger whose row is gone (task left the deferred state) takes the user-action path."""
2874+
trigger = TimeDeltaTrigger(datetime.timedelta(days=7))
2875+
_, _, trigger_orm, task_instance = create_trigger_in_db(session, trigger)
2876+
supervisor = supervisor_builder()
2877+
supervisor.running_triggers = {trigger_orm.id}
2878+
2879+
session.execute(
2880+
update(TaskInstance)
2881+
.where(TaskInstance.id == task_instance.id)
2882+
.values(trigger_id=None, state="scheduled")
2883+
)
2884+
session.execute(delete(Trigger).where(Trigger.id == trigger_orm.id))
2885+
session.flush()
2886+
2887+
supervisor.load_triggers()
2888+
2889+
assert supervisor.cancelling_triggers == {trigger_orm.id}
2890+
assert supervisor.releasing_triggers == set()
2891+
2892+
2893+
def test_update_triggers_splits_cancel_set_by_row_existence(supervisor_builder, mocker):
2894+
supervisor = supervisor_builder()
2895+
supervisor.running_triggers = {1, 2, 3}
2896+
fetch_assignments = mocker.patch.object(
2897+
TriggerRunnerSupervisor, "fetch_trigger_assignments", autospec=True, return_value={2: 99}
2898+
)
2899+
2900+
supervisor.update_triggers({3})
2901+
2902+
fetch_assignments.assert_called_once_with(supervisor, {1, 2})
2903+
assert supervisor.releasing_triggers == {2}
2904+
assert supervisor.cancelling_triggers == {1}
2905+
2906+
# Already-classified triggers are not re-queried on the next loop.
2907+
supervisor.update_triggers({3})
2908+
fetch_assignments.assert_called_once()
2909+
2910+
2911+
def test_state_sync_sends_released_triggers_separately_from_cancels(supervisor_builder, mocker):
2912+
supervisor = supervisor_builder()
2913+
send_msg = mocker.patch.object(TriggerRunnerSupervisor, "send_msg", autospec=True)
2914+
log = MagicMock(spec=FilteringBoundLogger)
2915+
supervisor.running_triggers = {1, 2}
2916+
supervisor.cancelling_triggers = {1}
2917+
supervisor.releasing_triggers = {2}
2918+
2919+
supervisor._handle_request(messages.TriggerStateChanges(), log=log, req_id=1)
2920+
2921+
resp = send_msg.call_args.args[1]
2922+
assert isinstance(resp, messages.TriggerStateSync)
2923+
assert resp.to_cancel == {1}
2924+
assert resp.to_release == {2}
2925+
2926+
# The runner reporting them finished clears both tracking sets.
2927+
supervisor._handle_request(messages.TriggerStateChanges(finished=[1, 2]), log=log, req_id=2)
2928+
assert supervisor.cancelling_triggers == set()
2929+
assert supervisor.releasing_triggers == set()
2930+
assert supervisor.running_triggers == set()
2931+
2932+
27822933
class TestTriggererJobRunner:
27832934
@patch("airflow.jobs.triggerer_job_runner.stats.initialize")
27842935
@patch.object(TriggerRunnerSupervisor, "start")

0 commit comments

Comments
 (0)