Skip to content

The agent that grows with you

fix(serve): retire an SSH-isolated backend once the install moves to new code

calvinnwq979c7baeef9f
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index 2600a1a7927..f17936cc831 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -1319,6 +1319,11 @@ def _on_server_started(
except (TypeError, ValueError):
grace = DEFAULT_IDLE_GRACE_S
start_idle_watchdog(server, app.state.ssh_isolated_clients, grace_s=grace)
+ # A connected client keeps the idle watchdog quiet forever, and the host's updater may not
+ # restart this backend, so it retires itself (between turns) when the install moves on.
+ from hermes_cli.web_server_skew_exit import start_code_skew_watchdog
+
+ start_code_skew_watchdog(server)
actual_port = _read_bound_port(server, fallback=port)
app.state.bound_port = actual_port
diff --git a/hermes_cli/web_server_skew_exit.py b/hermes_cli/web_server_skew_exit.py
new file mode 100644
index 00000000000..3d78a704d35
--- /dev/null
+++ b/hermes_cli/web_server_skew_exit.py
@@ -0,0 +1,84 @@
+"""Code-skew retirement for Desktop-owned ``hermes serve --isolated`` backends reached over SSH.
+
+Such a backend belongs to a Desktop on another machine: the host's updater never restarts it (only
+the remote client holds its token and owner nonce), so after ``hermes update`` it keeps serving the
+code it imported at startup against a tree that has moved on, and lazily imports new modules into
+an old process. The idle watchdog (``web_server_idle_exit``) only fires once every client has left,
+which a connected Desktop never does.
+
+This watchdog polls ``gateway.code_skew`` (the boot revision the serve lifespan records, compared
+with the checkout on disk) and, once no update is in flight and the retirement fence proves the
+backend idle (and closes admission so no turn can start mid-teardown), exits cleanly. The client's
+reconnect path respawns it from the new code. Every uncertain read (unknown revision, busy or
+indeterminate ledgers, a live update) keeps the process up.
+"""
+
+from __future__ import annotations
+
+import logging
+import threading
+import time
+from typing import Callable, Optional
+
+_log = logging.getLogger(__name__)
+
+DEFAULT_SKEW_POLL_S = 30.0
+# Two consecutive observations: a checkout mid-rewrite (ref file replaced, packed-refs repacked) can
+# briefly read differently; a real update reads the new revision on every poll after it finishes.
+_CONFIRMATIONS = 2
+
+# ``(boot_rev, disk_rev)`` when the checkout drifted since boot, else None (``detect_code_skew``).
+Skew = Optional[tuple[str, str]]
+
+
+def should_retire_for_skew(*, skew: Skew, update_in_progress: bool) -> bool:
+ """Retire only on a proven code change, and never while the tree may still be mid-swap."""
+ return bool(skew) and not update_in_progress
+
+
+def _update_in_progress() -> bool:
+ try:
+ from hermes_cli.update_lock import read_live_update
+
+ return read_live_update() is not None
+ except Exception:
+ return True # cannot prove the swap is over: wait
+
+
+def start_code_skew_watchdog(server, *, skew_fn: Optional[Callable[[], Skew]] = None,
+ update_probe: Callable[[], bool] = _update_in_progress,
+ fence=None, poll_s: float = DEFAULT_SKEW_POLL_S,
+ max_polls: Optional[int] = None) -> threading.Thread:
+ """Daemon thread that sets ``server.should_exit`` once the loaded code is provably stale and
+ the backend is provably idle. ``max_polls`` bounds the loop for tests only."""
+ if skew_fn is None:
+ from gateway.code_skew import detect_code_skew
+
+ skew_fn = detect_code_skew
+ if fence is None:
+ from hermes_cli.backend_retirement import retirement
+
+ fence = retirement
+ read_skew: Callable[[], Skew] = skew_fn
+
+ def _loop() -> None:
+ seen = polls = 0
+ while not getattr(server, "should_exit", False) and (max_polls is None or polls < max_polls):
+ polls += 1
+ skew = read_skew()
+ if should_retire_for_skew(skew=skew, update_in_progress=update_probe()):
+ seen += 1
+ else:
+ seen = 0
+ if seen >= _CONFIRMATIONS and skew:
+ permit = fence.prepare()
+ if permit.get("ok") and fence.commit(permit.get("token")).get("ok"):
+ _log.warning("SSH-isolated backend loaded %s but the install is now at %s; "
+ "retiring so its client respawns it on the new code.", *skew)
+ server.should_exit = True
+ return
+ time.sleep(poll_s)
+
+ thread = threading.Thread(target=_loop, daemon=True, name="ssh-isolated-skew-watchdog")
+ thread.start()
+ return thread
diff --git a/tests/hermes_cli/test_web_server_skew_exit.py b/tests/hermes_cli/test_web_server_skew_exit.py
new file mode 100644
index 00000000000..3b2a6c8d8be
--- /dev/null
+++ b/tests/hermes_cli/test_web_server_skew_exit.py
@@ -0,0 +1,97 @@
+"""A Desktop-over-SSH ``serve --isolated`` backend retires itself once the install under it moved to
+new code: nothing on its host may restart it (only the remote client holds its token), so without
+this it runs the pre-update code against the updated tree until that client happens to reconnect.
+It exits only between turns (the retirement fence proves idle and closes admission first), never
+while an update is still in flight, and its client respawns it from the new code."""
+
+from __future__ import annotations
+
+import subprocess
+
+from hermes_cli.web_server_skew_exit import should_retire_for_skew, start_code_skew_watchdog
+
+_SKEW = ("aaaaaaaaaa", "bbbbbbbbbb")
+
+
+class _Server:
+ should_exit = False
+
+
+class _Fence:
+ """Retirement fence stand-in: ``idle`` answers prepare; commit records the exit permit."""
+
+ 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 test_retires_only_on_a_proven_code_change_outside_an_update():
+ assert should_retire_for_skew(skew=_SKEW, update_in_progress=False) is True
+ # No drift, or an unreadable revision (detect_code_skew returns None for both): stay up.
+ assert should_retire_for_skew(skew=None, update_in_progress=False) is False
+ # The tree is mid-swap: respawning now would import a half-updated install.
+ assert should_retire_for_skew(skew=_SKEW, update_in_progress=True) is False
+
+
+def _run(fence, skews, *, update=False):
+ server = _Server()
+ seq = iter(skews)
+ thread = start_code_skew_watchdog(
+ server, skew_fn=lambda: next(seq, skews[-1]),
+ update_probe=lambda: update, fence=fence, poll_s=0.01, max_polls=len(skews) + 2)
+ thread.join(timeout=5)
+ return server
+
+
+def test_skew_retires_through_the_fence_after_two_consecutive_observations():
+ fence = _Fence(idle=True)
+ assert _run(fence, [_SKEW, _SKEW]).should_exit is True
+ assert fence.committed is True # admission closed before exit: no turn can start mid-teardown
+
+
+def test_a_single_blip_does_not_retire():
+ fence = _Fence(idle=True)
+ assert _run(fence, [_SKEW, None, _SKEW, None]).should_exit is False
+ assert fence.committed is False
+
+
+def test_a_busy_backend_waits_instead_of_cutting_off_its_client():
+ fence = _Fence(idle=False)
+ assert _run(fence, [_SKEW, _SKEW, _SKEW]).should_exit is False
+
+
+def test_never_retires_while_an_update_is_in_flight():
+ fence = _Fence(idle=True)
+ assert _run(fence, [_SKEW, _SKEW, _SKEW], update=True).should_exit is False
+
+
+def test_default_probe_retires_once_the_checkout_moves_past_the_boot_revision(tmp_path, monkeypatch):
+ """The real wiring: the watchdog reads the boot revision the serve lifespan records
+ (``gateway.code_skew``) against a checkout whose HEAD then moves."""
+ import gateway.code_skew as code_skew
+
+ repo = tmp_path / "repo"
+ git = ["git", "-C", str(repo), "-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"]
+ subprocess.run(["git", "init", "-q", str(repo)], check=True)
+ subprocess.run([*git, "commit", "-q", "--allow-empty", "-m", "one"], check=True)
+ monkeypatch.setattr(code_skew, "_PROJECT_ROOT", repo)
+ monkeypatch.setattr(code_skew, "_boot_fingerprint", None)
+ code_skew.record_boot_fingerprint()
+
+ fence = _Fence(idle=True)
+ unchanged = _Server()
+ start_code_skew_watchdog(unchanged, update_probe=lambda: False, fence=fence,
+ poll_s=0.01, max_polls=4).join(timeout=5)
+ assert unchanged.should_exit is False
+
+ subprocess.run([*git, "commit", "-q", "--allow-empty", "-m", "two"], check=True)
+ moved = _Server()
+ start_code_skew_watchdog(moved, update_probe=lambda: False, fence=fence,
+ poll_s=0.01, max_polls=4).join(timeout=5)
+ assert moved.should_exit is True