Skip to content

The agent that grows with you

fix(update): reap leaked serve backends during a GUI hand-off instead of dead-ending the venv sync (Windows)

Tekniumd5edb66199cb
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index fd29544f902..e24eb46e2e9 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -4877,6 +4877,7 @@ _LAZY_COMMAND_EXPORTS = {
"_for_each_systemd_gateway_unit",
"_format_concurrent_instances_message",
"_format_time_ago",
+ "_handoff_reapable_backend_pids",
"_format_venv_python_holders_message",
"_gateway_prompt",
"_get_origin_url",
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index b69f9a79979..8a443cc6b46 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -3941,6 +3941,76 @@ def _orphaned_desktop_backend_pids(
return roots
+def _handoff_reapable_backend_pids(
+ matches: list[tuple[int, str, str]],
+) -> list[int] | None:
+ """PIDs of Hermes ``serve``/``dashboard`` backends safe to reap during a
+ GUI-updater hand-off, INCLUDING ones with a still-live parent.
+
+ Complements ``_orphaned_desktop_backend_pids``, which only reaps backends
+ whose supervisor is provably dead. That check returns ``None`` (keep
+ refusing) the moment ANY holder still has a live parent — which is exactly
+ the case that produced the field incident this fixes: a Windows Desktop
+ update hand-off (``update --yes --gateway --force``) left a *swarm* of
+ per-profile ``serve`` backends (mr-tester, probe-inherit, turqoise, …)
+ holding ``cryptography\\_rust.pyd``. Several still had a lingering
+ parent (the tearing-down Electron process, or the two-hop venv
+ launcher→worker chain mid-exit), so the orphan check disqualified the
+ WHOLE set and the update dead-ended — the user saw a 12-minute hang, then
+ force-closed, and the half-done state stranded bot sessions.
+
+ The hand-off is the safe signal: when the update-incomplete marker is
+ present (the GUI updater claimed it) AND this is a ``--gateway`` hand-off
+ run AND no live Desktop shim (``hermes.exe``) is open, NOTHING legitimate
+ is supervising or respawning a ``serve`` backend from this venv — by the
+ hand-off contract the Desktop tree-kills its backends and parks any
+ relaunch behind the marker (#50238). Any ``serve`` backend still holding
+ the venv here is therefore a leak, live parent or not, and reaping its
+ tree is correct rather than a race.
+
+ Guarded conservatively:
+
+ - Only Hermes backends (``hermes_cli.main`` + ``serve``/``dashboard``)
+ from THIS install's venv qualify; a non-backend holder (operator REPL,
+ stray script) disqualifies the whole set → ``None`` (keep refusing), so
+ we never widen the blast radius during a hand-off.
+ - Requires ``handoff`` True (caller passes ``args.gateway`` AND a claimed
+ marker) — outside a hand-off this returns ``None`` and the stricter
+ orphan-only path stands.
+ - psutil unavailable → ``None`` (can't re-read argv to classify → refuse).
+
+ Returns the backend root PIDs to tree-reap, or ``None`` to leave the
+ decision to the caller's existing rungs. Never raises.
+ """
+ try:
+ import psutil # type: ignore
+ except Exception:
+ return None
+
+ def _is_backend(argv_low: str) -> bool:
+ return "hermes_cli.main" in argv_low and (
+ " serve" in argv_low or " dashboard" in argv_low
+ )
+
+ roots: list[int] = []
+ for pid, _name, cmdline in matches:
+ argv = cmdline
+ try:
+ argv = " ".join(psutil.Process(int(pid)).cmdline()) or cmdline
+ except psutil.NoSuchProcess:
+ # Exited between scan and classification — nothing to reap.
+ continue
+ except Exception:
+ pass
+ if not _is_backend(argv.lower()):
+ # A non-backend holder during a hand-off is unexpected; refuse the
+ # whole set rather than reap something we cannot justify.
+ return None
+ roots.append(int(pid))
+
+ return roots or None
+
+
def _stop_process_trees(pids: list[int]) -> None:
"""Force-stop each PID with its full child tree (Windows).
@@ -4824,6 +4894,40 @@ def _cmd_update_impl(args, gateway_mode: bool):
_m()._stop_process_trees(_orphan_backends)
_time.sleep(1.0)
_venv_holders = _m()._detect_venv_python_processes()
+ if _venv_holders:
+ # Final rung before the dead-end: a GUI-updater hand-off
+ # (`update --gateway --force` with the update-incomplete marker
+ # claimed) means the Desktop is contractually gone and nothing
+ # legitimate will respawn a `serve` backend from this venv. The
+ # orphan-only reap above bails the instant ANY holder still has a
+ # live parent — which stranded a whole swarm of per-profile
+ # backends (the tearing-down Electron parent / the venv
+ # launcher→worker chain still mid-exit) and hung the update. In
+ # the hand-off context those surviving Hermes backends are leaks,
+ # live parent or not — reap them by cmdline instead of dead-ending.
+ _handoff = False
+ try:
+ _handoff = bool(getattr(args, "gateway", False)) and _m()._update_marker_path().exists()
+ except Exception:
+ _handoff = False
+ _no_live_shim = True
+ try:
+ _scripts_dir = _m()._venv_scripts_dir()
+ if _scripts_dir is not None:
+ _no_live_shim = not _m()._detect_concurrent_hermes_instances(_scripts_dir)
+ except Exception:
+ _no_live_shim = True
+ if _handoff and _no_live_shim:
+ _handoff_backends = _m()._handoff_reapable_backend_pids(_venv_holders)
+ if _handoff_backends:
+ print(
+ f" ⚠ {len(_handoff_backends)} Hermes backend process(es) "
+ "still hold the venv after the Desktop hand-off; "
+ "stopping their trees"
+ )
+ _m()._stop_process_trees(_handoff_backends)
+ _time.sleep(1.0)
+ _venv_holders = _m()._detect_venv_python_processes()
if _venv_holders:
print(_format_venv_python_holders_message(_venv_holders))
_m()._resume_windows_gateways_after_update(_windows_gateway_resume)
diff --git a/tests/hermes_cli/test_update_handoff_backend_reap.py b/tests/hermes_cli/test_update_handoff_backend_reap.py
new file mode 100644
index 00000000000..e25f5838e64
--- /dev/null
+++ b/tests/hermes_cli/test_update_handoff_backend_reap.py
@@ -0,0 +1,149 @@
+"""Tests for the GUI-updater hand-off backend reap (_handoff_reapable_backend_pids).
+
+Field incident (2026-08-20, Teknium's Windows box): a Desktop update hand-off
+(`hermes update --yes --gateway --force`) left a *swarm* of per-profile `serve`
+backends (mr-tester, probe-inherit, turqoise, clippy, maroon, …) holding
+`cryptography\\_rust.pyd`. Some still had a live parent (the tearing-down
+Electron process, or the venv launcher→worker two-hop chain mid-exit), so the
+strict orphan-only reap (_orphaned_desktop_backend_pids) disqualified the whole
+set and the update dead-ended — a 12-minute hang, then a force-close that
+stranded bot sessions.
+
+_handoff_reapable_backend_pids is the additional rung that ONLY runs in the
+hand-off context (caller gates on args.gateway + the update-incomplete marker +
+no live hermes.exe shim). There, any surviving Hermes `serve`/`dashboard`
+backend from this venv is a leak — live parent or not — and safe to reap.
+A non-backend holder still disqualifies the whole set.
+
+Runs on any host via a fake psutil module (same approach as
+test_update_orphan_backend_reap.py).
+"""
+
+from __future__ import annotations
+
+import sys
+import types
+from unittest.mock import MagicMock, patch
+
+from hermes_cli import main as cli_main
+
+
+class _FakeNoSuchProcess(Exception):
+ pass
+
+
+def _fake_psutil(procs: dict[int, MagicMock]):
+ def _process(pid: int):
+ if pid not in procs:
+ raise _FakeNoSuchProcess(pid)
+ return procs[pid]
+
+ return types.SimpleNamespace(Process=_process, NoSuchProcess=_FakeNoSuchProcess)
+
+
+def _proc(pid: int, cmdline: list[str]):
+ proc = MagicMock()
+ proc.pid = pid
+ proc.cmdline.return_value = cmdline
+ return proc
+
+
+def _serve_argv(profile: str = "mr-tester") -> list[str]:
+ return [
+ "C:\\hermes\\venv\\Scripts\\python.exe",
+ "-m",
+ "hermes_cli.main",
+ "--profile",
+ profile,
+ "serve",
+ "--host",
+ "127.0.0.1",
+ "--port",
+ "0",
+ ]
+
+
+def _holder(pid: int, cmdline: str):
+ return (pid, "python.exe", cmdline)
+
+
+def test_live_parent_backend_reaped_in_handoff():
+ # The exact case the orphan-only path REFUSES: a serve backend that still
+ # has a live parent. In the hand-off context it must still be reaped.
+ backend = _proc(200, _serve_argv("mr-tester"))
+ fake = _fake_psutil({200: backend})
+ with patch.dict(sys.modules, {"psutil": fake}):
+ holders = [_holder(200, "python.exe -m hermes_cli.main --profile mr-tester serve")]
+ assert cli_main._handoff_reapable_backend_pids(holders) == [200]
+
+
+def test_swarm_of_profile_backends_all_reaped():
+ profiles = ["mr-tester", "probe-inherit", "turqoise", "clippy", "maroon"]
+ procs = {200 + i: _proc(200 + i, _serve_argv(p)) for i, p in enumerate(profiles)}
+ fake = _fake_psutil(procs)
+ with patch.dict(sys.modules, {"psutil": fake}):
+ holders = [
+ _holder(200 + i, f"python.exe -m hermes_cli.main --profile {p} serve")
+ for i, p in enumerate(profiles)
+ ]
+ assert sorted(cli_main._handoff_reapable_backend_pids(holders)) == sorted(procs)
+
+
+def test_dashboard_backend_reaped():
+ backend = _proc(200, ["python.exe", "-m", "hermes_cli.main", "dashboard"])
+ fake = _fake_psutil({200: backend})
+ with patch.dict(sys.modules, {"psutil": fake}):
+ holders = [_holder(200, "python.exe -m hermes_cli.main dashboard")]
+ assert cli_main._handoff_reapable_backend_pids(holders) == [200]
+
+
+def test_non_backend_holder_disqualifies_whole_set():
+ # An operator REPL / stray script during a hand-off is unexpected — refuse
+ # the whole set rather than reap something we can't justify.
+ backend = _proc(200, _serve_argv("mr-tester"))
+ repl = _proc(300, ["python.exe", "-m", "hermes_cli.main", "chat"])
+ fake = _fake_psutil({200: backend, 300: repl})
+ with patch.dict(sys.modules, {"psutil": fake}):
+ holders = [
+ _holder(200, "python.exe -m hermes_cli.main --profile mr-tester serve"),
+ _holder(300, "python.exe -m hermes_cli.main chat"),
+ ]
+ assert cli_main._handoff_reapable_backend_pids(holders) is None
+
+
+def test_exited_holder_skipped_not_fatal():
+ # A holder that vanished between scan and classification is skipped, and the
+ # remaining real backend still qualifies.
+ backend = _proc(200, _serve_argv("mr-tester"))
+ fake = _fake_psutil({200: backend}) # 300 absent → NoSuchProcess
+ with patch.dict(sys.modules, {"psutil": fake}):
+ holders = [
+ _holder(300, "python.exe -m hermes_cli.main --profile gone serve"),
+ _holder(200, "python.exe -m hermes_cli.main --profile mr-tester serve"),
+ ]
+ assert cli_main._handoff_reapable_backend_pids(holders) == [200]
+
+
+def test_no_holders_returns_none():
+ fake = _fake_psutil({})
+ with patch.dict(sys.modules, {"psutil": fake}):
+ assert cli_main._handoff_reapable_backend_pids([]) is None
+
+
+def test_psutil_unavailable_returns_none():
+ # Can't re-read argv to classify → refuse (leave the decision to the
+ # caller's existing rungs / the dead-end).
+ import builtins
+
+ real_import = builtins.__import__
+
+ def _no_psutil(name, *a, **k):
+ if name == "psutil":
+ raise ImportError("no psutil")
+ return real_import(name, *a, **k)
+
+ with patch.dict(sys.modules, {}, clear=False):
+ sys.modules.pop("psutil", None)
+ with patch("builtins.__import__", _no_psutil):
+ holders = [_holder(200, "python.exe -m hermes_cli.main --profile x serve")]
+ assert cli_main._handoff_reapable_backend_pids(holders) is None