The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): a delivered run keeps its ok status when the fire claim sample misses after delivery (#105861)
finn763132a181d805a
diff --git a/cron/scheduler.py b/cron/scheduler.pyindex e64e86fe49c..98e9e14566e 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -2522,6 +2522,8 @@ def run_one_job(if cancel_event is not Noneelse lost_ownership),+ transport_cancel=cancel_event,+ sampled_claim_lost=lost_ownership,execution_token=execution_token))finally:with _running_lock:@@ -2619,9 +2621,21 @@ class _FireClaimLostDuringSideEffect(Exception):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]):+ def __init__(+ self, job: dict, fire_claim_lost: Optional[_CancelEventLike],+ sampled_claim_lost: Optional[_CancelEventLike] = None,+ ):self.job = jobself.fire_claim_lost = fire_claim_lost+ # ``fire_claim_lost`` may be a ``_CombinedCancelEvent``, whose ``set()`` propagates into+ # EVERY source it ORs — including the caller's transport ``cancel_event`` (dashboard drain).+ # Latching a sampled loss through that wrapper therefore made the transport event read as+ # cancelled: the delivered-run exemption at the call site became unreachable, and the drain+ # event the caller owns was mutated by this run's bookkeeping. Latch the sampled source+ # itself; the combined still reports it through ``is_set()``, so an in-flight agent is+ # interrupted exactly as before (#105861 review).+ self.sampled_claim_lost = (+ sampled_claim_lost if sampled_claim_lost is not None else fire_claim_lost)claim = job.get("fire_claim")self.owner = str(claim.get("by") or "") if isinstance(claim, dict) else None@@ -2645,8 +2659,8 @@ class _FireOwnership:logger.debug("Job '%s': fire_claim ownership validation failed", self.job["id"], exc_info=True)return False- if self.fire_claim_lost is not None:- self.fire_claim_lost.set()+ if self.sampled_claim_lost is not None:+ self.sampled_claim_lost.set()return True@@ -2857,9 +2871,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,+ transport_cancel: Optional[_CancelEventLike] = None,+ sampled_claim_lost: Optional[_CancelEventLike] = None,execution_token: Optional[object] = None,) -> bool:- fence = _FireOwnership(job, fire_claim_lost)+ fence = _FireOwnership(job, fire_claim_lost, sampled_claim_lost)fire_owner = fence.owner_side_effect_fence = fence.side_effect_fence_fire_claim_ownership_lost = fence.lost@@ -2981,10 +2997,46 @@ def _run_one_job_body(# Every path must tear down deferred agent(s) so they never leak subprocesses/clients._teardown_deferred()- if d.side_effect_ownership_lost or _fire_claim_ownership_lost():+ if d.side_effect_ownership_lost:+ # The claim died inside a side-effect fence: the side effect did NOT complete._record_fire_ownership_lost(job["id"], fire_owner, execution_id)return True+ if _fire_claim_ownership_lost():+ # #105861: that check is one sample of the claim, and a sample that misses AFTER the+ # notice already left the process used to overwrite a delivered success with an error+ # (the operator's health watchdog then alerted on every tick for a job that was+ # working). A completed delivery is this run's terminal outcome, so warn and fall+ # through to _finish_completed_run: its owner-fenced mark_job_run is the authoritative+ # claim check — it records ok while the claim is still held and records nothing when it+ # really is gone, so a genuine loss is still not papered over. A run that did not+ # deliver (failed / never attempted) keeps the ownership-loss error below.+ # #105861 review: ``fire_claim_lost`` ORs the sampled claim with the transport-level+ # ``cancel_event`` (dashboard drain / shutdown), and the flag alone cannot tell which one+ # fired — so the exemption is scoped to the sampled path only. An explicit transport+ # cancel is a cooperative stop signal the provider relies on, not a sampling artefact:+ # it stays fail-closed and records the interrupted run.+ transport_cancelled = transport_cancel is not None and transport_cancel.is_set()+ if (+ d.success+ and d.delivery_attempted+ and 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"])+ else:+ 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 = Falsediff --git a/tests/cron/test_fire_claim_lost_after_delivery.py b/tests/cron/test_fire_claim_lost_after_delivery.pynew file mode 100644index 00000000000..171c354f06f--- /dev/null+++ b/tests/cron/test_fire_claim_lost_after_delivery.py@@ -0,0 +1,246 @@+"""#105861: a fire-claim that only *reads* as lost AFTER a run delivered must not overwrite+the delivered success with an error.++`_FireOwnership.lost()` samples the claim from the store once. In the reported incidents that+sample missed (a run's own delivery holds the per-job fence past `_JOBS_LOCK_TIMEOUT_SECONDS`,+and jobs.json is rewritten by two processes per run), the run wrapper then recorded+`last_status: error` — and the operator's health watchdog alerted on every tick for a job whose+output had already reached the channel.++Suggested fix #1 (the smallest one that closes it): when the run's delivery actually completed,+the sampled claim loss is bookkeeping, not a delivery failure — warn and fall through to the+owner-fenced terminal write in `_finish_completed_run`, which is the authoritative claim check+(it records `ok` only while the claim is still held, and records nothing when it really is gone).++These drive the real store (``jobs.json`` under a temp HERMES_HOME) so the assertion is the+actual on-disk ``last_status`` the health watchdog reads, not a mock's call list.+"""++import logging++import pytest+++def temp_home(tmp_path, monkeypatch):+ """Isolated HERMES_HOME so jobs.json/executions don't touch the real store."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ return tmp_path++[email protected](autouse=True)+def _clean_running_state():+ import cron.scheduler as sched++ sched._running_job_ids.clear()+ sched._running_fire_owners.clear()+ sched._interrupted_job_ids.clear()+ yield+ sched._running_job_ids.clear()+ sched._running_fire_owners.clear()+ sched._interrupted_job_ids.clear()+++class _SampledHeartbeat:+ """The real ``heartbeat_fire_claim``, with exactly ONE armed sample missing.++ That single miss is the whole bug: the claim is sampled once, a miss flips the run's+ ownership flag permanently, and the *next* heartbeat (inside+ ``_record_fire_ownership_lost``) confirms the claim is still ours — which is how a+ delivered run ended up recorded as ``error``.+ """++ def __init__(self, real, skip_samples: int):+ self._real = real+ self._skip = skip_samples+ self._armed = False+ self._seen = 0+ self.missed = 0++ def __call__(self, job_id, *, expected_owner):+ if self._armed:+ self._seen += 1+ if self._seen > self._skip:+ self._armed = False+ self.missed += 1+ return False+ return self._real(job_id, expected_owner=expected_owner)++ def arm(self):+ """Miss on the ``skip_samples + 1``-th sample taken from here on."""+ self._seen = 0+ self._armed = True+++def _claimed_job():+ """A real recurring job record holding a live fire claim (as a firing tick has)."""+ from cron.jobs import claim_job_for_fire, create_job, get_job++ job = create_job(prompt="x", schedule="every 5m", name="105861")+ assert claim_job_for_fire(job["id"]) is True+ job = get_job(job["id"])+ assert isinstance(job.get("fire_claim"), dict) and job["fire_claim"].get("by")+ return job+++def _drive(monkeypatch, *, final_response, deliver, miss_at_sample):+ """Run one job through run_one_job with the sampled-heartbeat harness.++ The claim is sampled once after ``run_job`` returns (the pre-delivery check), once again+ just before the delivery side effect, and once after it (the post-delivery check that the+ incidents tripped on). ``miss_at_sample`` picks which of those samples misses.+ """+ import cron.scheduler as sched++ job = _claimed_job()+ hb = _SampledHeartbeat(sched.heartbeat_fire_claim, skip_samples=miss_at_sample)+ delivered = []++ def fake_run_job(job, **kwargs):+ hb.arm()+ return (True, "output text", final_response, None)++ def fake_deliver(job, content, **kwargs):+ delivered.append(content)+ return deliver++ monkeypatch.setattr(sched, "heartbeat_fire_claim", hb)+ monkeypatch.setattr(sched, "run_job", fake_run_job)+ monkeypatch.setattr(sched, "_deliver_result", fake_deliver)+ return sched, job, hb, delivered+++def test_delivered_run_stays_ok_when_claim_sample_misses_after_delivery(+ temp_home, monkeypatch, caplog,+):+ """① Delivery completed, then the claim sample missed → last_status stays ok + warning.++ Sample 1 is the pre-delivery check, sample 2 the one guarding the side effect; the third+ (post-delivery) is the one the reported incidents hit.+ """+ from cron.jobs import get_job++ sched, job, hb, delivered = _drive(+ monkeypatch, final_response="the report", deliver=None, miss_at_sample=2)++ with caplog.at_level(logging.WARNING):+ assert sched.run_one_job(job) is True++ assert delivered == ["the report"], "the notice must have left the process"+ assert hb.missed == 1, "exactly the post-delivery sample missed"+ record = get_job(job["id"])+ assert record["last_status"] == "ok"+ assert record["last_error"] is None+ assert record["failure_streak"] == 0+ warnings = " | ".join(r.getMessage().lower() for r in caplog.records)+ assert "ownership lost" in warnings and "deliver" in warnings+++def test_claim_lost_during_delivery_still_records_error(temp_home, monkeypatch):+ """②a A delivery that FAILED, then a lost claim → error (the protection must not weaken)."""+ from cron.jobs import get_job++ sched, job, _hb, delivered = _drive(+ monkeypatch, final_response="the report", deliver="send failed: 502", miss_at_sample=2)++ assert sched.run_one_job(job) is True++ assert delivered == ["the report"]+ record = get_job(job["id"])+ assert record["last_status"] == "error"+ assert record["last_error"] == sched._OWNERSHIP_LOST_INTERRUPTED+++def test_claim_lost_with_delivery_never_attempted_still_records_error(temp_home, monkeypatch):+ """②b A SILENT run delivers nothing, then a lost claim → error, not a delivered-ok.++ No delivery means no delivery phase to guard: sample 2 here is the post-delivery check.+ """+ import cron.scheduler as sched+ from cron.jobs import get_job++ sched, job, _hb, delivered = _drive(+ monkeypatch, final_response=sched.SILENT_MARKER, deliver=None, miss_at_sample=1)++ assert sched.run_one_job(job) is True++ assert delivered == [], "a SILENT run must not deliver"+ record = get_job(job["id"])+ assert record["last_status"] == "error"+ assert record["last_error"] == sched._OWNERSHIP_LOST_INTERRUPTED+++def test_claim_lost_before_delivery_still_records_error(temp_home, monkeypatch):+ """③ A claim sampled as lost before the side effect → error, delivery untouched."""+ from cron.jobs import get_job++ sched, job, _hb, delivered = _drive(+ monkeypatch, final_response="the report", deliver=None, miss_at_sample=0)++ assert sched.run_one_job(job) is True++ assert delivered == [], "a run that lost its claim must not deliver"+ record = get_job(job["id"])+ assert record["last_status"] == "error"+ assert record["last_error"] == sched._OWNERSHIP_LOST_INTERRUPTED+++def test_transport_cancel_during_delivery_stays_fail_closed(temp_home, monkeypatch):+ """④ The transport cancel is an explicit stop signal, not a sampled miss → still interrupted.++ ``fire_claim_lost`` ORs the sampled claim with the transport-level ``cancel_event``, so the+ delivered-success exemption must not swallow a drain that arrived while the notice was being+ sent: the run's provider relies on that cancellation being fail-closed.+ """+ import threading++ from cron.jobs import get_job++ sched, job, hb, delivered = _drive(+ monkeypatch, final_response="the report", deliver=None, miss_at_sample=99)+ cancel = threading.Event()+ deliver_result = sched._deliver_result++ def deliver_then_cancel(job, content, **kwargs):+ outcome = deliver_result(job, content, **kwargs)+ cancel.set()+ return outcome++ monkeypatch.setattr(sched, "_deliver_result", deliver_then_cancel)++ assert sched.run_one_job(job, cancel_event=cancel) is True++ assert delivered == ["the report"], "the notice had already left the process"+ assert hb.missed == 0, "the sampled claim never missed — only the transport event fired"+ record = get_job(job["id"])+ assert record["last_status"] == "error"+ assert record["last_error"] == sched._OWNERSHIP_LOST_INTERRUPTED+++def test_sampled_miss_leaves_an_idle_transport_event_alone(temp_home, monkeypatch):+ """⑤ A sampled miss with an (unset) transport cancel supplied → the run's own loss latch+ must not read as a transport cancellation, so the delivered run stays ok.++ ``_FireOwnership.lost()`` latches a sampled loss by calling ``set()`` on ``fire_claim_lost``.+ With a transport ``cancel_event`` in play that object is ``_CombinedCancelEvent(lost_ownership,+ cancel_event)``, and its ``set()`` sets every source — so the transport event read as cancelled+ and the delivered-run exemption was skipped, recording the same false interrupted error the+ issue reports. The latch has to carry the cancellation source's identity.+ """+ import threading++ from cron.jobs import get_job++ sched, job, hb, delivered = _drive(+ monkeypatch, final_response="the report", deliver=None, miss_at_sample=2)+ cancel = threading.Event()++ assert sched.run_one_job(job, cancel_event=cancel) is True++ assert delivered == ["the report"], "the notice had already left the process"+ assert hb.missed == 1, "exactly the post-delivery sample missed"+ assert cancel.is_set() is False, "the run's loss latch must not cancel the caller's transport"+ record = get_job(job["id"])+ assert record["last_status"] == "ok"+ assert record["last_error"] is None+ assert record["failure_streak"] == 0