The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(serve): reap orphaned host owner instead of looping observe-only
finn7634a916f7a8340
diff --git a/hermes_cli/process_identity.py b/hermes_cli/process_identity.pyindex d220b8a4eee..81bc0c2e1bb 100644--- a/hermes_cli/process_identity.py+++ b/hermes_cli/process_identity.py@@ -33,6 +33,10 @@ LEDGER_FILENAME = "spawn-ledger.json"#: Interactive processes (chat, REPLs) are deliberately NOT in this set.REAPABLE_PURPOSES = frozenset({"serve", "dashboard", "gateway", "mcp-helper"})+#: Host-role owners a fresh backend may reap on a HELD_BY_OTHER conflict (#121964): the+#: serve/dashboard/gateway subset. The mcp-helper rung stays owned by reap_orphaned_mcp_helpers.+_BACKEND_OWNER_PURPOSES = REAPABLE_PURPOSES - {"mcp-helper"}+_IS_WINDOWS = platform.system() == "Windows"# Module-global job handle: must live exactly as long as this process so the@@ -375,6 +379,96 @@ def spawner_is_dead(entry: dict) -> Optional[bool]:return None if alive is None else not alive+def _terminate_then_kill(pid: int, create_time: Optional[float]) -> bool:+ """SIGTERM, 2 s grace, then SIGKILL. False when the incarnation moved on or is already gone."""+ try:+ import psutil++ proc = psutil.Process(pid)+ if not _same_incarnation(proc, create_time):+ return False # PID reused since registration — never signal a stranger+ proc.terminate()+ try:+ proc.wait(timeout=2.0)+ except psutil.TimeoutExpired:+ proc.kill()+ return True+ except Exception:+ logger.debug("orphan terminate failed for pid %s", pid, exc_info=True)+ return False+++def _reparented_orphan(pid: int) -> bool:+ """Null-spawner owner with no live supervisor: reparented to init, old, lock-unclaimed.++ Mirrors ``_reap_orphaned_desktop_local_serves``: operator-managed remote backends legitimately+ sit at ppid 1 (systemd, an exited sshd), so ppid alone is never proof — the SSH-lock claim+ and the 180 s lock-write grace exclude live-supervised backends. Windows: the ppid probe is+ unavailable there, so this rung never fires (desktop tree-kill reaps instead).+ """+ try:+ from hermes_cli.dashboard_procs import (+ _REAP_MIN_AGE_SECONDS, _lock_owned_serve_pids, _process_ppid)+ if _process_ppid(pid) not in (0, 1):+ return False+ if pid in (_lock_owned_serve_pids() or ()):+ return False+ import time as _time++ import psutil+ return max(0.0, _time.time() - psutil.Process(pid).create_time()) >= _REAP_MIN_AGE_SECONDS+ except Exception:+ return False # unprovable → never touch+++def reap_orphaned_backend_owner(+ pid: int, create_time: Optional[float], *, kill_fn=None) -> Optional[int]:+ """Kill the conflicting host owner when the ledger PROVES it is a dead session's orphan.++ HELD_BY_OTHER rung for #121964: the owner PID is alive (re-parented to init), so+ ``record_is_stale()`` never fires and a fresh backend would loop observe-only against the+ same orphan forever. Reaped only with a live ``serve``/``dashboard``/``gateway`` entry for+ THIS install whose spawner is provably dead — or whose spawner was never recorded and which+ is reparented to init, old, and claimed by no Desktop SSH lock. Live-spawned, lock-claimed,+ young, interactive, self, or unprovable owners are never touched. Returns the reaped pid,+ else ``None``; never raises.++ # ponytail: a dead session's surviving backend.lock.json still shields its orphan (the lock+ # has no session liveness); clearing stale locks is a Desktop-side lifecycle job, not this rung.+ """+ try:+ pid = int(pid)+ except (TypeError, ValueError):+ return None+ if pid <= 0 or pid == os.getpid():+ return None+ try:+ entry = next(+ (e for e in ledger_entries()+ if e.get("pid") == pid+ and e.get("purpose") in _BACKEND_OWNER_PURPOSES+ and (e.get("create_time") is None or create_time is None+ or abs(float(e["create_time"]) - float(create_time)) < 2.0)),+ None)+ except Exception:+ return None+ if entry is None:+ return None+ if spawner_is_dead(entry) is not True and not (+ entry.get("spawner_pid") is None and _reparented_orphan(pid)):+ return None # live or unprovable spawner → never touch+ try:+ if kill_fn is not None:+ kill_fn(pid)+ elif not _terminate_then_kill(pid, entry.get("create_time")):+ return None+ except Exception:+ logger.debug("backend owner reap failed for %s", entry, exc_info=True)+ return None+ logger.info("reaped orphaned %s backend owner pid %s", entry.get("purpose"), pid)+ return pid++def reap_orphaned_mcp_helpers(*, project_root: Optional[Path] = None, kill_fn=None) -> list[int]:"""Kill ledger-registered stdio MCP helpers whose spawner is provably dead.diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex a2892d550ed..f23e3eb0fc4 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -1267,6 +1267,40 @@ def _best_effort(what: str, fn) -> None:_log.debug("%s skipped: %s", what, exc)+def _reclaim_host_from_orphaned_owner(role: str) -> bool:+ """True when the conflicting host owner was reaped/cleared and the claim is worth retrying.++ HELD_BY_OTHER helper for #121964. A stale record with no live owner is retracted via+ ``discard_dead_record`` (which only removes provably-gone owners); a live owner is reaped+ only when the spawn ledger proves it is a dead session's orphan. Anything else returns+ False and the caller stays observe-only. Never raises.+ """+ from gateway import host_rendezvous as hr+ from hermes_cli.process_identity import reap_orphaned_backend_owner++ try:+ owner = hr.read_record(role)+ except Exception:+ return False+ if owner is None:+ try:+ return bool(hr.discard_dead_record(role))+ except Exception:+ return False+ if owner.pid == os.getpid():+ return False # never reap our own incarnation on a re-entrant claim+ try:+ if reap_orphaned_backend_owner(owner.pid, owner.create_time) is None:+ return False+ except Exception:+ return False+ try:+ hr.discard_dead_record(role)+ except Exception:+ pass+ return True++def _publish_host_rendezvous(host: str, port: int) -> None:"""Publish this backend's host record: ``ROLE_SERVE`` for the machine-level owner,``ROLE_DESKTOP_SERVE`` for a Desktop-owned child."""@@ -1287,6 +1321,13 @@ def _publish_host_rendezvous(host: str, port: int) -> None:"Host backend lock could not be opened (%s); this backend is not discoverable. ""This is NOT another backend holding it.", error)return+ if outcome is hr.HostLockOutcome.HELD_BY_OTHER and not desktop_child:+ # A prior backend whose session died (dead spawner, PID re-parented to init) is still+ # alive, so it still holds the flock and its record passes every staleness check: the+ # pre-#121964 code returned observe-only here forever, and every attach retried against+ # the same orphan. Reap exactly that corpse and re-claim instead.+ if _reclaim_host_from_orphaned_owner(role):+ outcome, error = hr.claim_host_lock(role)if outcome is hr.HostLockOutcome.HELD_BY_OTHER:owner = hr.read_record(role)if desktop_child:diff --git a/tests/hermes_cli/test_process_identity.py b/tests/hermes_cli/test_process_identity.pyindex 603a58dc7f7..5435374f84a 100644--- a/tests/hermes_cli/test_process_identity.py+++ b/tests/hermes_cli/test_process_identity.py@@ -309,3 +309,99 @@ def test_desktop_ssh_backend_spawn_shape_is_desktop_owned(monkeypatch):assert pi.is_desktop_owned_backend() is True# The bare inherited flag (a Desktop terminal pane running `hermes serve`) is still not ownership.assert pi.is_desktop_owned_backend(["serve", "--host", "127.0.0.1", "--port", "0"]) is False+++# ---------------------------------------------------------------------------+# Host-reclaim rung: reap_orphaned_backend_owner (#121964)+# ---------------------------------------------------------------------------++def _reap(entry_pid=555, create=55.0, procs=None, kill_fn=None, **entry_kw):+ """Run the reclaim predicate with a faked psutil world; returns (result, kills)."""+ entry = _entry(entry_pid, create, **entry_kw)+ kills = []+ fake = _fake_psutil({} if procs is None else procs)+ with patch.dict(sys.modules, {"psutil": fake}), \+ patch.object(pi, "ledger_entries", return_value=[entry]):+ result = pi.reap_orphaned_backend_owner(+ entry_pid, create, kill_fn=(kills.append if kill_fn is None else kill_fn))+ return result, kills+++def test_reclaim_reaps_dead_spawner_owner():+ result, kills = _reap(spawner_pid=700, spawner_create=7.0, procs={555: 55.0})+ assert result == 555+ assert kills == [555]+++def test_reclaim_spares_live_spawner_owner():+ result, kills = _reap(spawner_pid=500, spawner_create=5.0, procs={555: 55.0, 500: 5.0})+ assert result is None+ assert kills == []+++def test_reclaim_spares_unprovable_spawner():+ # Spawner probe itself fails (permission): unprovable means never touch.+ import types++ from unittest.mock import MagicMock++ def _process(pid):+ if pid == 500:+ raise PermissionError(pid)+ proc = MagicMock()+ proc.create_time.return_value = 55.0+ return proc++ fake = types.SimpleNamespace(Process=_process, NoSuchProcess=_FakeNoSuchProcess)+ with patch.dict(sys.modules, {"psutil": fake}), \+ patch.object(pi, "ledger_entries",+ return_value=[_entry(555, 55.0, spawner_pid=500, spawner_create=5.0)]):+ assert pi.reap_orphaned_backend_owner(555, 55.0, kill_fn=lambda pid: None) is None+++def test_reclaim_reaps_null_spawner_orphan_to_init():+ from hermes_cli import dashboard_procs++ with patch.object(dashboard_procs, "_process_ppid", return_value=1), \+ patch.object(dashboard_procs, "_lock_owned_serve_pids", return_value=set()):+ # Ancient orphan: create_time far past vs real clock → past the lock-write grace.+ result, kills = _reap(procs={555: 1000.0}, create=1000.0)+ assert result == 555+ assert kills == [555]+++def test_reclaim_spares_null_spawner_with_live_parent():+ from hermes_cli import dashboard_procs++ with patch.object(dashboard_procs, "_process_ppid", return_value=1234):+ result, kills = _reap(procs={555: 55.0})+ assert result is None+ assert kills == []+++def test_reclaim_spares_lock_claimed_orphan():+ """A valid backend.lock.json claims the PID: another session owns it, never kill."""+ from hermes_cli import dashboard_procs++ with patch.object(dashboard_procs, "_process_ppid", return_value=1), \+ patch.object(dashboard_procs, "_lock_owned_serve_pids", return_value={555}):+ result, kills = _reap(procs={555: 1000.0}, create=1000.0)+ assert result is None+ assert kills == []+++def test_reclaim_spares_interactive_purposes_and_self():+ result, kills = _reap(purpose="chat", spawner_pid=700, spawner_create=7.0,+ procs={555: 55.0})+ assert (result, kills) == (None, [])+ with patch.object(pi.os, "getpid", return_value=555):+ result, kills = _reap(spawner_pid=700, spawner_create=7.0, procs={555: 55.0})+ assert (result, kills) == (None, [])+++def test_reclaim_ignores_unknown_pid_and_never_raises():+ with patch.dict(sys.modules, {"psutil": _fake_psutil({555: 55.0})}), \+ patch.object(pi, "ledger_entries", return_value=[_entry(555, 55.0)]):+ assert pi.reap_orphaned_backend_owner(999, 9.0, kill_fn=lambda pid: None) is None+ with patch.object(pi, "ledger_entries", side_effect=RuntimeError("boom")):+ assert pi.reap_orphaned_backend_owner(555, 55.0, kill_fn=lambda pid: None) is Nonediff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.pyindex 623b9c2a28a..b58279c00ab 100644--- a/tests/hermes_cli/test_web_server.py+++ b/tests/hermes_cli/test_web_server.py@@ -3591,6 +3591,114 @@ class TestDesktopHostRendezvousIsolation:assert published[0][1]["port"] == 9119+class TestOrphanedOwnerReclaim:+ """HELD_BY_OTHER against a dead session's orphan must re-claim, not loop observe-only (#121964).++ The conflicting owner is alive (re-parented to init), so ``record_is_stale()`` never fires+ and the old code returned observe-only forever: every attach retried against the same orphan.+ """++ def _owner_record(self, pid=555, create_time=55.0):+ from gateway import host_rendezvous as hr++ return hr.HostRecord(+ role=hr.ROLE_SERVE, pid=pid, create_time=create_time, host="0.0.0.0", port=9119,+ protocol_version=hr.HOST_PROTOCOL_VERSION, token_fingerprint="", profiles=("default",),+ updated_at="2026-09-24T00:00:00+00:00")++ def _owner_entry(self, pid=555, create_time=55.0, spawner_pid=700, spawner_create=7.0):+ from hermes_cli import process_identity as pi+ from pathlib import Path as _Path++ return {+ "pid": pid, "create_time": create_time, "purpose": "serve",+ "install": pi.install_id(_Path("/x/install")),+ "spawner_pid": spawner_pid, "spawner_create": spawner_create,+ "registered_at": 0.0, "argv": "",+ }++ def _run_publish(self, monkeypatch, tmp_path, *, entry, procs):+ """Drive ``_publish_host_rendezvous`` through HELD_BY_OTHER with a faked owner world.++ First claim fails (the orphan holds the flock), the retry succeeds (it died); returns+ ``(claimed, published, fake_procs)``.+ """+ import types+ from unittest.mock import MagicMock+ from gateway import host_rendezvous as hr+ import hermes_cli.web_server as web_server+ from hermes_cli import process_identity as pi++ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(tmp_path / "locks"))+ monkeypatch.setattr(web_server, "is_desktop_owned_backend", lambda: False)+ claims = iter([hr.HostLockOutcome.HELD_BY_OTHER, hr.HostLockOutcome.ACQUIRED])+ claimed, published = [], []+ monkeypatch.setattr(+ hr, "claim_host_lock",+ lambda role: (claimed.append(role) or (next(claims), None)),+ )+ monkeypatch.setattr(hr, "read_record", lambda role, **kw: self._owner_record())+ monkeypatch.setattr(hr, "publish_record", lambda *a, **k: published.append((a, k)))+ monkeypatch.setattr(hr, "cleanup_on_exit", lambda role: None)+ monkeypatch.setattr(pi, "ledger_entries", lambda **kw: [entry])++ made = {}++ def _process(pid):+ if pid not in procs:+ raise fake_psutil.NoSuchProcess(pid)+ if pid not in made:+ proc = MagicMock()+ proc.pid = pid+ proc.create_time.return_value = procs[pid]+ made[pid] = proc+ return made[pid]++ fake_psutil = types.SimpleNamespace(+ Process=_process,+ NoSuchProcess=type("NoSuchProcess", (Exception,), {}),+ TimeoutExpired=type("TimeoutExpired", (Exception,), {}),+ STATUS_ZOMBIE="zombie",+ )+ monkeypatch.setitem(sys.modules, "psutil", fake_psutil)++ web_server._publish_host_rendezvous("0.0.0.0", 9119)+ return claimed, published, made++ def test_dead_spawner_owner_is_reaped_and_lock_reclaimed(self, monkeypatch, tmp_path):+ """Spawner provably gone: the orphan is terminated and this backend publishes."""+ entry = self._owner_entry(spawner_pid=700, spawner_create=7.0) # 700 not alive+ claimed, published, made = self._run_publish(+ monkeypatch, tmp_path, entry=entry, procs={555: 55.0})++ assert made[555].terminate.called+ assert claimed == ["serve", "serve"] # conflict, then re-claim after the reap+ assert published and published[0][0][0] == "serve"++ def test_live_spawner_owner_stays_observe_only(self, monkeypatch, tmp_path):+ """Spawner alive: never touch, never re-claim — the old observe-only stands."""+ entry = self._owner_entry(spawner_pid=500, spawner_create=5.0)+ claimed, published, made = self._run_publish(+ monkeypatch, tmp_path, entry=entry, procs={555: 55.0, 500: 5.0})++ assert 555 not in made # no signal attempted+ assert claimed == ["serve"] # no retry: nothing was reaped+ assert published == []++ def test_unprovable_owner_is_untouched(self, monkeypatch, tmp_path):+ """Null spawner whose parent is alive: unprovable means never touch."""+ from hermes_cli import dashboard_procs++ entry = self._owner_entry(spawner_pid=None, spawner_create=None)+ monkeypatch.setattr(dashboard_procs, "_process_ppid", lambda pid: 1234)+ claimed, published, made = self._run_publish(+ monkeypatch, tmp_path, entry=entry, procs={555: 55.0})++ assert 555 not in made+ assert claimed == ["serve"]+ assert published == []++# ---------------------------------------------------------------------------# Model context length: normalize/denormalize + /api/model/info# ---------------------------------------------------------------------------