The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(delegation): restore durable completions on first consume, not on import (#123265, salvage #123348, #123298)
webtecnica34c2dc5cb178
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.pyindex 3922b9862ca..e7f05d0a3c7 100644--- a/gateway/run_notifications.py+++ b/gateway/run_notifications.py@@ -1864,8 +1864,8 @@ class GatewayNotificationsMixin:def _restore_secondary_completion_ledgers(self, profile_homes) -> None:"""Re-queue undelivered async completions from every SECONDARY profile's ledger. The process- registry restores only the launch profile's ``state.db`` at import; a secondary's rows would- otherwise never be replayed after a restart."""+ registry's ``restore_completions()`` covers only the launch profile's ``state.db``; a+ secondary's rows would otherwise never be replayed after a restart."""from tools.async_delegation import restore_undelivered_completionsfrom tools.process_registry import process_registry as _prself._each_secondary_ledger(profile_homes, lambda: restore_undelivered_completions(_pr.completion_queue),diff --git a/gateway/run_startup.py b/gateway/run_startup.pyindex b7a39d25f7f..d18c27d6316 100644--- a/gateway/run_startup.py+++ b/gateway/run_startup.py@@ -1327,6 +1327,10 @@ class GatewayStartupMixin:) -> Tuple[bool, int]:"""Bring up multiplexed secondary-profile adapters. Returns (aborted, connected_count)."""from gateway.run import MultiplexConfigError+ from tools.process_registry import process_registry as _pr+ # The launch profile's durable completions replay here, not at import (#123265); the+ # secondaries' ledgers are replayed by _restore_secondary_completion_ledgers below.+ _pr.restore_completions()# Secondary-profile adapters connect under their own home + credential scope.try:connected_count += await self._start_secondary_profile_adapters()diff --git a/tests/tools/test_process_registry_lazy_restore.py b/tests/tools/test_process_registry_lazy_restore.pynew file mode 100644index 00000000000..938a91e935d--- /dev/null+++ b/tests/tools/test_process_registry_lazy_restore.py@@ -0,0 +1,30 @@+"""Importing the tool registry must not touch state.db; the durable completion replay runs when a+consumer asks for it (#123265)."""+import os+import subprocess+import sys+from pathlib import Path++REPO = Path(__file__).resolve().parents[2]+++def test_model_tools_import_creates_no_state_db(tmp_path):+ typo_home = tmp_path / "profiles" / "typo" # a missing named profile: a typo'd HERMES_HOME+ env = {**os.environ, "HERMES_HOME": str(typo_home), "PYTHONPATH": str(REPO)}+ env.pop("HERMES_DELEGATED_CHILD_CONTEXT", None)+ proc = subprocess.run([sys.executable, "-c", "import model_tools"], cwd=REPO, env=env,+ text=True, capture_output=True, timeout=120)+ assert proc.returncode == 0, proc.stderr[-2000:]+ assert not (typo_home / "state.db").exists(), sorted(os.listdir(typo_home)) if typo_home.exists() else None+++def test_restore_runs_once_on_first_drain(monkeypatch):+ from tools import async_delegation, process_registry as pr_mod+ calls = []+ monkeypatch.setattr(async_delegation, "restore_undelivered_completions", lambda q: calls.append(q) or 1)+ registry = pr_mod.ProcessRegistry()+ assert calls == [] # construction (module import) does not replay the ledger+ registry.drain_notifications("sess")+ registry.drain_notifications("sess")+ assert registry.restore_completions() == 0+ assert calls == [registry.completion_queue] # first consumer restores, exactly oncediff --git a/tools/async_delegation.py b/tools/async_delegation.pyindex 85cec62b31d..deec0defa47 100644--- a/tools/async_delegation.py+++ b/tools/async_delegation.py@@ -103,10 +103,12 @@ def _connect() -> sqlite3.Connection:# Same state.db as hermes_state.SessionDB -- reuse its owner-only (0600)# hardening so this writer doesn't create/leave the file (and its WAL# sidecars) at the process umask. See hermes_state._secure_state_db_files.+ from hermes_constants import mkdir_under_hermes_homefrom hermes_state import _secure_state_db_filespath = _db_path()- path.parent.mkdir(parents=True, exist_ok=True)+ # A late replay or writer must not resurrect a removed named profile (#123265).+ mkdir_under_hermes_home(path.parent)_secure_state_db_files(path, create_main=True)# wal=False: SessionDB owns state.db's journal mode (_initialize_schema applies the barriers).conn = open_db(path, db_label="state.db (async_delegation)", busy_timeout_ms=10_000,@@ -319,6 +321,8 @@ def restore_undelivered_completions(target_queue) -> int:ownership, otherwise a brand-new session adopts a dead session's delegation results seconds after boot(#64484)."""+ if not _db_path().exists():+ return 0 # nothing to replay; a replay must not create (or migrate) the ledger (#123265)recover_abandoned_delegations()now = time.time()with _DB_LOCK, _transaction() as conn:diff --git a/tools/process_registry.py b/tools/process_registry.pyindex 6dfeb9739ef..2cbcb120120 100644--- a/tools/process_registry.py+++ b/tools/process_registry.py@@ -631,6 +631,9 @@ class ProcessRegistry(ProcessCheckpointMixin):"no job control in this shell", "cannot set terminal process group","tcsetattr: Inappropriate ioctl for device")+ # Class default so registries built via __new__ (tests) still restore on first drain.+ _completions_restored = False+def __init__(self):self._running: Dict[str, ProcessSession] = {}self._finished: Dict[str, ProcessSession] = {}@@ -641,12 +644,11 @@ class ProcessRegistry(ProcessCheckpointMixin):# process_loop and the gateway drain it after each agent turn to trigger new turns.import queue as _queue_modself.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 rehydrated by restore_completions(), NOT here: the+ # module-level singleton runs __init__ on `import model_tools`, and the replay opens+ # (creates, migrates) the launch profile's state.db (#123265). Importing the module is+ # side-effect free and keeps its import-order contract for later completion writers.+ import tools.async_delegation # noqa: F401# 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()@@ -1905,6 +1907,20 @@ class ProcessRegistry(ProcessCheckpointMixin):# ownership, so leave them for the owner.return not (is_async_delegation and evt.get("restored"))+ def restore_completions(self) -> int:+ """Rehydrate durable delegation completions from the launch profile's ledger, once per+ process. Called by the first consumer that drains the queue (CLI/TUI drain, gateway boot,+ TUI poller) so a mere ``import model_tools`` never touches state.db (#123265)."""+ if self._completions_restored:+ return 0+ self._completions_restored = True+ try:+ from tools.async_delegation import restore_undelivered_completions+ return restore_undelivered_completions(self.completion_queue)+ except Exception as exc:+ logger.warning("Could not restore async delegation completions: %s", exc)+ return 0+def drain_notifications(self, session_key: str = "", owns_event=None, *, skip_poll_observed: bool = True,) -> "list[tuple[dict, str]]":@@ -1916,6 +1932,7 @@ class ProcessRegistry(ProcessCheckpointMixin):compression-chain-aware check) consumes ONLY on True, ``session_key`` uses plainequality; non-owned events are re-queued for their owner. No filter consumeseverything (legacy single-session) except restored delegation payloads (fail-closed)."""+ self.restore_completions()results: "list[tuple[dict, str]]" = []requeue: "list[dict]" = []# delegation.surface_child_process_notifications, read at most once per draindiff --git a/tui_gateway/session_notifications.py b/tui_gateway/session_notifications.pyindex 43a43865ac1..81d61d87e7e 100644--- a/tui_gateway/session_notifications.py+++ b/tui_gateway/session_notifications.py@@ -720,6 +720,7 @@ def _notification_poller_scoped_loop(stop_event: threading.Event, sid: str, sessfrom tools import async_delegationfrom tools.process_registry import process_registryfrom tools.process_registry_notifications import format_process_notification+ process_registry.restore_completions() # first consumer in a TUI process (#123265)queue = process_registry.completion_queueemitted = session.setdefault("_notification_emitted", set())handle = lambda events, deferred: _notif_handle_ready( # noqa: E731