Skip to content

The agent that grows with you

fix(tools): processes.json writers keep the worker handoffs they do not track

Teknium92fec1607b0b
diff --git a/tests/tools/test_process_checkpoint_worker_handoff.py b/tests/tools/test_process_checkpoint_worker_handoff.py
new file mode 100644
index 00000000000..997018316d8
--- /dev/null
+++ b/tests/tools/test_process_checkpoint_worker_handoff.py
@@ -0,0 +1,52 @@
+"""processes.json keeps the worker handoffs its writer does not track (ahrazzle B2-04).
+
+A managed worker's background process reaches the next interpreter only through the profile
+checkpoint. The owner (or a second worker) rewrote that file from its own table alone, so its
+next process start/exit dropped the worker's entry: nobody tailed the log, notify_on_complete
+never fired and poll/kill could not see the process. Real processes, real checkpoint file.
+"""
+import json
+import subprocess
+import sys
+import time
+
+import psutil
+import pytest
+
+
[email protected]("linux", "macos")
+def test_owner_checkpoint_write_keeps_a_live_worker_handoff(tmp_path, monkeypatch):
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ from tools import process_registry as pr
+ from tools.process_registry_output_log import output_dir
+ checkpoint = tmp_path / 'processes.json'
+ monkeypatch.setattr(pr, 'CHECKPOINT_PATH', checkpoint)
+ logs = output_dir()
+ logs.mkdir(parents=True)
+ worker_proc = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)'], stdin=subprocess.DEVNULL)
+ owner_proc = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)'], stdin=subprocess.DEVNULL)
+ try:
+ handoff = {'session_id': 'proc_worker', 'command': 'dev-server', 'pid': worker_proc.pid, 'pid_scope': 'host',
+ 'host_start_time': pr.ProcessRegistry._safe_host_start_time(worker_proc.pid),
+ 'started_at': time.time(), 'output_log': str(logs / 'proc_worker.log'), 'notify_on_complete': True}
+ (logs / 'proc_worker.log').write_text('serving\n')
+ gone = {**handoff, 'session_id': 'proc_gone', 'pid': 2 ** 22 + 7, 'output_log': str(logs / 'proc_gone.log')}
+ (logs / 'proc_gone.log').write_text('')
+ checkpoint.write_text(json.dumps([handoff, gone])) # what the exiting worker left behind
+ owner = pr.ProcessRegistry()
+ owner._running['proc_owner'] = pr.ProcessSession(
+ id='proc_owner', command='owner-job', task_id='t', started_at=time.time(), pid=owner_proc.pid,
+ pid_scope='host', host_start_time=pr.ProcessRegistry._safe_host_start_time(owner_proc.pid))
+ owner._write_checkpoint() # the owner's own process start
+ ids = {entry['session_id'] for entry in json.loads(checkpoint.read_text())}
+ assert ids == {'proc_owner', 'proc_worker'}, ids
+ # The next interpreter still adopts the worker's process from the file.
+ successor = pr.ProcessRegistry()
+ successor._running['proc_owner'] = owner._running['proc_owner']
+ assert successor.recover_from_checkpoint() == 1
+ assert successor.get('proc_worker') is not None
+ finally:
+ for proc in (worker_proc, owner_proc):
+ proc.kill()
+ proc.wait(timeout=10)
+ assert not psutil.pid_exists(worker_proc.pid) or psutil.Process(worker_proc.pid).status() == psutil.STATUS_ZOMBIE
diff --git a/tools/process_registry_checkpoint.py b/tools/process_registry_checkpoint.py
index 700aab028f7..c05ab07a5ea 100644
--- a/tools/process_registry_checkpoint.py
+++ b/tools/process_registry_checkpoint.py
@@ -42,11 +42,33 @@ class ProcessCheckpointMixin:
if extra_entries:
tracked_ids = {item.get("session_id") for item in entries}
entries.extend(item for item in extra_entries if item.get("session_id") not in tracked_ids)
+ known = {*self._running, *self._finished}
+ from hermes_cli.active_sessions import _FileLock
from utils import atomic_json_write
- atomic_json_write(_checkpoint_path(), entries)
+ path = _checkpoint_path()
+ # Every interpreter of the profile (owner, each managed worker) rewrites this file from
+ # its own table; a worker's output-log handoff is its only path to the next one, so a
+ # writer keeps the handoffs it does not track (read-merge-write under one file lock).
+ with _FileLock(path.with_name(path.name + ".lock")):
+ entries.extend(self._foreign_handoffs(path, known))
+ atomic_json_write(path, entries)
except Exception as e:
logger.debug("Failed to write checkpoint file: %s", e, exc_info=True)
+ def _foreign_handoffs(self, path, known) -> list[dict[str, Any]]:
+ """On-disk worker handoffs this registry never tracked whose log still decides an outcome:
+ the process is alive (same start time) or its recorded exit is waiting to be read."""
+ from pathlib import Path
+ from tools.process_registry_output_log import _exit_path, adoptable_log
+ try:
+ on_disk = json.loads(path.read_text(encoding="utf-8-sig"))
+ except (OSError, ValueError):
+ return []
+ return [entry for entry in on_disk if isinstance(entry, dict) and entry.get("session_id") not in known
+ and (log := adoptable_log(entry.get("output_log"))) and Path(log).exists()
+ and (_exit_path(log).exists() or self._detached_host_fate(
+ entry.get("pid"), entry.get("host_start_time")) == "running")]
+
def recover_from_checkpoint(self) -> int:
"""On gateway startup, probe PIDs from the checkpoint file; returns how many
were recovered as detached sessions."""