The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): keep unsent worker deliveries queued, cheapen handoff polling
kshitijk4poorb440a492b35f
diff --git a/cron/delivery_queue.py b/cron/delivery_queue.pyindex 013bef5048c..f03413b7271 100644--- a/cron/delivery_queue.py+++ b/cron/delivery_queue.py@@ -20,6 +20,8 @@ from pathlib import Pathfrom typing import Any, Callable, Iterator, Optionalfrom agent.redact import redact_sensitive_text+from cron.executions import _owner_is_live, _process_start_time+from hermes_cli.sqlite_util import add_column_if_missingfrom hermes_constants import get_hermes_homefrom hermes_time import now as _hermes_now@@ -84,8 +86,10 @@ def _transaction() -> Iterator[sqlite3.Connection]:passconn.row_factory = sqlite3.Rowtry:+ from hermes_state import apply_wal_with_fallback+conn.execute("PRAGMA busy_timeout=5000")- conn.execute("PRAGMA journal_mode=WAL")+ apply_wal_with_fallback(conn, db_label="cron/deliveries.db")conn.execute("PRAGMA synchronous=FULL")conn.execute("""CREATE TABLE IF NOT EXISTS deliveries (@@ -111,43 +115,19 @@ def _transaction() -> Iterator[sqlite3.Connection]:finished_at 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"- )+ add_column_if_missing(+ conn, "deliveries", "for_failure",+ "for_failure INTEGER NOT NULL DEFAULT 0",+ )+ # Pruning is done explicitly by the paths that create terminal+ # rows (_finish / recover_abandoned / _terminalize_wait_timeout);+ # read-only polls must not pay for a full-table UPDATE + COUNT.with conn:- _prune_terminal_unlocked(conn)yield connfinally:conn.close()-def _process_start_time(pid: int) -> Optional[int]:- try:- from gateway.status import get_process_start_time-- return get_process_start_time(pid)- except Exception:- return None---def _owner_is_live(pid: int, started_at: Optional[int]) -> bool:- try:- from gateway.status import _pid_exists-- if not _pid_exists(pid):- return False- except Exception:- return True- if started_at is None:- return pid == os.getpid()- return _process_start_time(pid) == started_at--def enqueue(execution_id: str,job: dict,@@ -325,21 +305,28 @@ def drain(def _terminalize_wait_timeout(execution_id: str) -> str:- """Fence a delivery whose worker can no longer wait for confirmation."""+ """Fence a delivery whose worker can no longer wait for confirmation.++ A row still ``pending`` was provably never attempted, so it is left queued+ for whichever gateway comes up next (a restart that includes an update can+ easily exceed the worker's wait budget). Only a row caught mid-send is+ uncertain and gets fenced ``unknown``.+ """now = _hermes_now().isoformat()- pending_error = "timed out waiting for a live gateway; delivery was not attempted"+ pending_error = (+ "timed out waiting for a live gateway; delivery is still queued and "+ "will be sent by the next gateway"+ )uncertain_error = ("timed out while gateway delivery was in progress; outcome is unknown and ""was not retried")with _transaction() as conn:- cur = conn.execute(- """UPDATE deliveries SET status='failed', finished_at=?, error=?- WHERE execution_id=? AND status='pending'""",- (now, pending_error, str(execution_id)),- )- if cur.rowcount:- _prune_terminal_unlocked(conn)+ row = conn.execute(+ "SELECT status FROM deliveries WHERE execution_id=?",+ (str(execution_id),),+ ).fetchone()+ if row is not None and row["status"] == "pending":return pending_errorconn.execute("""UPDATE deliveries SET status='unknown', finished_at=?, error=?@@ -382,5 +369,5 @@ def enqueue_and_wait(return None if row["status"] == "delivered" else str(row.get("error") or f"delivery {row['status']}")- time.sleep(0.25)+ time.sleep(1.0)return _terminalize_wait_timeout(execution_id) or Nonediff --git a/cron/executions.py b/cron/executions.pyindex 3abd5f54df1..023ed75a4d4 100644--- a/cron/executions.py+++ b/cron/executions.py@@ -62,18 +62,15 @@ def _initialize_schema(conn: sqlite3.Connection) -> None: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"- )+ from hermes_cli.sqlite_util import add_column_if_missing++ add_column_if_missing(+ conn, "executions", "handoff_pending",+ "handoff_pending INTEGER NOT NULL DEFAULT 0",+ )+ add_column_if_missing(+ conn, "executions", "handoff_started_at", "handoff_started_at REAL"+ )conn.execute("CREATE INDEX IF NOT EXISTS idx_executions_job_claimed ""ON executions(job_id, claimed_at DESC, id DESC)"diff --git a/cron/scheduler.py b/cron/scheduler.pyindex 8191dd71033..65313c4a987 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -4150,8 +4150,13 @@ def _deliver_result(def drain_delivery_queue(adapters, loop) -> int:"""Send queued worker results through this gateway's live adapters."""- from cron.delivery_queue import drain+ from cron.delivery_queue import _path, drain+ # Only restart-safe workers create the queue file. Every gateway (macOS,+ # Windows, launchd, Docker) runs this housekeeping tick, so skip the sqlite+ # open/create entirely until a worker has actually queued something.+ if not _path().exists():+ return 0return drain(lambda queued_job, queued_content, queued_for_failure: _deliver_result(queued_job,@@ -8069,28 +8074,33 @@ def _wait_for_external_cron_worker_body(current = get_execution(execution_id)return bool(current and current.get("status") in terminal_states)+ # The worker commits its terminal row before its process exits, so exit is+ # the correct wakeup. Each ledger read opens a connection and re-runs+ # schema init; polling it at 50ms for an hours-long agent run is ~72k+ # opens/hour of pure contention with the worker's own writes.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()+ try:+ returncode = process.wait(timeout=1.0)+ except subprocess.TimeoutExpired: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)+ continue+ # The worker can commit its terminal row and exit between the first+ # read and wait(). 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})"+ )def _wait_for_external_cron_worker(@@ -8098,6 +8108,7 @@ def _wait_for_external_cron_worker(*,execution_id: str,job_id: Optional[str] = None,+ handoff_files: tuple[Path, ...] = (),) -> bool:try:return _wait_for_external_cron_worker_body(@@ -8107,6 +8118,13 @@ def _wait_for_external_cron_worker(if job_id is not None:with _running_lock:_restart_safe_waiter_job_ids.discard(job_id)+ # The execution is terminal or its worker is dead: nobody will read a+ # payload or acknowledgement left behind by a late/unread handoff.+ for stale in handoff_files:+ try:+ stale.unlink(missing_ok=True)+ except OSError:+ passdef _launch_external_cron_worker(job: dict) -> bool:@@ -8206,7 +8224,10 @@ def _launch_external_cron_worker(job: dict) -> bool:execution_id,)return _wait_for_external_cron_worker(- process, execution_id=execution_id, job_id=job_id+ process,+ execution_id=execution_id,+ job_id=job_id,+ handoff_files=(payload_path,),)finally:ack_path.unlink(missing_ok=True)@@ -8220,7 +8241,10 @@ def _launch_external_cron_worker(job: dict) -> bool:execution_id,)return _wait_for_external_cron_worker(- process, execution_id=execution_id, job_id=job_id+ process,+ execution_id=execution_id,+ job_id=job_id,+ handoff_files=(payload_path,),)logger.info("Cron job '%s' handed to restart-safe worker pid=%s execution=%s",@@ -8229,7 +8253,10 @@ def _launch_external_cron_worker(job: dict) -> bool:execution_id,)return _wait_for_external_cron_worker(- process, execution_id=execution_id, job_id=job_id+ process,+ execution_id=execution_id,+ job_id=job_id,+ handoff_files=(payload_path,),)returncode = process.poll()if returncode is not None:@@ -8252,7 +8279,10 @@ def _launch_external_cron_worker(job: dict) -> bool:job_id,)return _wait_for_external_cron_worker(- process, execution_id=execution_id, job_id=job_id+ process,+ execution_id=execution_id,+ job_id=job_id,+ handoff_files=(payload_path, ack_path),)@@ -8956,6 +8986,14 @@ if __name__ == "__main__":parser.add_argument("--external-worker-file", type=Path, required=True)parser.add_argument("--ack-file", type=Path, required=True)args = parser.parse_args()+ # The gateway spawns this worker with stdout/stderr on DEVNULL; without+ # a handler every adoption/ack failure below would be invisible.+ try:+ from hermes_logging import setup_logging++ setup_logging(hermes_home=_get_hermes_home(), mode="cron")+ except Exception:+ passraise SystemExit(0 if _run_external_worker_payload(args.external_worker_file, args.ack_file) else 1)diff --git a/tests/cron/test_delivery_queue.py b/tests/cron/test_delivery_queue.pyindex b944fda2246..66ad30bb3f2 100644--- a/tests/cron/test_delivery_queue.py+++ b/tests/cron/test_delivery_queue.py@@ -163,7 +163,11 @@ def test_delivery_failure_is_terminal_not_retried_and_redacted(assert "token=***" in status["error"]-def test_wait_timeout_cancels_unclaimed_delivery(tmp_path, monkeypatch):+def test_wait_timeout_leaves_unclaimed_delivery_queued_for_next_gateway(+ tmp_path, monkeypatch+):+ """A row nobody claimed was never attempted: it is not uncertain, so a+ gateway outage longer than the worker's wait budget must not lose it."""import cron.delivery_queue as queuemonkeypatch.setattr(queue, "DELIVERY_DB", tmp_path / "deliveries.db")@@ -171,13 +175,14 @@ def test_wait_timeout_cancels_unclaimed_delivery(tmp_path, monkeypatch):error = queue.enqueue_and_wait("exec-3", job, "result", timeout=0)- assert "timed out" in error+ assert "timed out" in error and "still queued" in errorstatus = queue.get_status("exec-3")assert status is not None- assert status["status"] == "failed"+ assert status["status"] == "pending"send = Mock(return_value=None)- assert queue.drain(send) == 0- send.assert_not_called()+ assert queue.drain(send) == 1+ send.assert_called_once_with(job, "result", False)+ assert queue.get_status("exec-3")["status"] == "delivered"def test_same_gateway_recovers_terminalization_failure_without_resending(diff --git a/tests/cron/test_restart_safe_worker.py b/tests/cron/test_restart_safe_worker.pyindex ad996fd56de..4820c3e8999 100644--- a/tests/cron/test_restart_safe_worker.py+++ b/tests/cron/test_restart_safe_worker.py@@ -207,10 +207,19 @@ def test_launch_external_worker_uses_restart_safe_scope_and_acknowledges(def poll(self):return self.returncode+ def wait(self, timeout=None):+ if self.returncode is None:+ raise subprocess.TimeoutExpired(cmd="worker", timeout=timeout)+ return self.returncode+spawned = []+ payloads = []+def popen(command, **kwargs):spawned.append((command, kwargs))+ payload_index = command.index("--external-worker-file") + 1+ payloads.append(json.loads(Path(command[payload_index]).read_text()))ack_index = command.index("--ack-file") + 1Path(command[ack_index]).write_text(json.dumps({"pid": 4321, "execution_id": "exec-1"}),@@ -243,8 +252,9 @@ def test_launch_external_worker_uses_restart_safe_scope_and_acknowledges(assert "ANTHROPIC_API_KEY" not in spawned[0][1]["env"]handoff.assert_called_once_with("exec-1")assert get.call_count == 2- payload = json.loads((tmp_path / "cron/external-workers/exec-1.json").read_text())- assert payload["multiplex_active"] is True+ assert payloads[0]["multiplex_active"] is True+ # Once the attempt is terminal the parent reaps its own handoff artifacts.+ assert not (tmp_path / "cron/external-workers/exec-1.json").exists()def test_external_worker_exit_rechecks_exact_execution_before_failure(monkeypatch):@@ -260,6 +270,7 @@ def test_external_worker_exit_rechecks_exact_execution_before_failure(monkeypatcmonkeypatch.setattr(scheduler, "get_execution", get, raising=False)process = Mock()process.poll.return_value = 0+ process.wait.return_value = 0assert scheduler._wait_for_external_cron_worker(process, execution_id="exec-1"@@ -272,7 +283,6 @@ def test_external_worker_crash_recovers_uncertain_attempt(monkeypatch):statuses = iter([- {"id": "exec-1", "status": "running"},{"id": "exec-1", "status": "running"},{"id": "exec-1", "status": "unknown"},]@@ -285,12 +295,13 @@ def test_external_worker_crash_recovers_uncertain_attempt(monkeypatch):)process = Mock()process.poll.return_value = 9+ process.wait.return_value = 9assert scheduler._wait_for_external_cron_worker(process, execution_id="exec-1") is Truerecover.assert_called_once_with()- assert get.call_count == 3+ assert get.call_count == 2def test_launch_external_worker_stays_in_process_outside_managed_gateway(diff --git a/tests/cron/test_script_claim_heartbeat.py b/tests/cron/test_script_claim_heartbeat.pyindex a989b01457e..11fb4501b02 100644--- a/tests/cron/test_script_claim_heartbeat.py+++ b/tests/cron/test_script_claim_heartbeat.py@@ -392,7 +392,7 @@ def test_lost_fire_claim_stops_stale_delivery(monkeypatch):monkeypatch.setattr(scheduler, "heartbeat_fire_claim", _heartbeat)monkeypatch.setattr(scheduler, "run_job", _run_job)monkeypatch.setattr(scheduler, "claim_dispatch", lambda job_id: True)- monkeypatch.setattr(scheduler, "mark_execution_running", lambda execution_id: None)+ monkeypatch.setattr(scheduler, "mark_execution_running", lambda execution_id: {})monkeypatch.setattr(scheduler, "finish_execution", lambda *args, **kwargs: None)save_output = MagicMock()deliver_result = MagicMock()