Skip to content

The agent that grows with you

fix: restore durable delegation completions from the gateway owner, not at tools import

Teknium9977864dcc0c
diff --git a/gateway/run_startup.py b/gateway/run_startup.py
index 29fd2c252fd..c80b40616e6 100644
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@ -913,6 +913,11 @@ class GatewayStartupMixin:
recovered = process_registry.recover_from_checkpoint()
if recovered:
logger.info("Recovered %s background process(es) from previous run", recovered)
+ # The gateway owns delegation state: replay durable completions the previous
+ # process never delivered. Explicit here, never at tools import (clients).
+ with _log_suppressed(logging.WARNING, "Could not restore async delegation completions: %s"):
+ from tools.async_delegation import restore_undelivered_completions
+ restore_undelivered_completions(process_registry.completion_queue)
# Recover sessions active at last exit (exact turn markers + 120s recency fallback for
# marker-less older turns). SKIP after a clean exit — the previous process already drained.
_clean_marker = _hermes_home / ".clean_shutdown"
diff --git a/tests/tools/test_async_delegation.py b/tests/tools/test_async_delegation.py
index 361e5df93f9..17859a01533 100644
--- a/tests/tools/test_async_delegation.py
+++ b/tests/tools/test_async_delegation.py
@@ -527,7 +527,8 @@ def test_in_tool_stall_uses_higher_threshold(monkeypatch):
def test_real_process_restart_restores_owned_completion_once(tmp_path):
- """Real-import E2E: a fresh interpreter restores a prior process's result."""
+ """Real-import E2E: the owning runtime, in a fresh interpreter, restores a prior process's
+ result exactly once. Importing the tools graph alone restores nothing (client fence)."""
repo = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
env = {**os.environ, "HERMES_HOME": str(tmp_path), "PYTHONPATH": repo}
producer = r'''
@@ -552,6 +553,9 @@ print(r["delegation_id"])
consumer = r'''
import json
from tools.process_registry import process_registry
+from tools.async_delegation import restore_undelivered_completions
+assert process_registry.completion_queue.empty(), "import must not restore"
+restore_undelivered_completions(process_registry.completion_queue)
evt = process_registry.completion_queue.get_nowait()
print(json.dumps(evt, sort_keys=True))
'''
@@ -574,7 +578,7 @@ assert ad.mark_completion_delivered({delegation_id!r})
text=True, capture_output=True, timeout=15, check=True,
)
probe = subprocess.run(
- [sys.executable, "-c", "from tools.process_registry import process_registry; print(process_registry.completion_queue.qsize())"],
+ [sys.executable, "-c", "from tools.process_registry import process_registry; from tools.async_delegation import restore_undelivered_completions; restore_undelivered_completions(process_registry.completion_queue); print(process_registry.completion_queue.qsize())"],
cwd=repo, env=env, text=True, capture_output=True, timeout=15, check=True,
)
assert probe.stdout.strip().splitlines()[-1] == "0"
diff --git a/tests/tools/test_process_registry_import_fence.py b/tests/tools/test_process_registry_import_fence.py
new file mode 100644
index 00000000000..0e0aa7f83e1
--- /dev/null
+++ b/tests/tools/test_process_registry_import_fence.py
@@ -0,0 +1,77 @@
+"""Importing a tool module must never open the canonical store.
+
+Only the runtime that owns delegation state (gateway authority, interactive agent) may
+restore durable completions, and only explicitly; an ordinary client CLI (``hermes cron
+run``, ``hermes sessions list``) imports ``tools.process_registry`` transitively and must
+stay a zero-writer against ``state.db``.
+"""
+import json
+import os
+import queue
+import subprocess
+import sys
+import time
+
+import pytest
+
+_IMPORT_PROBE = r'''
+import json, os, sys
+home = os.environ["HERMES_HOME"]
+connects = []
+sys.addaudithook(lambda ev, a: connects.append(str(a[0])) if ev == "sqlite3.connect" and home in str(a[0]) else None)
+import tools.process_registry # noqa: F401
+print(json.dumps(connects))
+'''
+
+
+def test_importing_process_registry_does_not_connect_to_state_db(tmp_path):
+ home = tmp_path / "home"
+ home.mkdir()
+ env = {k: v for k, v in os.environ.items() if not k.startswith("HERMES_")}
+ env.update(HERMES_HOME=str(home), HOME=str(tmp_path), PYTHONPATH=os.getcwd())
+ out = subprocess.run([sys.executable, "-c", _IMPORT_PROBE], env=env, capture_output=True, text=True,
+ timeout=120, stdin=subprocess.DEVNULL)
+ assert out.returncode == 0, out.stderr
+ assert json.loads(out.stdout.strip().splitlines()[-1]) == []
+ assert not (home / "state.db").exists()
+
+
+async def test_gateway_startup_restores_pending_delegation_completions(tmp_path, monkeypatch):
+ """The gateway authority is the owner that rehydrates durable completions, at startup."""
+ from unittest.mock import MagicMock
+ import gateway.run as gateway_run
+ import tools.async_delegation as ad
+ from tools.process_registry import process_registry
+
+ monkeypatch.setattr(ad, "_db_path", lambda: tmp_path / "state.db")
+ monkeypatch.setattr(gateway_run, "_hermes_home", tmp_path)
+ monkeypatch.setattr("hermes_cli.plugins.discover_plugins", lambda: None)
+ monkeypatch.setattr("agent.shell_hooks.register_from_config", lambda *a, **k: None)
+ monkeypatch.setattr(process_registry, "recover_from_checkpoint", lambda: 0)
+ event = {"type": "async_delegation", "delegation_id": "d-owner", "session_key": "OLD", "origin_ui_session_id": "",
+ "goal": "g", "status": "success", "summary": "S", "api_calls": 1, "duration_seconds": 1.0,
+ "dispatched_at": time.time() - 2, "completed_at": time.time() - 1}
+ ad._persist_dispatch({"delegation_id": "d-owner", "goal": "g", "context": None, "toolsets": None, "role": "leaf",
+ "model": "m", "session_key": "OLD", "origin_ui_session_id": "", "parent_session_id": "OLD",
+ "status": "running", "dispatched_at": time.time() - 2, "completed_at": None, "interrupt_fn": None})
+ ad._persist_completion(event, {"summary": "S"})
+ while not process_registry.completion_queue.empty():
+ process_registry.completion_queue.get_nowait()
+
+ runner = gateway_run.GatewayRunner.__new__(gateway_run.GatewayRunner)
+ runner._start_register_plugins_relay_hooks = MagicMock()
+ runner.hooks = MagicMock()
+ runner._recover_unclean_sessions = _async_return((0, 0))
+ runner._consume_clean_shutdown_marker = _async_return(0)
+ runner._suspend_stuck_loop_sessions = lambda: 0
+ await runner._start_recover_previous_run()
+
+ restored = process_registry.completion_queue.get_nowait()
+ assert restored["delegation_id"] == "d-owner" and restored["restored"] is True
+
+
+def _async_return(value):
+ async def _f(*a, **k):
+ return value
+ return _f
diff --git a/tools/process_registry.py b/tools/process_registry.py
index a58aa6ce099..a96bfedcd9c 100644
--- a/tools/process_registry.py
+++ b/tools/process_registry.py
@@ -473,12 +473,11 @@ class ProcessRegistry(ProcessCheckpointMixin):
# process_loop and the gateway drain it after each agent turn to trigger new turns.
import queue as _queue_mod
self.completion_queue: _queue_mod.Queue = _queue_mod.Queue()
- # Rehydrate durable delegation completions once, at registry startup.
- try:
- from tools.async_delegation import restore_undelivered_completions
- restore_undelivered_completions(self.completion_queue)
- except Exception as exc:
- logger.warning("Could not restore async delegation completions: %s", exc)
+ # Durable delegation completions are NOT rehydrated here: this constructor runs at
+ # import time in every process that touches the tools graph (cron clients, `hermes
+ # sessions list`, workers), and restoring means writing the canonical ledger. Only
+ # the runtime that owns delegation state calls restore_undelivered_completions,
+ # explicitly (GatewayRunner._start_recover_previous_run).
# Completions the agent already consumed via wait()/read_log() (output in
# hand): drain loops AND gateway/tui watchers skip them.
self._completion_consumed: set = set()