Skip to content

The agent that grows with you

fix(cron): publish the canonical delivery row under the fire-claim fence

Teknium7e8e321ebda0
diff --git a/cron/scheduler.py b/cron/scheduler.py
index c10f7a89ae5..5dff45b87db 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -3149,9 +3149,14 @@ def _save_compose_deliver(
queued_job = dict(job)
if d.failure_incident_id:
queued_job["_failure_incident_id"] = d.failure_incident_id
- queued = enqueue(execution_id, queued_job, deliver_content, for_failure=not d.success)
- # The queue owns this send even if subsequent bookkeeping fails.
- d.delivery_attempted = True
+ # The queue row IS the send: publish it under the same fence as a direct send, so a claim
+ # stolen after the lost() sample above cannot leave this stale fire's notice queued.
+ with fence.side_effect_fence() as owns_delivery:
+ if not owns_delivery:
+ raise _FireClaimLostDuringSideEffect
+ queued = enqueue(execution_id, queued_job, deliver_content, for_failure=not d.success)
+ # The queue owns this send even if subsequent bookkeeping fails.
+ d.delivery_attempted = True
job['last_delivery_queued'] = {'canonical': {'status': queued['status'], 'execution_id': execution_id}}
return
d.unresolved_origin = (
diff --git a/tests/cron/test_queued_delivery_fencing.py b/tests/cron/test_queued_delivery_fencing.py
new file mode 100644
index 00000000000..4dabc47de75
--- /dev/null
+++ b/tests/cron/test_queued_delivery_fencing.py
@@ -0,0 +1,26 @@
+"""The canonical delivery queue row is the cron run's send: it obeys the same fire-claim fence,
+receipt and settlement rules as a direct send."""
+from cron import delivery_queue, executions, jobs, scheduler
+
+
+def test_claim_stolen_after_the_ownership_sample_queues_no_ghost_send(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setattr(scheduler, "run_job", lambda job, **kw: (True, "raw", "the result", None))
+ job = jobs.create_job(prompt="p", schedule="every 1h", deliver="telegram:fixture")
+ fire = jobs.claim_job_for_fire(job["id"], return_job=True, force=True)
+ samples = []
+ real_lost = scheduler._FireOwnership.lost
+
+ def stolen_after_second_sample(self):
+ verdict = real_lost(self)
+ samples.append(verdict)
+ if len(samples) == 2: # _save_compose_deliver's pre-send sample: a replacement wins now
+ jobs.update_job(job["id"], {"fire_claim": dict(fire["fire_claim"], by="replacement")})
+ return verdict
+
+ monkeypatch.setattr(scheduler._FireOwnership, "lost", stolen_after_second_sample)
+ scheduler.run_one_job(fire)
+ execution = executions.latest_execution(job["id"])
+ assert samples[:2] == [False, False]
+ assert delivery_queue.get_status(execution["id"]) is None
+ assert execution["status"] == "failed"