The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(serve): retire an SSH-isolated backend once its ownership lock names a newer spawn
kshitijk4poor79f6f944bb7b
diff --git a/hermes_cli/dashboard_procs.py b/hermes_cli/dashboard_procs.pyindex 5561ff2b428..a3e14c99afa 100644--- a/hermes_cli/dashboard_procs.py+++ b/hermes_cli/dashboard_procs.py@@ -886,7 +886,6 @@ def _remote_lock_roots(base_dir: Path | None) -> list[Path]:def _lock_owned_serve_pids(base_dir: Path | None = None) -> set[int]:"""PIDs claimed by valid ``{hermes_home}/desktop-ssh/<ownershipId>/backend.lock.json`` records(best-effort: a bad record contributes no PID; never raises)."""- import jsonowned: set[int] = set()entries: list[Path] = []for root in _remote_lock_roots(base_dir):@@ -895,22 +894,29 @@ def _lock_owned_serve_pids(base_dir: Path | None = None) -> set[int]:except OSError:continuefor entry in entries:- ownership_id = entry.name- lock_path = entry / "backend.lock.json"- try: # validateOwnershipId(): exactly 32 lowercase hex chars- if not entry.is_dir() or not _is_hex(ownership_id, 32) or not lock_path.is_file():- continue- data = lock_path.read_bytes()- if len(data) > 65536:- continue- parsed = json.loads(data)- except (OSError, UnicodeDecodeError, ValueError):- continue- if _valid_lockfile_payload(parsed, ownership_id):- owned.add(parsed["pid"]) # validated as int above+ lock = read_valid_backend_lock(entry / "backend.lock.json")+ if lock is not None:+ owned.add(lock["pid"]) # validated as intreturn owned+def read_valid_backend_lock(lock_path: Path) -> dict | None:+ """The validated body of one ``desktop-ssh/<ownershipId>/backend.lock.json``, or None when it is+ missing, unreadable, oversized or does not match the writer's schema (never raises)."""+ import json+ ownership_id = lock_path.parent.name+ try: # validateOwnershipId(): exactly 32 lowercase hex chars+ if not _is_hex(ownership_id, 32) or not lock_path.is_file():+ return None+ data = lock_path.read_bytes()+ if len(data) > 65536:+ return None+ parsed = json.loads(data)+ except (OSError, UnicodeDecodeError, ValueError):+ return None+ return parsed if _valid_lockfile_payload(parsed, ownership_id) else None++# Covers the gap between process start and the Desktop client writing backend.lock.json._REAP_MIN_AGE_SECONDS = 180.0diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 467836a8704..c106809785c 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -2839,6 +2839,8 @@ def cmd_dashboard(args):ssh_session_token=_ssh_session_token,ssh_owner_nonce=_ssh_owner_nonce,start_mcp_discovery_after_bind=_mcp_discovery_after_bind,+ # The validated token file lives in desktop-ssh/<ownershipId>/, next to the Desktop's lock.+ ssh_lock_path=Path(_token_file).parent / "backend.lock.json" if _token_file else None,)diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex 077c7a5fa3c..fdbc439b1d1 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -1319,6 +1319,7 @@ def _on_server_started(open_browser: bool,initial_profile: str,start_mcp_discovery_after_bind: bool,+ ssh_lock_path: Optional[Path] = None,) -> None:"""Post-bind arming on the serving loop right after ``server.startup()``.@@ -1367,6 +1368,12 @@ def _on_server_started(from hermes_cli.web_server_skew_exit import start_code_skew_watchdogstart_code_skew_watchdog(server)+ if getattr(app.state, "ssh_isolated_clients", None) is not None and ssh_lock_path and _SSH_OWNER_NONCE:+ # A reconnect that cannot prove this pid is its own drops the lock without signalling us+ # and spawns a new nonce (#132034); retire (between turns) once the lock names that spawn.+ from hermes_cli.web_server_owner_exit import start_owner_watchdog++ start_owner_watchdog(server, lock_path=ssh_lock_path, nonce=_SSH_OWNER_NONCE)actual_port = _read_bound_port(server, fallback=port)app.state.bound_port = actual_port@@ -1528,6 +1535,7 @@ def start_server(ssh_session_token: Optional[str] = None,ssh_owner_nonce: Optional[str] = None,start_mcp_discovery_after_bind: bool = False,+ ssh_lock_path: Optional[Path] = None,):"""Start the web UI server.@@ -1537,7 +1545,8 @@ def start_server(``isolated`` (``--isolated``) is recorded in the spawn ledger so attach-firstdiscovery never adopts this process.``ssh_session_token``/``ssh_owner_nonce`` are process-local Desktop SSH- bootstrap state, never persisted or exported to children.+ bootstrap state, never persisted or exported to children; ``ssh_lock_path`` is the+ Desktop's ``backend.lock.json`` for that ownership slot (supersession watchdog).``start_mcp_discovery_after_bind`` (Desktop ``serve``) defers MCP discoveryuntil the ready sentinel is written so its SDK import can't hold the GILagainst the pre-bind path.@@ -1625,6 +1634,7 @@ def start_server(open_browser=open_browser,initial_profile=initial_profile,start_mcp_discovery_after_bind=start_mcp_discovery_after_bind,+ ssh_lock_path=ssh_lock_path,)if headless:from hermes_cli.observability.shared_metrics_startup import record_process_readydiff --git a/hermes_cli/web_server_owner_exit.py b/hermes_cli/web_server_owner_exit.pynew file mode 100644index 00000000000..9ae47dbbc37--- /dev/null+++ b/hermes_cli/web_server_owner_exit.py@@ -0,0 +1,76 @@+"""Supersession retirement for Desktop-owned ``hermes serve --isolated`` backends reached over SSH.++Such a backend is detached on purpose (#91668) and the remote Desktop decides ownership through+``desktop-ssh/<ownershipId>/backend.lock.json``. When a reconnect cannot prove the recorded pid is+its own (dead-looking pid, foreign argv proof) it drops the lock without signalling that pid and+spawns a new nonce (#132034), so the old backend keeps running until the idle watchdog fires — never,+while a half-open tunnel still counts as a client — stacking writers on ``state.db``.++This watchdog polls the lock and, once a VALID lock names another ``spawnNonce`` on consecutive+polls and the retirement fence proves the backend idle (closing admission so no turn can start+mid-teardown), exits cleanly. A missing, unreadable or skewed lock keeps the process up: those are+the windows between a cleanup and the replacement's write, or another Desktop build's file.+Design from the #132034 report by @VexterZ; lock-ownership watchdog idea first drafted in #89452.+"""++from __future__ import annotations++import logging+import threading+import time+from pathlib import Path+from typing import Callable, Optional++_log = logging.getLogger(__name__)++DEFAULT_OWNER_POLL_S = 15.0+# The Desktop writes the lock right after the spawn returns; a young process may still see an+# older lock for a moment, so supersession only counts once the backend has settled.+MIN_AGE_S = 90.0+_CONFIRMATIONS = 2+++def should_retire_superseded(*, lock: Optional[dict], my_nonce: str, age_s: float) -> bool:+ """Retire only when a valid lock provably names another spawn of this ownership slot."""+ return lock is not None and lock["spawnNonce"] != my_nonce and age_s >= MIN_AGE_S+++def start_owner_watchdog(server, *, lock_path: Path, nonce: str,+ read_lock: Optional[Callable[[Path], Optional[dict]]] = None,+ fence=None, poll_s: float = DEFAULT_OWNER_POLL_S,+ now: Callable[[], float] = time.monotonic,+ max_polls: Optional[int] = None) -> threading.Thread:+ """Daemon thread that sets ``server.should_exit`` once this backend is provably superseded and+ provably idle. ``max_polls`` bounds the loop for tests only."""+ if read_lock is None:+ from hermes_cli.dashboard_procs import read_valid_backend_lock++ read_lock = read_valid_backend_lock+ if fence is None:+ from hermes_cli.backend_retirement import retirement++ fence = retirement+ reader: Callable[[Path], Optional[dict]] = read_lock+ started = now()++ def _loop() -> None:+ seen = polls = 0+ while not getattr(server, "should_exit", False) and (max_polls is None or polls < max_polls):+ polls += 1+ lock = reader(lock_path)+ if should_retire_superseded(lock=lock, my_nonce=nonce, age_s=now() - started):+ seen += 1+ else:+ seen = 0+ if seen >= _CONFIRMATIONS and lock is not None:+ permit = fence.prepare()+ if permit.get("ok") and fence.commit(permit.get("token")).get("ok"):+ _log.warning("SSH-isolated backend %s was superseded by spawn %s; retiring.",+ nonce, lock["spawnNonce"])+ server.should_exit = True+ return+ time.sleep(poll_s)++ thread = threading.Thread(target=_loop, daemon=True, name="ssh-isolated-owner-watchdog")+ thread.start()+ return threaddiff --git a/tests/hermes_cli/test_web_server_owner_exit.py b/tests/hermes_cli/test_web_server_owner_exit.pynew file mode 100644index 00000000000..0f7aeab8859--- /dev/null+++ b/tests/hermes_cli/test_web_server_owner_exit.py@@ -0,0 +1,80 @@+"""A Desktop-over-SSH ``serve --isolated`` backend retires itself once the Desktop's ownership lock+names a newer spawn (#132034): a reconnect that cannot prove the old pid is its own drops the lock+without signalling it, so without this the superseded backend lingers as an extra ``state.db``+writer. It exits only between turns (the retirement fence proves idle and closes admission first),+and any lock it cannot validate keeps it up."""++from __future__ import annotations++import json+from pathlib import Path++from hermes_cli.dashboard_procs import read_valid_backend_lock+from hermes_cli.web_server_owner_exit import should_retire_superseded, start_owner_watchdog++OID, ME, NEW = "f" * 32, "a" * 16, "b" * 16+++def _lock(nonce: str) -> dict:+ return {"schemaVersion": 2, "protocolVersion": 1, "ownershipId": OID, "spawnNonce": nonce,+ "tokenFingerprint": "c" * 32, "pid": 4242, "port": 0, "profile": "default",+ "hermesPath": "/opt/hermes/bin/hermes", "hermesHome": "~/.hermes",+ "logPath": f"~/.hermes/desktop-ssh/{OID}/{nonce}.log", "startedAt": "2026-10-03T00:00:00Z"}+++def test_retires_only_on_a_valid_lock_naming_another_spawn(tmp_path):+ lock_path = tmp_path / "desktop-ssh" / OID / "backend.lock.json"+ lock_path.parent.mkdir(parents=True)++ def verdict(body, age_s=600.0):+ if body is None:+ lock_path.unlink(missing_ok=True)+ else:+ lock_path.write_text(body if isinstance(body, str) else json.dumps(body))+ return should_retire_superseded(lock=read_valid_backend_lock(lock_path), my_nonce=ME, age_s=age_s)++ assert verdict(_lock(NEW)) is True+ assert verdict(_lock(ME)) is False # still ours+ assert verdict(None) is False # cleanup ran, replacement not written yet+ assert verdict("{not json") is False # unreadable+ assert verdict({**_lock(NEW), "schemaVersion": 99}) is False # another Desktop build's lock+ assert verdict(_lock(NEW), age_s=5.0) is False # just spawned: the lock may not name us yet+++class _Server:+ should_exit = False+++class _Fence:+ def __init__(self, idle: bool):+ self.idle, self.committed = idle, False++ def prepare(self):+ return {"ok": True, "idle": True, "token": "t"} if self.idle else {"ok": False, "idle": False}++ def commit(self, token):+ self.committed = token == "t"+ return {"ok": self.committed}+++def _run(fence, nonces):+ server, seq = _Server(), iter(nonces)+ clock = iter(range(0, 10_000, 100)) # every poll is well past the young-process window+ def read_lock(_path):+ nonce = next(seq, nonces[-1])+ return _lock(nonce) if nonce else None++ start_owner_watchdog(+ server, lock_path=Path("backend.lock.json"), nonce=ME, fence=fence, poll_s=0.01,+ now=lambda: float(next(clock)), read_lock=read_lock, max_polls=len(nonces) + 2).join(timeout=5)+ return server+++def test_superseded_backend_retires_through_the_fence_only_when_idle():+ idle = _Fence(idle=True)+ assert _run(idle, [NEW, NEW]).should_exit is True+ assert idle.committed is True # admission closed before exit+ assert _run(_Fence(idle=True), [NEW, None, NEW, ME]).should_exit is False # no 2 in a row+ busy = _Fence(idle=False)+ assert _run(busy, [NEW, NEW, NEW]).should_exit is False # an in-flight turn keeps it up+ assert busy.committed is False