The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(cron): _FireOwnership owns the combined cancel event; two handles, not three
kshitijk4poor8a6daa7702c9
diff --git a/cron/scheduler.py b/cron/scheduler.pyindex a67d3a475ad..17e0d934f71 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -2517,13 +2517,8 @@ def run_one_job(loop=loop,verbose=verbose,extra_prompt=extra_prompt,- fire_claim_lost=(- _CombinedCancelEvent(lost_ownership, cancel_event)- if cancel_event is not None- else lost_ownership- ),+ claim_lost=lost_ownership,transport_cancel=cancel_event,- sampled_claim_lost=lost_ownership,execution_token=execution_token))finally:with _running_lock:@@ -2622,26 +2617,33 @@ class _FireOwnership:"""Fire-claim ownership checks for one run (``owner`` is None when the job carries no claim)."""def __init__(- self, job: dict, fire_claim_lost: Optional[_CancelEventLike],- sampled_claim_lost: Optional[_CancelEventLike] = None,+ self, job: dict, claim_lost: Optional[_CancelEventLike] = None,+ transport_cancel: Optional[_CancelEventLike] = None,):self.job = job- self.fire_claim_lost = fire_claim_lost- # Latch a sampled miss on the raw ``lost_ownership`` event, never on the combined one:- # ``_CombinedCancelEvent.set()`` propagates into the caller's transport ``cancel_event``,- # which would mask the source and mutate an event this run does not own (#105861).- self.sampled_claim_lost = (- sampled_claim_lost if sampled_claim_lost is not None else fire_claim_lost)+ # Two handles: the heartbeat's raw ``lost_ownership`` event and the caller's transport+ # ``cancel_event``. A sampled miss latches on the raw one only — the combined view's+ # ``set()`` would propagate into the transport event this run does not own (#105861).+ self.claim_lost = claim_lost+ self.transport_cancel = transport_cancel+ # What ``run_job`` receives as its ``cancel_event``: either source cancels the run.+ self.cancel_event: Optional[_CancelEventLike] = (+ _CombinedCancelEvent(claim_lost, transport_cancel)+ if claim_lost is not None or transport_cancel is not None+ else None)claim = job.get("fire_claim")self.owner = str(claim.get("by") or "") if isinstance(claim, dict) else None+ def transport_cancelled(self) -> bool:+ return self.transport_cancel is not None and self.transport_cancel.is_set()+def side_effect_fence(self):if self.owner is None:return contextlib.nullcontext(True)return fire_claim_fence(self.job["id"], expected_owner=self.owner)def lost(self) -> bool:- if self.fire_claim_lost is not None and self.fire_claim_lost.is_set():+ if self.cancel_event is not None and self.cancel_event.is_set():return Trueif self.owner is None:return False@@ -2655,8 +2657,8 @@ class _FireOwnership:logger.debug("Job '%s': fire_claim ownership validation failed", self.job["id"], exc_info=True)return False- if self.sampled_claim_lost is not None:- self.sampled_claim_lost.set()+ if self.claim_lost is not None:+ self.claim_lost.set()return True@@ -2866,12 +2868,11 @@ def _deliver_crash_failure(def _run_one_job_body(job: dict, *, adapters=None, loop=None, verbose: bool = False,- extra_prompt: Optional[str] = None, fire_claim_lost: Optional[_CancelEventLike] = None,+ extra_prompt: Optional[str] = None, claim_lost: Optional[_CancelEventLike] = None,transport_cancel: Optional[_CancelEventLike] = None,- sampled_claim_lost: Optional[_CancelEventLike] = None,execution_token: Optional[object] = None,) -> bool:- fence = _FireOwnership(job, fire_claim_lost, sampled_claim_lost)+ fence = _FireOwnership(job, claim_lost, transport_cancel)fire_owner = fence.owner_side_effect_fence = fence.side_effect_fence_fire_claim_ownership_lost = fence.lost@@ -2955,8 +2956,8 @@ def _run_one_job_body("defer_agent_teardown": _deferred_agents,"extra_prompt": extra_prompt,"execution_id": execution_id}- if fire_claim_lost is not None:- _run_kwargs["cancel_event"] = fire_claim_lost+ if fence.cancel_event is not None:+ _run_kwargs["cancel_event"] = fence.cancel_eventtry:success, output, final_response, error = run_job(job, **_run_kwargs)except BaseException:@@ -2998,36 +2999,37 @@ def _run_one_job_body(_record_fire_ownership_lost(job["id"], fire_owner, execution_id)return True+ # Empty final_response is a soft failure so last_status is not "ok".+ if d.success and not final_response.strip():+ d.success = False+ d.error = "Agent completed but produced empty response (model error, timeout, or misconfiguration)"+if _fire_claim_ownership_lost():# #105861: the claim check is one sample; a miss AFTER a completed delivery must not# overwrite the ok status — fall through to _finish_completed_run, whose owner-fenced# mark_job_run is authoritative. An explicit transport cancel stays fail-closed.- transport_cancelled = transport_cancel is not None and transport_cancel.is_set()+ transport_cancelled = fence.transport_cancelled()if (d.successand d.delivery_attemptedand not d.delivery_error- and final_response.strip()and not transport_cancelled):logger.warning("Job '%s': fire claim ownership lost after successful delivery; ""recording the delivered run's terminal status",job["id"])+ elif transport_cancelled:+ logger.warning(+ "Job '%s': transport cancellation arrived during a successful delivery; "+ "keeping the interrupted terminal status",+ job["id"])+ _record_fire_ownership_lost(job["id"], fire_owner, execution_id)+ return Trueelse:- if transport_cancelled:- logger.warning(- "Job '%s': transport cancellation arrived during a successful delivery; "- "keeping the interrupted terminal status",- job["id"])_record_fire_ownership_lost(job["id"], fire_owner, execution_id)return True- # Empty final_response is a soft failure so last_status is not "ok".- if d.success and not final_response.strip():- d.success = False- d.error = "Agent completed but produced empty response (model error, timeout, or misconfiguration)"-if _consume_interrupted_flag(job["id"], execution_token):_finish_interrupted_run(job, execution_id, delivery_error)return Truediff --git a/tests/cron/test_script_claim_heartbeat.py b/tests/cron/test_script_claim_heartbeat.pyindex 854f0f4bf3e..fb5072504c6 100644--- a/tests/cron/test_script_claim_heartbeat.py+++ b/tests/cron/test_script_claim_heartbeat.py@@ -664,7 +664,7 @@ def test_repeated_heartbeat_errors_cancel_after_bounded_grace(monkeypatch):raise OSError("store unavailable")def run_body(_job, **kwargs):- assert kwargs["fire_claim_lost"].wait(timeout=0.5)+ assert kwargs["claim_lost"].wait(timeout=0.5)cancellation_after.append(time.monotonic() - last_confirmed_at[0])return Truediff --git a/tests/cron/test_shutdown_interrupt.py b/tests/cron/test_shutdown_interrupt.pyindex a8bb3bf28f1..940beebab62 100644--- a/tests/cron/test_shutdown_interrupt.py+++ b/tests/cron/test_shutdown_interrupt.py@@ -416,7 +416,10 @@ class TestCombinedCancelEvent:), patch.object(sched, "_run_one_job_body", return_value=True) as body:assert sched.run_one_job(job, cancel_event=external) is True- combined = body.call_args.kwargs["fire_claim_lost"]+ kwargs = body.call_args.kwargs+ assert kwargs["transport_cancel"] is external+ # What run_job receives: the ownership handle built from the two forwarded sources.+ combined = sched._FireOwnership(job, kwargs["claim_lost"], kwargs["transport_cancel"]).cancel_eventassert combined.is_set() is Falseexternal.set()assert combined.is_set() is True