150150tracer = 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 )
0 commit comments