The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): write a drained delivery's outcome back onto the run that queued it
Tekniume1de0c26653b
diff --git a/cron/delivery_outcome.py b/cron/delivery_outcome.pynew file mode 100644index 00000000000..31f27980907--- /dev/null+++ b/cron/delivery_outcome.py@@ -0,0 +1,94 @@+"""Write a queued cron delivery's terminal outcome back onto the run that queued it.++An agent run hands its send to ``cron.delivery_queue`` and books ``last_status =+"delivery_queued"`` / ledger ``delivery_outcome = "queued"``. Once a gateway drain sends,+refuses, suppresses or fences the send ``unknown``, the job record and the execution+ledger must carry the real result (main's inline ``ok``/``delivered`` and+``delivery_failed``/``failed`` + ``last_delivery_error``); otherwise ``hermes cron list``+says "delivery still in progress" forever and refused sends never surface.++Both sides call :func:`settle_queued_delivery`: the drain right after it terminalizes a+row, and the run right after its own bookkeeping (a drain can finish before the run's+``mark_job_run`` lands). Every write is fenced on the execution id, so the call is+idempotent and never rewrites a later run's status.+"""+from __future__ import annotations++import logging+from typing import Optional++logger = logging.getLogger(__name__)++# Queue terminal status -> ledger delivery_outcome. ``unknown`` (owner died mid-send, never+# retried) is surfaced as a failure: the user cannot be told the result arrived.+_LEDGER_OUTCOME = {+ "delivered": "delivered", "suppressed": "suppressed", "failed": "failed", "unknown": "failed",+}+++def _settle_job_record(job_id: str, execution_id: str, delivery_error: Optional[str]) -> bool:+ """Stamp the outcome onto the job only while *execution_id* is still its current run:+ the ledger's latest attempt for the job AND the job's latest recorded completion."""+ from cron.executions import latest_execution+ from cron.jobs import _with_job, save_jobs++ latest = latest_execution(job_id)+ if latest is None or latest.get("id") != execution_id:+ return False++ def apply(jobs, _i, job):+ completions = job.get("canonical_completions") or []+ if not completions or completions[-1] != execution_id:+ return False+ status = job.get("last_status")+ if status == "delivery_queued":+ status = "delivery_failed" if delivery_error else "ok"+ if (status, delivery_error) == (job.get("last_status"), job.get("last_delivery_error")):+ return True+ job["last_status"] = status+ job["last_delivery_error"] = delivery_error+ save_jobs(jobs)+ return True++ return bool(_with_job(job_id, apply, missing=False))+++def _terminal(execution_id: str) -> Optional[tuple[str, Optional[str]]]:+ """``(ledger_outcome, delivery_error)`` once the queue row is terminal, else None."""+ from cron.delivery_queue import get_status++ row = get_status(str(execution_id))+ if not row or row["status"] not in _LEDGER_OUTCOME:+ return None+ delivery_error = None+ if row["status"] in ("failed", "unknown"):+ delivery_error = str(row.get("error") or f"delivery {row['status']}")+ return _LEDGER_OUTCOME[row["status"]], delivery_error+++def settled_outcome(execution_id: str) -> Optional[str]:+ """The ledger outcome a drain already reached for *execution_id* (None while queued)."""+ terminal = _terminal(execution_id)+ return terminal[0] if terminal else None+++def settle_queued_delivery(job_id: Optional[str], execution_id: Optional[str]) -> bool:+ """Apply the queue's terminal outcome for *execution_id*; False while still in flight."""+ if not job_id or not execution_id:+ return False+ terminal = _terminal(str(execution_id))+ if terminal is None:+ return False+ from cron.executions import settle_delivery_outcome++ settle_delivery_outcome(str(execution_id), terminal[0])+ _settle_job_record(str(job_id), str(execution_id), terminal[1])+ return True+++def settle_quietly(job_id: Optional[str], execution_id: Optional[str]) -> None:+ """Bookkeeping failure must not undo a terminal at-most-once send or fail its run."""+ try:+ settle_queued_delivery(job_id, execution_id)+ except Exception:+ logger.warning("Cron delivery %s: outcome write-back failed", execution_id, exc_info=True)diff --git a/cron/delivery_queue.py b/cron/delivery_queue.pyindex 32848c2c0c4..12b220ded0c 100644--- a/cron/delivery_queue.py+++ b/cron/delivery_queue.py@@ -334,8 +334,11 @@ def drain()except BaseException as exc:error = f"{type(exc).__name__}: {exc}"- _finish(row["execution_id"], error=error,- suppressed=bool(row["job"].get("_notification_all_targets_suppressed")))+ if _finish(row["execution_id"], error=error,+ suppressed=bool(row["job"].get("_notification_all_targets_suppressed"))):+ from cron.delivery_outcome import settle_quietly++ settle_quietly(row["job"].get("id"), row["execution_id"])finally:with _lock:_ACTIVE_DELIVERIES.discard(row["execution_id"])diff --git a/cron/executions.py b/cron/executions.pyindex b6afa0d3797..682d77c86cc 100644--- a/cron/executions.py+++ b/cron/executions.py@@ -308,6 +308,22 @@ def finish_execution(return record+def settle_delivery_outcome(execution_id: str, outcome: str) -> bool:+ """Replace a terminal attempt's ``queued`` delivery outcome with the drain's real one.++ The only post-terminal rewrite the ledger allows: the attempt's status is untouched and+ only a ``queued`` handoff can settle, so a replay or a late caller is a no-op.+ """+ with _transaction() as conn:+ cur = conn.execute(+ """UPDATE executions SET delivery_outcome=?+ WHERE id=? AND delivery_outcome='queued'+ AND status IN ('completed','failed','unknown')""",+ (outcome, execution_id),+ )+ return cur.rowcount == 1++_OWNER_GONE_REASON = ("Scheduler restarted after this execution's owner exited before a durable ""terminal state; whether side effects ran is unknown."diff --git a/cron/scheduler.py b/cron/scheduler.pyindex 6a2018eddd5..1d193d1fd56 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -3293,11 +3293,18 @@ def _finish_completed_run(d: _RunDelivery, fire_owner: Optional[str], execution_incident_acked=d.incident_acked,success=d.success,)+ from cron.delivery_outcome import settle_quietly, settled_outcome+ if delivery_outcome == "queued":+ # A drain that already finished this send (cron/delivery_outcome.py) is the real outcome.+ delivery_outcome = settled_outcome(execution_id) or "queued"if delivery_outcome in ("delivered", "not_configured") and not d.success:# Failure ping left the process (or had a configured target): mark the incident alerted._mark_incident_alerted(d.failure_incident_id)finish_execution(execution_id, success=d.success, error=d.error, delivery_outcome=delivery_outcome)+ if job.get("last_delivery_queued"):+ # A drain that settled before this run's own bookkeeping landed found nothing to fence on.+ settle_quietly(job["id"], execution_id)journal.unlink(missing_ok=True)return Truediff --git a/cron/scheduler_authority.py b/cron/scheduler_authority.pyindex 7ee02b72847..0db6d1f467e 100644--- a/cron/scheduler_authority.py+++ b/cron/scheduler_authority.py@@ -125,6 +125,9 @@ def reconcile_pending(*, allow_connect=True):enqueue(params['request_id'], job, content, for_failure=not success)mark_job_run(job['id'], success, error, status='delivery_queued' if deliver else None,execution_id=params['request_id'])+ if deliver:+ from cron.delivery_outcome import settle_quietly+ settle_quietly(job['id'], params['request_id'])journal.unlink(missing_ok=True)except Exception:logging.getLogger(__name__).warning('Cron receipt recovery deferred: %s', journal, exc_info=True)diff --git a/tests/cron/test_cron_failure_deliver.py b/tests/cron/test_cron_failure_deliver.pyindex 560367c32e2..1c043ce3d25 100644--- a/tests/cron/test_cron_failure_deliver.py+++ b/tests/cron/test_cron_failure_deliver.py@@ -108,6 +108,13 @@ def run_env(monkeypatch, tmp_path):s, "finish_execution",lambda *a, **kw: state["finished"].append((a, kw)),)+ # The drain settles a queued outcome in the (stubbed) ledger: record it the same way.+ from cron import executions+ monkeypatch.setattr(+ executions, "settle_delivery_outcome",+ lambda execution_id, outcome: state["finished"].append(+ ((execution_id,), {"delivery_outcome": outcome})) or True,+ )# No durable incident store in play: never acked, no id.monkeypatch.setattr(s, "_upsert_incident_for_failure", lambda *_a, **_kw: (False, None)@@ -422,6 +429,7 @@ class TestOutcomeBookkeeping:run_env["drain"](for_failure=True)assert [c["chat_id"] for c in run_env["send"]] == ["D0OPS"]assert "failed" in run_env["send"][0]["message"].lower()+ assert self._outcome(run_env) == ("delivered" if transport_success else "failed")assert alerted == (["inc-b1"] if transport_success else []), ("only a delivered failure ping may mark the incident alerted")@@ -439,6 +447,7 @@ class TestOutcomeBookkeeping:assert self._outcome(run_env) == "queued"run_env["drain"](for_failure=False)assert [c["chat_id"] for c in run_env["send"]] == ["D0MAIN"]+ assert self._outcome(run_env) == "delivered"class TestPreflightAndDashboardLanes:diff --git a/tests/cron/test_delivery_outcome_writeback.py b/tests/cron/test_delivery_outcome_writeback.pynew file mode 100644index 00000000000..0f9092f84bb--- /dev/null+++ b/tests/cron/test_delivery_outcome_writeback.py@@ -0,0 +1,57 @@+"""A queued cron delivery's real outcome is written back onto the run that queued it.++The in-process run hands its send to the durable queue and books ``delivery_queued`` /+ledger ``queued``. Once a gateway drain sends or refuses it, the job and the ledger must+say what actually happened (main's inline ``ok``/``delivered`` and ``delivery_failed``/+``failed`` + error) — including when the drain wins the race against the run's own+bookkeeping write.+"""+import pytest++from cron import executions, jobs, scheduler+from gateway.config import GatewayConfig, Platform, PlatformConfig++[email protected]("drain_timing", ["after_run", "before_bookkeeping"])[email protected]("transport_ok", [True, False], ids=["sent", "refused"])+def test_drained_delivery_outcome_is_written_back(tmp_path, monkeypatch, transport_ok, drain_timing):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ config = GatewayConfig()+ config.platforms[Platform.TELEGRAM] = PlatformConfig(enabled=True)+ monkeypatch.setattr("gateway.config.load_gateway_config", lambda: config)+ sent = []++ async def send(platform, pconfig, chat_id, text, **kwargs):+ sent.append(text)+ return {"success": transport_ok, "message_id": "r",+ "error": None if transport_ok else "transport refused"}++ monkeypatch.setattr("tools.send_message_tool._send_to_platform", send)+ monkeypatch.setattr(scheduler, "run_job", lambda job, **kw: (True, "raw", "the result", None))+ if drain_timing == "before_bookkeeping":+ from cron import delivery_queue+ real_enqueue = delivery_queue.enqueue++ def enqueue_then_drain(*args, **kwargs):+ queued = real_enqueue(*args, **kwargs)+ assert scheduler.drain_delivery_queue({}, None) == 1+ return queued++ monkeypatch.setattr(delivery_queue, "enqueue", enqueue_then_drain)++ job = jobs.create_job(prompt="p", schedule="every 1h", deliver="telegram:fixture")+ scheduler.run_one_job(job)+ if drain_timing == "after_run":+ assert sent == [], "the run only queues; the gateway drain sends"+ assert scheduler.drain_delivery_queue({}, None) == 1++ assert len(sent) == 1+ saved = jobs.get_job(job["id"])+ row = executions.latest_execution(job["id"])+ if transport_ok:+ assert (saved["last_status"], saved["last_delivery_error"]) == ("ok", None)+ assert row["delivery_outcome"] == "delivered"+ else:+ assert saved["last_status"] == "delivery_failed"+ assert "transport refused" in saved["last_delivery_error"]+ assert row["delivery_outcome"] == "failed"diff --git a/tests/cron/test_fire_claim_lost_after_delivery.py b/tests/cron/test_fire_claim_lost_after_delivery.pyindex da6b18fe2e7..77495ac737b 100644--- a/tests/cron/test_fire_claim_lost_after_delivery.py+++ b/tests/cron/test_fire_claim_lost_after_delivery.py@@ -89,13 +89,14 @@ def _drive(monkeypatch, *, run_result, samples_before_miss):hb.arm()return run_result- def fake_deliver(execution_id, job, content, **kwargs):+ def fake_deliver(job, content, **kwargs):delivered.append(content)- return {"status": "pending"}+ return Nonemonkeypatch.setattr(sched, "heartbeat_fire_claim", hb)monkeypatch.setattr(sched, "run_job", fake_run_job)- monkeypatch.setattr("cron.delivery_queue.enqueue", fake_deliver)+ # The run queues its notice durably; the gateway drain sends it through _deliver_result.+ monkeypatch.setattr(sched, "_deliver_result", fake_deliver)return sched, job, hb, delivered@@ -105,8 +106,7 @@ _REAL_ERROR = "the real error text the failure path recorded"@pytest.mark.parametrize("success, run_result, expected_status, expected_error",[- # A queued (durable-queue) success books ``delivery_queued`` until the gateway drains it.- (True, (True, "output text", "the report", None), "delivery_queued", None),+ (True, (True, "output text", "the report", None), "ok", None),(False, (False, "output text", "", _REAL_ERROR), "error", _REAL_ERROR),],ids=["delivered-ok", "delivered-failure-notice"],@@ -123,6 +123,7 @@ def test_delivered_run_keeps_its_terminal_status_when_claim_sample_misses_after_cancel = threading.Event()assert sched.run_one_job(job, cancel_event=cancel) is True+ assert sched.drain_delivery_queue({}, None) == 1assert len(delivered) == 1, "the notice must have left the process"if success:@@ -157,6 +158,7 @@ def test_transport_cancel_during_delivery_stays_fail_closed(temp_home, monkeypatmonkeypatch.setattr("cron.delivery_queue.enqueue", deliver_then_cancel)assert sched.run_one_job(job, cancel_event=cancel) is True+ assert sched.drain_delivery_queue({}, None) == 1assert delivered == ["the report"], "the notice had already left the process"assert hb.missed == 0, "the sampled claim never missed — only the transport event fired"@@ -227,8 +229,7 @@ def _drive_heartbeat_thread(monkeypatch, *, misses, steal=False):monkeypatch.setattr(sched, "_FIRE_CLAIM_MISS_CONFIRM_SECONDS", 0.01, raising=False)monkeypatch.setattr(sched, "heartbeat_fire_claim", hb)monkeypatch.setattr(sched, "run_job", fake_run_job)- monkeypatch.setattr("cron.delivery_queue.enqueue",- lambda execution_id, job, content, **kw: (delivered.append(content), {"status": "pending"})[1])+ monkeypatch.setattr(sched, "_deliver_result", lambda job, content, **kw: delivered.append(content))return sched, job, hb, delivered, run_cancel@@ -243,12 +244,13 @@ def test_heartbeat_miss_mid_run_keeps_completed_run(temp_home, monkeypatch, misssched, job, hb, delivered, run_cancel = _drive_heartbeat_thread(monkeypatch, misses=misses)assert sched.run_one_job(job) is True+ assert sched.drain_delivery_queue({}, None) == 1assert hb.missed == missesassert run_cancel == [latched], "only a confirmed miss reaches the run's cancel event"assert delivered == ["the report"]record = get_job(job["id"])- assert record["last_status"] == "delivery_queued" # queued success, never the interrupted error+ assert record["last_status"] == "ok"assert record["last_error"] is Noneassert get_execution(job["execution_id"])["status"] == "completed"diff --git a/tests/cron/test_script_claim_heartbeat.py b/tests/cron/test_script_claim_heartbeat.pyindex 776891ae503..9e9fc088d4c 100644--- a/tests/cron/test_script_claim_heartbeat.py+++ b/tests/cron/test_script_claim_heartbeat.py@@ -379,10 +379,19 @@ def _run_claimed_job_with_mid_run_action(raise crashreturn True, "saved output", "D1 is promoting", None- # A completed agent run with an execution id hands its notice to the durable delivery queue- # (drained by the gateway), never to an inline ``_deliver_result``; the enqueue IS the- # delivery. A crash still alerts inline, so both doors are stubbed.- delivered = MagicMock(return_value={"status": "queued"})+ # A completed agent run hands its notice to the durable delivery queue; a gateway drain that+ # wins the race against the run's bookkeeping sends it through ``_deliver_result``. A crash+ # alerts inline through the same stubbed door.+ from cron import delivery_queue+ monkeypatch.setattr(delivery_queue, "DELIVERY_DB", tmp_path / "cron" / "deliveries.db")+ real_enqueue = delivery_queue.enqueue++ def _enqueue_then_drain(*args, **kwargs):+ queued = real_enqueue(*args, **kwargs)+ assert scheduler.drain_delivery_queue({}, None) == 1+ return queued++ delivered = MagicMock(side_effect=_enqueue_then_drain)monkeypatch.setattr(scheduler, "_deliver_result", MagicMock(return_value=None))finished = MagicMock()monkeypatch.setattr(scheduler, "_RUN_CLAIM_HEARTBEAT_SECONDS", 0.05)@@ -421,7 +430,7 @@ def test_self_removed_job_still_delivers_after_post_removal_heartbeat(tmp_path,delivered.assert_called_once()finished.assert_called_once_with("self-removal-heartbeat-execution",- success=True, error=None, delivery_outcome="queued")+ success=True, error=None, delivery_outcome="delivered")with jobs.use_cron_store(tmp_path):assert jobs.load_jobs() == []diff --git a/tests/cron/test_warning_execution_outcome.py b/tests/cron/test_warning_execution_outcome.pyindex 7bd8c373260..9e00bec96b0 100644--- a/tests/cron/test_warning_execution_outcome.py+++ b/tests/cron/test_warning_execution_outcome.py@@ -67,11 +67,11 @@ def test_real_run_ledger_and_incident_match_actual_presentation(tmp_path, monkeyassert scheduler.drain_delivery_queue({}, None) == 1(queued,) = delivery_queue_rows()assert queued["status"] == ("suppressed" if expected_suppression else "delivered")- else:- assert row["delivery_outcome"] == ("suppressed" if expected_suppression else "delivered")+ row = executions.latest_execution(job["id"]) # the drain writes its outcome backassert len(sent) == (0 if expected_suppression else 1)+ assert row["delivery_outcome"] == ("suppressed" if expected_suppression else "delivered")saved = jobs.get_job(job["id"])- assert saved["last_status"] == ("error" if mode != "success" else "delivery_queued" if queued_lane else "ok")+ assert saved["last_status"] == ("ok" if mode == "success" else "error")if mode != "success":assert "isolated provider failure" in saved["last_error"]incident = next(i for i in incidents.list_incidents() if i["job_id"] == job["id"])