The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
[verified] fix(cron): harden gateway restart handoff
Brooklyn Nicholson29e5172487c1
diff --git a/cron/delivery_queue.py b/cron/delivery_queue.pyindex a7dbc8eea28..99757f7cdff 100644--- a/cron/delivery_queue.py+++ b/cron/delivery_queue.py@@ -27,6 +27,34 @@ _PROCESS_ID = uuid.uuid4().hex_lock = threading.RLock()_ACTIVE_DELIVERIES: set[str] = set()_TERMINAL = ("delivered", "failed", "unknown")+MAX_TERMINAL_DELIVERIES = 1000+++def _prune_terminal_unlocked(conn: sqlite3.Connection) -> None:+ """Redact terminal payloads and retain only bounded outcome metadata."""+ conn.execute(+ """UPDATE deliveries SET job_json='{}', content=''+ WHERE status IN ('delivered','failed','unknown')+ AND (job_json != '{}' OR content != '')"""+ )+ keep = max(0, int(MAX_TERMINAL_DELIVERIES))+ terminal_count = int(+ conn.execute(+ "SELECT COUNT(*) FROM deliveries "+ "WHERE status IN ('delivered','failed','unknown')"+ ).fetchone()[0]+ )+ excess = terminal_count - keep+ if excess > 0:+ conn.execute(+ """DELETE FROM deliveries WHERE execution_id IN (+ SELECT execution_id FROM deliveries+ WHERE status IN ('delivered','failed','unknown')+ ORDER BY finished_at, created_at, execution_id+ LIMIT ?+ )""",+ (excess,),+ )def _path() -> Path:@@ -53,6 +81,7 @@ def _transaction() -> Iterator[sqlite3.Connection]:execution_id TEXT PRIMARY KEY,job_json TEXT NOT NULL,content TEXT NOT NULL,+ for_failure INTEGER NOT NULL DEFAULT 0,status TEXT NOT NULL CHECK(status IN('pending','delivering','delivered','failed','unknown')),owner_process_id TEXT,@@ -63,7 +92,16 @@ def _transaction() -> Iterator[sqlite3.Connection]:error TEXT)""")+ columns = {+ str(row[1]) for row in conn.execute("PRAGMA table_info(deliveries)")+ }+ if "for_failure" not in columns:+ conn.execute(+ "ALTER TABLE deliveries "+ "ADD COLUMN for_failure INTEGER NOT NULL DEFAULT 0"+ )with conn:+ _prune_terminal_unlocked(conn)yield connfinally:conn.close()@@ -91,17 +129,24 @@ def _owner_is_live(pid: int, started_at: Optional[int]) -> bool:return _process_start_time(pid) == started_at-def enqueue(execution_id: str, job: dict, content: str) -> dict:+def enqueue(+ execution_id: str,+ job: dict,+ content: str,+ *,+ for_failure: bool = False,+) -> dict:"""Persist one idempotent delivery request before the worker waits."""with _transaction() as conn:conn.execute("""INSERT OR IGNORE INTO deliveries- (execution_id, job_json, content, status, created_at)- VALUES (?, ?, ?, 'pending', ?)""",+ (execution_id, job_json, content, for_failure, status, created_at)+ VALUES (?, ?, ?, ?, 'pending', ?)""",(str(execution_id),json.dumps(job, ensure_ascii=False, sort_keys=True),str(content),+ int(bool(for_failure)),_hermes_now().isoformat(),),)@@ -163,6 +208,7 @@ def _finish(execution_id: str, *, error: Optional[str]) -> bool:os.getpid(),),)+ _prune_terminal_unlocked(conn)return cur.rowcount == 1@@ -198,10 +244,13 @@ def recover_abandoned() -> int:),)changed += cur.rowcount+ _prune_terminal_unlocked(conn)return changed-def drain(send: Callable[[dict, str], Optional[str]], *, limit: int = 20) -> int:+def drain(+ send: Callable[[dict, str, bool], Optional[str]], *, limit: int = 20+) -> int:"""Deliver pending rows through *send*, terminalizing every claimed row."""recover_abandoned()processed = 0@@ -213,7 +262,9 @@ def drain(send: Callable[[dict, str], Optional[str]], *, limit: int = 20) -> int_ACTIVE_DELIVERIES.add(row["execution_id"])try:try:- error = send(row["job"], row["content"])+ error = send(+ row["job"], row["content"], bool(row["for_failure"])+ )except BaseException as exc:error = f"{type(exc).__name__}: {exc}"_finish(row["execution_id"], error=error)@@ -229,10 +280,11 @@ def enqueue_and_wait(job: dict,content: str,*,+ for_failure: bool = False,timeout: Optional[float] = None,) -> Optional[str]:"""Queue delivery and wait for a gateway's terminal at-most-once outcome."""- enqueue(execution_id, job, content)+ enqueue(execution_id, job, content, for_failure=for_failure)deadline = None if timeout is None else time.monotonic() + timeoutwhile deadline is None or time.monotonic() < deadline:row = get_status(execution_id)diff --git a/cron/executions.py b/cron/executions.pyindex d05afc2decc..9cf204e559d 100644--- a/cron/executions.py+++ b/cron/executions.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport osimport sqlite3import threading+import timeimport uuidfrom contextlib import contextmanagerfrom typing import Any, Dict, Iterator, List, Optional@@ -22,6 +23,7 @@ from hermes_time import now as _hermes_now# profile's execution records into the import-time home.EXECUTIONS_FILE: Optional[Path] = NoneMAX_TERMINAL_EXECUTIONS = 1000+HANDOFF_ADOPTION_GRACE_SECONDS = 30.0_TERMINAL_STATES = ("completed", "failed", "unknown")_lock = threading.RLock()_PROCESS_ID = uuid.uuid4().hex@@ -52,12 +54,26 @@ def _initialize_schema(conn: sqlite3.Connection) -> None:process_started_at INTEGER,status TEXT NOT NULL CHECK(status IN('claimed','running','completed','failed','unknown')),+ handoff_pending INTEGER NOT NULL DEFAULT 0,+ handoff_started_at REAL,claimed_at TEXT NOT NULL,started_at TEXT,finished_at TEXT,error TEXT)""")+ columns = {+ str(row[1]) for row in conn.execute("PRAGMA table_info(executions)")+ }+ if "handoff_pending" not in columns:+ conn.execute(+ "ALTER TABLE executions "+ "ADD COLUMN handoff_pending INTEGER NOT NULL DEFAULT 0"+ )+ if "handoff_started_at" not in columns:+ conn.execute(+ "ALTER TABLE executions ADD COLUMN handoff_started_at REAL"+ )conn.execute("CREATE INDEX IF NOT EXISTS idx_executions_job_claimed ""ON executions(job_id, claimed_at DESC, id DESC)"@@ -160,6 +176,25 @@ def create_execution(job_id: str, *, source: str) -> Dict[str, Any]:return record # type: ignore[return-value]+def mark_execution_handoff_pending(execution_id: str) -> Optional[Dict[str, Any]]:+ """Fence restart recovery while an external worker is adopting a claim."""+ with _transaction() as conn:+ cur = conn.execute(+ """UPDATE executions+ SET handoff_pending=1, handoff_started_at=?+ WHERE id=? AND status='claimed'+ AND process_id=? AND pid=?""",+ (time.time(), execution_id, _PROCESS_ID, os.getpid()),+ )+ if cur.rowcount != 1:+ return None+ record = _record(conn.execute(+ "SELECT * FROM executions WHERE id=?", (execution_id,)+ ).fetchone())+ _emit_execution_state(record)+ return record++def adopt_claimed_execution(execution_id: str) -> Optional[Dict[str, Any]]:"""Atomically transfer and start an attempt in its worker process.@@ -174,7 +209,8 @@ def adopt_claimed_execution(execution_id: str) -> Optional[Dict[str, Any]]:cur = conn.execute("""UPDATE executionsSET process_id=?, pid=?, process_started_at=?,- status='running', started_at=?+ status='running', started_at=?, handoff_pending=0,+ handoff_started_at=NULLWHERE id=? AND status='claimed'""",(_PROCESS_ID, pid, process_started_at, now, execution_id),)@@ -192,8 +228,10 @@ def mark_execution_running(execution_id: str) -> Optional[Dict[str, Any]]:now = _hermes_now().isoformat()with _transaction() as conn:cur = conn.execute(- """UPDATE executions SET status='running', started_at=?- WHERE id=? AND status='claimed'""",+ """UPDATE executions+ SET status='running', started_at=?, handoff_pending=0,+ handoff_started_at=NULL+ WHERE id=? AND status='claimed' AND handoff_pending=0""",(now, execution_id),)if cur.rowcount != 1:@@ -215,7 +253,9 @@ def finish_execution(detail = None if success else (str(error) if error else "unknown failure")with _transaction() as conn:cur = conn.execute(- """UPDATE executions SET status=?, finished_at=?, error=?+ """UPDATE executions+ SET status=?, finished_at=?, error=?, handoff_pending=0,+ handoff_started_at=NULLWHERE id=? AND status IN ('claimed','running')""",(status, now, detail, execution_id),)@@ -236,7 +276,9 @@ def recover_interrupted_executions() -> int:recovered: List[Dict[str, Any]] = []with _transaction() as conn:rows = conn.execute(- """SELECT id, process_id, pid, process_started_at FROM executions+ """SELECT id, process_id, pid, process_started_at,+ handoff_pending, handoff_started_at+ FROM executionsWHERE status IN ('claimed','running')""").fetchall()for row in rows:@@ -244,8 +286,18 @@ def recover_interrupted_executions() -> int:continueif _owner_is_live(int(row["pid"]), row["process_started_at"]):continue+ handoff_started_at = row["handoff_started_at"]+ if (+ row["handoff_pending"]+ and handoff_started_at is not None+ and time.time() - float(handoff_started_at)+ < HANDOFF_ADOPTION_GRACE_SECONDS+ ):+ continuecur = conn.execute(- """UPDATE executions SET status='unknown', finished_at=?, error=?+ """UPDATE executions+ SET status='unknown', finished_at=?, error=?,+ handoff_pending=0, handoff_started_at=NULLWHERE id=? AND status IN ('claimed','running')""",(now,"Scheduler restarted after this execution's owner exited before a durable "@@ -290,6 +342,16 @@ def list_executions(return [dict(row) for row in rows]+def get_execution(execution_id: str) -> Optional[Dict[str, Any]]:+ """Return one exact execution attempt, or ``None`` when it is absent."""+ with _transaction() as conn:+ row = conn.execute(+ "SELECT * FROM executions WHERE id=?",+ (str(execution_id),),+ ).fetchone()+ return dict(row) if row is not None else None++def latest_execution(job_id: str) -> Optional[Dict[str, Any]]:rows = list_executions(job_id=job_id, limit=1)return rows[0] if rows else Nonediff --git a/cron/scheduler.py b/cron/scheduler.pyindex aeda1b4196a..8191dd71033 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -725,7 +725,14 @@ from cron.jobs import (save_job_output,use_cron_store,)-from cron.executions import create_execution, finish_execution, mark_execution_running+from cron.executions import (+ create_execution,+ finish_execution,+ get_execution,+ mark_execution_handoff_pending,+ mark_execution_running,+ recover_interrupted_executions,+)# Sentinel: when a cron agent has nothing new to report, it can start its# response with this marker to suppress delivery. Output is still saved@@ -769,6 +776,10 @@ _parallel_pool: Optional[concurrent.futures.ThreadPoolExecutor] = None_parallel_pool_max_workers: Optional[int] = None_running_job_ids: set = set()_running_fire_owners: dict[str, dict[object, tuple[Optional[str], Path]]] = {}+# Parent gateway threads synchronously waiting on restart-safe scope workers.+# Shutdown must not misclassify these as ownerless in-process runs: the tool+# process sweep cannot reach the worker's transient scope.+_restart_safe_waiter_job_ids: set[str] = set()_running_lock = threading.Lock()# Wall-clock (time.time()) instant each in-flight job id was claimed by@@ -1287,9 +1298,11 @@ def mark_running_jobs_interrupted(Returns the list of job IDs marked, for the caller to log."""with _running_lock:+ restart_safe_waiters = set(_restart_safe_waiter_job_ids)active_fires = [(token, job_id, owner, profile_home)for job_id, executions in _running_fire_owners.items()+ if job_id not in restart_safe_waitersfor token, (owner, profile_home) in executions.items()]if only_owners is not None:@@ -1301,7 +1314,9 @@ def mark_running_jobs_interrupted(if only_owners is None:active_fires.extend((None, job_id, None, _get_hermes_home())- for job_id in _running_job_ids - registered_ids+ for job_id in (+ _running_job_ids - registered_ids - restart_safe_waiters+ ))_interrupted_job_ids.update(token if token is not None else job_id@@ -3211,7 +3226,12 @@ def _deliver_result(if external_execution and adapters is None:from cron.delivery_queue import enqueue_and_wait- return enqueue_and_wait(external_execution, job, content)+ return enqueue_and_wait(+ external_execution,+ job,+ content,+ for_failure=for_failure,+ )from tools.send_message_tool import _send_to_platformfrom gateway.config import load_gateway_config, Platform@@ -4133,11 +4153,12 @@ def drain_delivery_queue(adapters, loop) -> int:from cron.delivery_queue import drainreturn drain(- lambda queued_job, queued_content: _deliver_result(+ lambda queued_job, queued_content, queued_for_failure: _deliver_result(queued_job,queued_content,adapters=adapters,loop=loop,+ for_failure=queued_for_failure,))@@ -7395,11 +7416,13 @@ def run_one_job(# Every gateway path (built-in scheduler, external providers, and direct# API fires) crosses this seam. Ensure the detached worker has a durable# attempt to adopt before any launch can occur.- if adapters is not None and not job.get("execution_id"):+ if not job.get("execution_id"):execution = create_execution(job["id"], source="direct")job["execution_id"] = execution["id"]- if adapters is not None:+ execution_id = str(job["execution_id"])+ external_owner = os.environ.get("_HERMES_CRON_EXTERNAL_WORKER") == execution_id+ if not external_owner:try:if _launch_external_cron_worker(job):return True@@ -7416,9 +7439,7 @@ def run_one_job(**({"expected_fire_owner": owner} if owner else {}),)finally:- execution_id = job.get("execution_id")- if execution_id:- finish_execution(execution_id, success=False, error=error)+ finish_execution(execution_id, success=False, error=error)return Trueif extra_prompt is None:# A gateway-forwarded manual run (`hermes cron run --prompt` /@@ -7521,6 +7542,7 @@ def _run_one_job_body()_scope_token = None+ _terminal_scope_token = Nonetry:# Pre-run dispatch claim (issue #38758): atomically commit a finite# one-shot's dispatch BEFORE its side effect runs, so a tick that dies@@ -8028,6 +8050,65 @@ def _run_one_job_body(reset_terminal_scope(_terminal_scope_token)+def _wait_for_external_cron_worker_body(+ process: subprocess.Popen,+ *,+ execution_id: str,+) -> bool:+ """Preserve ``run_one_job``'s synchronous contract after handoff.++ The worker owns the durable execution and survives this gateway process.+ The caller nevertheless waits while it remains alive so manual/background+ callers do not release their in-process guard or report stale job state.+ A gateway replacement may kill this waiter; it does not kill the scoped+ worker or change its ledger ownership.+ """+ terminal_states = {"completed", "failed", "unknown"}++ def _is_terminal() -> bool:+ current = get_execution(execution_id)+ return bool(current and current.get("status") in terminal_states)++ while True:+ if _is_terminal():+ return True+ returncode = process.poll()+ if returncode is not None:+ # The worker can commit its terminal row and exit between the first+ # read and poll(). Re-read the exact attempt before declaring that+ # it died without terminalizing.+ if _is_terminal():+ return True+ # If the adopted worker died without terminalizing, its owner is+ # now provably gone. Recover to ``unknown`` rather than routing the+ # exception through the pre-handoff dispatch-failure path, which+ # would falsely assert that no side effect could have happened.+ recover_interrupted_executions()+ if _is_terminal():+ return True+ raise RuntimeError(+ "cron external worker exited before durable recovery could "+ f"terminalize its execution state (exit {returncode})"+ )+ time.sleep(0.05)+++def _wait_for_external_cron_worker(+ process: subprocess.Popen,+ *,+ execution_id: str,+ job_id: Optional[str] = None,+) -> bool:+ try:+ return _wait_for_external_cron_worker_body(+ process, execution_id=execution_id+ )+ finally:+ if job_id is not None:+ with _running_lock:+ _restart_safe_waiter_job_ids.discard(job_id)++def _launch_external_cron_worker(job: dict) -> bool:"""Launch *job* outside a managed gateway cgroup when required.@@ -8063,6 +8144,11 @@ def _launch_external_cron_worker(job: dict) -> bool:if scoped_command == command:return False+ if mark_execution_handoff_pending(execution_id) is None:+ raise RuntimeError(+ "cron execution claim changed before external worker handoff"+ )+_ensure_cron_dir(handoff_dir)try:handoff_dir.chmod(0o700)@@ -8105,6 +8191,9 @@ def _launch_external_cron_worker(job: dict) -> bool:payload_path.unlink(missing_ok=True)raise+ with _running_lock:+ _restart_safe_waiter_job_ids.add(job_id)+deadline = time.monotonic() + 5.0while time.monotonic() < deadline:if ack_path.exists():@@ -8116,25 +8205,36 @@ def _launch_external_cron_worker(job: dict) -> bool:"treating handoff as ownership-uncertain",execution_id,)- return True+ return _wait_for_external_cron_worker(+ process, execution_id=execution_id, job_id=job_id+ )finally:ack_path.unlink(missing_ok=True)- if acknowledgement.get("execution_id") != execution_id:+ if (+ not isinstance(acknowledgement, dict)+ or acknowledgement.get("execution_id") != execution_id+ ):logger.error("Cron external worker acknowledgement mismatch for %s; ""treating handoff as ownership-uncertain",execution_id,)- return True+ return _wait_for_external_cron_worker(+ process, execution_id=execution_id, job_id=job_id+ )logger.info("Cron job '%s' handed to restart-safe worker pid=%s execution=%s",job_id,acknowledgement.get("pid"),execution_id,)- return True+ return _wait_for_external_cron_worker(+ process, execution_id=execution_id, job_id=job_id+ )returncode = process.poll()if returncode is not None:+ with _running_lock:+ _restart_safe_waiter_job_ids.discard(job_id)payload_path.unlink(missing_ok=True)raise RuntimeError(f"cron external worker exited before ownership acknowledgement "@@ -8151,7 +8251,9 @@ def _launch_external_cron_worker(job: dict) -> bool:"leaving the durable execution claim untouched",job_id,)- return True+ return _wait_for_external_cron_worker(+ process, execution_id=execution_id, job_id=job_id+ )def _run_external_worker_payload(payload_path: Path, ack_path: Path) -> bool:diff --git a/gateway/run.py b/gateway/run.pyindex 27f88ea75f1..e17ab9eddf8 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -33280,13 +33280,13 @@ def _drain_restart_safe_cron_deliveries(adapters, loop, runner=None) -> None:"""Drain each profile's worker queue through its matching live adapters."""from cron import scheduler as cron_scheduler- if adapters:+ if adapters is not None:cron_scheduler.drain_delivery_queue(adapters, loop)if runner is None:returnfor profile_name, profile_home in _handoff_watch_scopes(runner)[1:]:profile_adapters = getattr(runner, "_profile_adapters", {}).get(profile_name)- if not profile_adapters:+ if profile_adapters is None:continuewith _profile_runtime_scope(profile_home):cron_scheduler.drain_delivery_queue(profile_adapters, loop)@@ -33358,10 +33358,7 @@ def _start_gateway_housekeeping(# their final send for whichever gateway instance is live. Drain on# the gateway-wide housekeeper rather than the built-in scheduler tick:# external providers do not run that ticker.- profile_adapters = (- getattr(runner, "_profile_adapters", {}) if runner is not None else {}- )- if adapters or any(profile_adapters.values()):+ if adapters is not None or runner is not None:try:_drain_restart_safe_cron_deliveries(adapters, loop, runner)except Exception as exc:diff --git a/tests/cron/test_cron_failure_deliver.py b/tests/cron/test_cron_failure_deliver.pyindex 1695447ad0d..88e6fee2441 100644--- a/tests/cron/test_cron_failure_deliver.py+++ b/tests/cron/test_cron_failure_deliver.py@@ -76,7 +76,7 @@ def run_env(monkeypatch, tmp_path):monkeypatch.setattr(s, "create_execution", lambda *_a, **_kw: {"id": "exec-t"})monkeypatch.setattr(s, "claim_dispatch", lambda _job_id: True)- monkeypatch.setattr(s, "mark_execution_running", lambda _execution_id: None)+ monkeypatch.setattr(s, "mark_execution_running", lambda _execution_id: {})monkeypatch.setattr(s, "save_job_output",lambda jid, out: state["saved"].append(jid) or f"/tmp/{jid}.txt",diff --git a/tests/cron/test_delivery_queue.py b/tests/cron/test_delivery_queue.pyindex 7fc65171585..67539a6ba3c 100644--- a/tests/cron/test_delivery_queue.py+++ b/tests/cron/test_delivery_queue.py@@ -2,6 +2,7 @@from __future__ import annotations+import sqlite3from unittest.mock import Mockimport pytest@@ -16,8 +17,79 @@ def test_pending_delivery_is_claimed_and_sent_once(tmp_path, monkeypatch):assert queue.drain(send) == 1assert queue.drain(send) == 0- send.assert_called_once_with({"id": "job-1"}, "brief")- assert queue.get_status("exec-1")["status"] == "delivered"+ send.assert_called_once_with({"id": "job-1"}, "brief", False)+ status = queue.get_status("exec-1")+ assert status["status"] == "delivered"+ assert status["job_json"] == "{}"+ assert status["content"] == ""+++def test_terminal_delivery_retention_is_bounded(tmp_path, monkeypatch):+ import cron.delivery_queue as queue++ monkeypatch.setattr(queue, "DELIVERY_DB", tmp_path / "deliveries.db")+ monkeypatch.setattr(queue, "MAX_TERMINAL_DELIVERIES", 2, raising=False)+ for index in range(4):+ execution_id = f"exec-{index}"+ queue.enqueue(execution_id, {"id": f"job-{index}"}, f"brief-{index}")+ assert queue.claim_next()["execution_id"] == execution_id+ assert queue._finish(execution_id, error=None)++ assert queue.get_status("exec-0") is None+ assert queue.get_status("exec-1") is None+ assert queue.get_status("exec-2")["status"] == "delivered"+ assert queue.get_status("exec-3")["status"] == "delivered"+++def test_failure_delivery_lane_survives_durable_handoff(tmp_path, monkeypatch):+ import cron.delivery_queue as queue++ monkeypatch.setattr(queue, "DELIVERY_DB", tmp_path / "deliveries.db")+ queue.enqueue(+ "exec-failure",+ {"id": "job-failure", "failure_deliver": "local"},+ "failed",+ for_failure=True,+ )+ send = Mock(return_value=None)++ assert queue.drain(send) == 1+ send.assert_called_once_with(+ {"id": "job-failure", "failure_deliver": "local"},+ "failed",+ True,+ )+++def test_legacy_queue_schema_adds_failure_lane_before_enqueue(tmp_path, monkeypatch):+ import cron.delivery_queue as queue++ db = tmp_path / "deliveries.db"+ with sqlite3.connect(db) as conn:+ conn.execute(+ """CREATE TABLE deliveries (+ execution_id TEXT PRIMARY KEY,+ job_json TEXT NOT NULL,+ content TEXT NOT NULL,+ status TEXT NOT NULL,+ owner_process_id TEXT,+ owner_pid INTEGER,+ owner_started_at INTEGER,+ created_at TEXT NOT NULL,+ finished_at TEXT,+ error TEXT+ )"""+ )+ monkeypatch.setattr(queue, "DELIVERY_DB", db)++ queue.enqueue(+ "exec-migrated",+ {"id": "job-migrated"},+ "failed",+ for_failure=True,+ )++ assert queue.get_status("exec-migrated")["for_failure"] == 1def test_dead_delivery_owner_becomes_unknown_and_is_not_retried(diff --git a/tests/cron/test_execution_ledger.py b/tests/cron/test_execution_ledger.pyindex f2b8a9cacf7..641be1fdf9d 100644--- a/tests/cron/test_execution_ledger.py+++ b/tests/cron/test_execution_ledger.py@@ -39,6 +39,54 @@ def test_execution_transitions_are_durable(monkeypatch, tmp_path):assert persisted == [completed]+def test_execution_can_be_loaded_by_exact_attempt_id(monkeypatch, tmp_path):+ executions = _point_ledger(monkeypatch, tmp_path)+ first = executions.create_execution("same-job", source="builtin")+ second = executions.create_execution("same-job", source="builtin")++ assert executions.get_execution(first["id"]) == first+ assert executions.get_execution(second["id"]) == second+ assert executions.get_execution("missing") is None+++def test_fresh_external_handoff_is_not_recovered_before_worker_adopts(+ monkeypatch, tmp_path+):+ executions = _point_ledger(monkeypatch, tmp_path)+ record = executions.create_execution("handoff-job", source="builtin")+ assert executions.mark_execution_handoff_pending(record["id"]) is not None++ monkeypatch.setattr(executions, "_PROCESS_ID", "replacement-gateway")+ monkeypatch.setattr(executions, "_owner_is_live", lambda _pid, _started: False)++ assert executions.recover_interrupted_executions() == 0+ assert executions.get_execution(record["id"])["status"] == "claimed"+ adopted = executions.adopt_claimed_execution(record["id"])+ assert adopted["status"] == "running"+ assert adopted["handoff_pending"] == 0+++def test_stale_external_handoff_is_recovered_unknown(monkeypatch, tmp_path):+ executions = _point_ledger(monkeypatch, tmp_path)+ record = executions.create_execution("handoff-job", source="builtin")+ pending = executions.mark_execution_handoff_pending(record["id"])++ monkeypatch.setattr(executions, "_PROCESS_ID", "replacement-gateway")+ monkeypatch.setattr(executions, "_owner_is_live", lambda _pid, _started: False)+ monkeypatch.setattr(+ executions.time,+ "time",+ lambda: pending["handoff_started_at"]+ + executions.HANDOFF_ADOPTION_GRACE_SECONDS+ + 1,+ )++ assert executions.recover_interrupted_executions() == 1+ recovered = executions.get_execution(record["id"])+ assert recovered["status"] == "unknown"+ assert recovered["handoff_pending"] == 0++def test_execution_ledger_follows_the_current_profile_home(monkeypatch, tmp_path):import cron.executions as executionsdiff --git a/tests/cron/test_restart_safe_worker.py b/tests/cron/test_restart_safe_worker.pyindex e0c0207f41a..8e1a2135d23 100644--- a/tests/cron/test_restart_safe_worker.py+++ b/tests/cron/test_restart_safe_worker.py@@ -2,7 +2,14 @@from __future__ import annotations+import asyncioimport json+import os+import signal+import subprocess+import sys+import threading+import timefrom pathlib import Pathfrom unittest.mock import Mock@@ -34,6 +41,29 @@ def test_execution_owner_moves_to_external_worker_before_running(assert execution_ledger.mark_execution_running(record["id"]) is None+def test_genuine_external_worker_crash_is_recovered_unknown(+ execution_ledger, monkeypatch+):+ record = execution_ledger.create_execution("job-crash", source="builtin")+ script = (+ "import os\n"+ "from pathlib import Path\n"+ "import cron.executions as executions\n"+ f"executions.EXECUTIONS_FILE = Path({str(execution_ledger.EXECUTIONS_FILE)!r})\n"+ f"assert executions.adopt_claimed_execution({record['id']!r}) is not None\n"+ "os._exit(9)\n"+ )++ crashed = subprocess.run([sys.executable, "-c", script], check=False)+ assert crashed.returncode == 9++ monkeypatch.setattr(execution_ledger, "_PROCESS_ID", "replacement-scheduler")+ assert execution_ledger.recover_interrupted_executions() == 1+ recovered = execution_ledger.latest_execution("job-crash")+ assert recovered["status"] == "unknown"+ assert "whether side effects ran is unknown" in recovered["error"]++def test_restart_safe_gateway_child_fails_closed_without_scope(monkeypatch):import tools.process_registry as process_registry@@ -159,7 +189,17 @@ def test_launch_external_worker_uses_restart_safe_scope_and_acknowledges()return FakeProcess()+ handoff = Mock(return_value={"id": "exec-1", "handoff_pending": 1})+ monkeypatch.setattr(scheduler, "mark_execution_handoff_pending", handoff)monkeypatch.setattr(scheduler.subprocess, "Popen", popen)+ observed_statuses = iter(+ [+ {"id": "exec-1", "status": "running"},+ {"id": "exec-1", "status": "completed"},+ ]+ )+ get = Mock(side_effect=lambda _execution_id: next(observed_statuses))+ monkeypatch.setattr(scheduler, "get_execution", get)monkeypatch.setenv("ANTHROPIC_API_KEY", "should-not-cross-profile")from agent.secret_scope import set_multiplex_active@@ -172,10 +212,58 @@ def test_launch_external_worker_uses_restart_safe_scope_and_acknowledges(assert spawned[0][0][0:2] == ["scope", "--"]assert spawned[0][1]["start_new_session"] is Trueassert "ANTHROPIC_API_KEY" not in spawned[0][1]["env"]+ handoff.assert_called_once_with("exec-1")+ assert get.call_count == 2payload = json.loads((tmp_path / "cron/external-workers/exec-1.json").read_text())assert payload["multiplex_active"] is True+def test_external_worker_exit_rechecks_exact_execution_before_failure(monkeypatch):+ import cron.scheduler as scheduler++ statuses = iter(+ [+ {"id": "exec-1", "status": "running"},+ {"id": "exec-1", "status": "completed"},+ ]+ )+ get = Mock(side_effect=lambda _execution_id: next(statuses))+ monkeypatch.setattr(scheduler, "get_execution", get, raising=False)+ process = Mock()+ process.poll.return_value = 0++ assert scheduler._wait_for_external_cron_worker(+ process, execution_id="exec-1"+ ) is True+ assert get.call_count == 2+++def test_external_worker_crash_recovers_uncertain_attempt(monkeypatch):+ import cron.scheduler as scheduler++ statuses = iter(+ [+ {"id": "exec-1", "status": "running"},+ {"id": "exec-1", "status": "running"},+ {"id": "exec-1", "status": "unknown"},+ ]+ )+ get = Mock(side_effect=lambda _execution_id: next(statuses))+ recover = Mock(return_value=1)+ monkeypatch.setattr(scheduler, "get_execution", get)+ monkeypatch.setattr(+ scheduler, "recover_interrupted_executions", recover, raising=False+ )+ process = Mock()+ process.poll.return_value = 9++ assert scheduler._wait_for_external_cron_worker(+ process, execution_id="exec-1"+ ) is True+ recover.assert_called_once_with()+ assert get.call_count == 3++def test_launch_external_worker_stays_in_process_outside_managed_gateway(monkeypatch,):@@ -215,6 +303,40 @@ def test_shared_run_path_hands_gateway_fire_to_external_worker(monkeypatch):run.assert_not_called()+def test_shutdown_does_not_interrupt_restart_safe_waiter():+ import cron.scheduler as scheduler++ job_id = "external-waiter"+ scheduler._running_job_ids.add(job_id)+ scheduler._restart_safe_waiter_job_ids.add(job_id)+ try:+ assert scheduler.mark_running_jobs_interrupted("gateway restart") == []+ assert job_id not in scheduler._interrupted_job_ids+ finally:+ scheduler._restart_safe_waiter_job_ids.discard(job_id)+ scheduler._running_job_ids.discard(job_id)+ scheduler._interrupted_job_ids.discard(job_id)+++def test_gateway_tool_run_without_adapter_objects_hands_off(monkeypatch):+ import cron.scheduler as scheduler++ created = Mock(return_value={"id": "exec-tool"})+ launch = Mock(return_value=True)+ run = Mock(side_effect=AssertionError("agent ran inside gateway"))+ monkeypatch.setattr(scheduler, "create_execution", created)+ monkeypatch.setattr(scheduler, "_launch_external_cron_worker", launch)+ monkeypatch.setattr(scheduler, "run_job", run)+ job = {"id": "tool-job"}++ assert scheduler.run_one_job(job, adapters=None) is True++ created.assert_called_once_with("tool-job", source="direct")+ assert job["execution_id"] == "exec-tool"+ launch.assert_called_once_with(job)+ run.assert_not_called()++def test_shared_run_path_creates_execution_before_managed_handoff(monkeypatch):import cron.scheduler as scheduler@@ -243,3 +365,150 @@ def test_lost_execution_start_cas_prevents_side_effects(monkeypatch):{"id": "job-1", "execution_id": "exec-1"}, adapters=None) is Truerun.assert_not_called()++[email protected]_only[email protected]_system_guard_bypass+def test_managed_gateway_restart_preserves_active_worker_and_single_side_effect(+ tmp_path, monkeypatch+):+ import cron.delivery_queue as delivery_queue+ import cron.executions as executions+ import cron.scheduler as scheduler+ from cron.jobs import create_job, use_cron_store+ from gateway.config import Platform, PlatformConfig+ from gateway.status import _pid_exists+ from tools import process_registry++ if not process_registry._systemd_run_user_scope_available():+ pytest.skip("systemd-run --user --scope is unavailable on this host")++ home = tmp_path / "profile"+ scripts_dir = home / "scripts"+ scripts_dir.mkdir(parents=True)+ started = tmp_path / "started"+ release = tmp_path / "release"+ side_effect = tmp_path / "side-effect"+ probe = scripts_dir / "restart_probe.py"+ probe.write_text(+ "import pathlib, time\n"+ f"started = pathlib.Path({str(started)!r})\n"+ f"release = pathlib.Path({str(release)!r})\n"+ f"side_effect = pathlib.Path({str(side_effect)!r})\n"+ "started.write_text('started')\n"+ "deadline = time.monotonic() + 15\n"+ "while not release.exists() and time.monotonic() < deadline:\n"+ " time.sleep(0.05)\n"+ "if not release.exists():\n"+ " raise SystemExit('release timeout')\n"+ "with side_effect.open('a') as handle:\n"+ " handle.write('once\\n')\n"+ "print('completed')\n",+ encoding="utf-8",+ )+ monkeypatch.setenv("HERMES_HOME", str(home))+ with use_cron_store(home):+ job = create_job(+ prompt=None,+ schedule="every 1h",+ name="restart probe",+ script=probe.name,+ no_agent=True,+ deliver="telegram:123",+ )+ payload = tmp_path / "job.json"+ launched = tmp_path / "launched.json"+ payload.write_text(json.dumps(job), encoding="utf-8")++ sent = []+ adapter = Mock()++ async def send(_chat_id, content, metadata=None):+ sent.append((content, metadata))+ return {"success": True, "message_id": "restart-delivery-1"}++ adapter.send = send+ gateway_config = Mock()+ gateway_config.platforms = {+ Platform.TELEGRAM: PlatformConfig(enabled=True),+ }+ gateway_config.get_home_channel = lambda _platform: None+ monkeypatch.setattr(+ "gateway.config.load_gateway_config", lambda: gateway_config+ )+ monkeypatch.setattr(+ scheduler, "load_config", lambda: {"cron": {"wrap_response": False}}+ )+ replacement_loop = asyncio.new_event_loop()+ replacement_thread = threading.Thread(+ target=replacement_loop.run_forever,+ daemon=True,+ )+ replacement_thread.start()+ deadline = time.monotonic() + 2+ while not replacement_loop.is_running() and time.monotonic() < deadline:+ time.sleep(0.01)+ assert replacement_loop.is_running()++ harness = (+ "import json, os, pathlib, time\n"+ f"os.environ['HERMES_HOME'] = {str(home)!r}\n"+ "os.environ['INVOCATION_ID'] = 'restart-fixture'\n"+ "from cron import scheduler\n"+ "from tools import process_registry\n"+ "process_registry._is_supervised_gateway_process = lambda: True\n"+ f"job = json.loads(pathlib.Path({str(payload)!r}).read_text())\n"+ "if not scheduler.run_one_job(job, adapters=None, loop=None):\n"+ " raise SystemExit('worker was not isolated')\n"+ f"pathlib.Path({str(launched)!r}).write_text('returned')\n"+ )+ parent = subprocess.Popen([sys.executable, "-c", harness])+ worker_pid = None+ try:+ deadline = time.monotonic() + 10+ current = None+ while time.monotonic() < deadline:+ if parent.poll() is not None:+ pytest.fail(f"gateway fixture exited early with {parent.returncode}")+ current = executions.latest_execution(job["id"])+ if started.exists() and current and current.get("pid") != os.getpid():+ break+ time.sleep(0.05)+ assert started.exists()+ assert current is not None+ execution = current+ worker_pid = int(current["pid"])+ assert not launched.exists(), "handoff returned before execution completed"++ # Replacing a managed gateway kills its old process tree. The active+ # cron owner must remain in its transient scope and keep the same PID.+ parent.terminate()+ parent.wait(timeout=5)+ assert _pid_exists(worker_pid)++ release.write_text("go", encoding="utf-8")+ deadline = time.monotonic() + 10+ while time.monotonic() < deadline:+ row = delivery_queue.get_status(execution["id"])+ if row and row["status"] == "pending":+ scheduler.drain_delivery_queue(+ {Platform.TELEGRAM: adapter}, replacement_loop+ )+ current = executions.latest_execution(job["id"])+ if current and current["status"] == "completed":+ break+ time.sleep(0.05)+ assert executions.latest_execution(job["id"])["status"] == "completed"+ assert side_effect.read_text(encoding="utf-8").splitlines() == ["once"]+ assert delivery_queue.get_status(execution["id"])["status"] == "delivered"+ assert len(sent) == 1+ assert "completed" in sent[0][0]+ finally:+ replacement_loop.call_soon_threadsafe(replacement_loop.stop)+ replacement_thread.join(timeout=2)+ replacement_loop.close()+ if parent.poll() is None:+ parent.terminate()+ parent.wait(timeout=5)+ if worker_pid is not None and _pid_exists(worker_pid):+ os.kill(worker_pid, signal.SIGKILL)diff --git a/tests/gateway/test_cron_delivery_housekeeping.py b/tests/gateway/test_cron_delivery_housekeeping.pyindex 8e38071679c..9260c031fbe 100644--- a/tests/gateway/test_cron_delivery_housekeeping.py+++ b/tests/gateway/test_cron_delivery_housekeeping.py@@ -37,11 +37,29 @@ def test_gateway_housekeeping_drains_cron_delivery_with_live_adapters(monkeypatcassert calls == [(adapters, loop)]+def test_gateway_housekeeping_drains_cron_delivery_without_connected_adapters(monkeypatch):+ adapters = {}+ loop = object()+ calls = []+ monkeypatch.setattr(+ scheduler,+ "drain_delivery_queue",+ lambda live_adapters, live_loop: calls.append((live_adapters, live_loop)),+ raising=False,+ )++ gateway_run._start_gateway_housekeeping(+ _OneTickStopEvent(), adapters=adapters, loop=loop, interval=0+ )++ assert calls == [(adapters, loop)]++def test_multiplex_housekeeping_drains_each_profile_with_its_adapters(tmp_path, monkeypatch):root_adapters = {}- secondary_adapters = {"telegram": "secondary"}+ secondary_adapters = {}runner = SimpleNamespace(config=SimpleNamespace(multiplex_profiles=True),adapters=root_adapters,@@ -77,6 +95,7 @@ def test_multiplex_housekeeping_drains_each_profile_with_its_adapters()assert calls == [+ ("drain", root_adapters),("scope", secondary_home),("drain", secondary_adapters),]diff --git a/tests/tools/test_cronjob_run_background.py b/tests/tools/test_cronjob_run_background.pyindex a35d4c4a8fb..c120273c03e 100644--- a/tests/tools/test_cronjob_run_background.py+++ b/tests/tools/test_cronjob_run_background.py@@ -237,6 +237,28 @@ class TestInFlightDedupe:assert seen_during_run["registered"] is Trueassert "job-bg-09" not in sched.get_running_job_ids() # released after+ def test_run_claimed_job_reports_exact_unknown_execution_not_stale_success(self):+ from tools.cronjob_tools import _run_claimed_job++ def probe_run(job, **_kwargs):+ job["execution_id"] = "exec-unknown"+ return True++ with patch("cron.scheduler.run_one_job", side_effect=probe_run), \+ patch("cron.executions.get_execution", return_value={+ "id": "exec-unknown",+ "status": "unknown",+ "error": "worker owner exited",+ }), \+ patch("tools.cronjob_tools.get_job", return_value={+ "last_status": "ok",+ "last_error": None,+ }):+ res = _run_claimed_job(_job("job-bg-unknown"))++ assert res["success"] is False+ assert res["error"] == "worker owner exited"+def test_background_dispatch_reports_running_job_immediately(self):"""The dispatch path pre-checks the running set so a mid-run jobreports in the tool response, not as a delayed completion event."""diff --git a/tools/cronjob_tools.py b/tools/cronjob_tools.pyindex cdcdc6cea5c..e59f364979f 100644--- a/tools/cronjob_tools.py+++ b/tools/cronjob_tools.py@@ -1125,6 +1125,12 @@ def _run_claimed_job(_registered = Falserelease_running_job(job_id)refreshed = get_job(job_id) or {}+ execution = None+ execution_id = job.get("execution_id")+ if execution_id:+ from cron.executions import get_execution++ execution = get_execution(str(execution_id))last_status = refreshed.get("last_status")# "delivery_failed" (#83993): the agent run itself succeeded but the# output never reached the user. That is NOT a success for the caller@@ -1136,6 +1142,12 @@ def _run_claimed_job(run_error = refreshed.get("last_error")if last_status == "delivery_failed" and not run_error:run_error = refreshed.get("last_delivery_error")+ if execution is not None and execution.get("status") != "completed":+ ok = False+ run_error = (+ execution.get("error")+ or f"execution ended in {execution.get('status') or 'unknown'} state"+ )return {"claimed": True,"success": bool(processed and ok),