From 39a269cb4946db5fa32fc7579ebd2f76588e8b88 Mon Sep 17 00:00:00 2001 From: Jeff Watts <186512915+lEWFkRAD@users.noreply.github.com> Date: Thu, 9 Jul 2026 10:18:24 -0400 Subject: [PATCH 1/2] fix(update): reap gateway venv children so the Windows venv guard self-clears MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On Windows, `hermes update` pauses the gateway before its venv-process guard, but pausing a gateway does not reap the helper processes it spawned from the install venv's python — stdio MCP servers and the perfmon probe. Those children survive as orphans holding native `.pyd` files mapped, so the venv-process guard (`_detect_venv_python_processes`) sees them and refuses the update indefinitely. Every blind retry hits the same wall; a killed `hermes-setup.exe` also leaves a stale `.hermes-update-in-progress` marker behind (observed July 2026 with `client_lookup_mcp` / `hermes-perfmon`). Fix (all Windows-guarded; POSIX behavior unchanged): - `_pause_windows_gateways_for_update` snapshots each gateway's venv-resident descendants BEFORE stopping it (a dead parent's dangling ppid defeats an after-the-fact walk), then reaps them once the gateways are down. They are re-spawned when the gateway restarts (resume path), so no state is lost. The supervised desktop backend (`serve`/`dashboard`) is a child of the Electron app, not a gateway, and is explicitly excluded from the reap. - `_cmd_update_impl` sweeps a stale `.hermes-update-in-progress` marker whose owning PID is dead before the guard runs, so the CLI recovery path also clears the desktop's launch gate. A live-owner marker (a genuine concurrent update, incl. our own parent setup) is never touched. - Extract the venv-holder predicate (`_venv_lock_prefixes` / `_process_holds_install_venv`) so the guard and the reaper classify holders identically. Adds tests for the predicate, snapshot (incl. desktop-backend exclusion, dedup, dead-gateway/no-psutil safety), reap (force-kill each, best-effort on error), `_pid_is_alive`, and the stale-marker sweep (dead/live/malformed/absent/POSIX). Co-Authored-By: Claude Opus 4.8 --- hermes_cli/main.py | 328 ++++++++++++++++-- .../hermes_cli/test_update_venv_child_reap.py | 283 +++++++++++++++ 2 files changed, 581 insertions(+), 30 deletions(-) create mode 100644 tests/hermes_cli/test_update_venv_child_reap.py diff --git a/hermes_cli/main.py b/hermes_cli/main.py index f450a76666f32..6e2545f6e56c6 100644 --- a/hermes_cli/main.py +++ b/hermes_cli/main.py @@ -8852,6 +8852,64 @@ def _venv_core_imports_healthy() -> tuple[bool, str]: return True, "" +def _venv_lock_prefixes() -> tuple[str, str]: + """Return ``(venv_prefix, root_prefix)`` — lowercased, ``os.sep``-terminated — + identifying this install's venv directory and checkout root. + + Used to decide whether a live process runs from, or imports out of, this + install's venv and would therefore keep its native ``.pyd`` extensions + mapped during an update. Factored out so the update-time venv guard and the + gateway-child reaper classify holders identically. + """ + venv_dir = PROJECT_ROOT / "venv" + try: + venv_prefix = str(venv_dir.resolve()).lower().rstrip(os.sep) + os.sep + except OSError: + venv_prefix = str(venv_dir).lower().rstrip(os.sep) + os.sep + try: + root_prefix = str(PROJECT_ROOT.resolve()).lower().rstrip(os.sep) + os.sep + except OSError: + root_prefix = str(PROJECT_ROOT).lower().rstrip(os.sep) + os.sep + return venv_prefix, root_prefix + + +def _process_holds_install_venv( + exe: str | None, + cmdline_raw: str, + cwd: str | None, + venv_prefix: str, + root_prefix: str, +) -> bool: + """True if a process runs from — or imports out of — this install's venv, + and so keeps its native ``.pyd`` extensions mapped (blocking a dep sync). + + Mirrors the three signals the venv-holder guard has always used: + 1. the executable itself lives under ``venv\\Scripts`` (the desktop + backend / a gateway child running straight off the venv python), + 2. a uv/base-interpreter trampoline whose cmdline references the venv + path, or + 3. a ``-m hermes_cli.main ...`` invocation tied to THIS install (install + root in the cmdline or as the working directory). + """ + if not exe: + return False + try: + exe_norm = str(Path(exe).resolve()).lower() + except (OSError, ValueError): + exe_norm = str(exe).lower() + cmdline_low = (cmdline_raw or "").lower() + cwd_low = str(cwd or "").lower().rstrip(os.sep) + os.sep + if exe_norm.startswith(venv_prefix): + return True + if venv_prefix in cmdline_low: + return True + if "hermes_cli.main" in cmdline_low and ( + root_prefix in cmdline_low or cwd_low.startswith(root_prefix) + ): + return True + return False + + def _detect_venv_python_processes( *, exclude_pids: set[int] | None = None ) -> list[tuple[int, str, str]]: @@ -8878,15 +8936,7 @@ def _detect_venv_python_processes( except Exception: return [] - venv_dir = PROJECT_ROOT / "venv" - try: - venv_prefix = str(venv_dir.resolve()).lower().rstrip(os.sep) + os.sep - except OSError: - venv_prefix = str(venv_dir).lower().rstrip(os.sep) + os.sep - try: - root_prefix = str(PROJECT_ROOT.resolve()).lower().rstrip(os.sep) + os.sep - except OSError: - root_prefix = str(PROJECT_ROOT).lower().rstrip(os.sep) + os.sep + venv_prefix, root_prefix = _venv_lock_prefixes() skip: set[int] = set(exclude_pids or set()) skip.add(os.getpid()) @@ -8910,28 +8960,10 @@ def _detect_venv_python_processes( exe = info.get("exe") if not exe or pid is None or int(pid) in skip: continue - try: - exe_norm = str(Path(exe).resolve()).lower() - except (OSError, ValueError): - exe_norm = str(exe).lower() cmdline_raw = " ".join(info.get("cmdline") or []) - cmdline_low = cmdline_raw.lower() - cwd_low = str(info.get("cwd") or "").lower().rstrip(os.sep) + os.sep - - # Primary match: the executable itself lives under this venv - # (venv\Scripts\python(w).exe — the desktop backend / gateway case). - is_holder = exe_norm.startswith(venv_prefix) - # Fallback: uv/base-interpreter trampolines run a python whose exe is - # OUTSIDE the venv but which still imports from it and holds its .pyd - # files. Catch those by what they're running: a cmdline that references - # this venv's path, or a `-m hermes_cli.main ...` invocation tied to - # this install (install root in the cmdline or as the working dir). - if not is_holder and venv_prefix in cmdline_low: - is_holder = True - if not is_holder and "hermes_cli.main" in cmdline_low: - if root_prefix in cmdline_low or cwd_low.startswith(root_prefix): - is_holder = True - if not is_holder: + if not _process_holds_install_venv( + exe, cmdline_raw, info.get("cwd"), venv_prefix, root_prefix + ): continue name = info.get("name") or Path(exe).name matches.append((int(pid), str(name), cmdline_raw[:120])) @@ -8968,6 +9000,218 @@ def _format_venv_python_holders_message(matches: list[tuple[int, str, str]]) -> return "\n".join(lines) +def _pid_is_alive(pid: int) -> bool: + """Best-effort liveness probe for a PID. + + Prefers psutil (reliable across platforms). If psutil is unavailable, + conservatively reports the PID as alive so callers never delete state based + on an unverifiable process. + """ + try: + import psutil + + return psutil.pid_exists(int(pid)) + except Exception: + # Can't verify -> assume alive (safe default: never act on a maybe-live + # process). The desktop's own launch gate self-heals stale markers too. + return True + + +def _sweep_stale_update_marker() -> None: + """Delete a stale ``.hermes-update-in-progress`` marker under HERMES_HOME. + + The desktop-driven updater (``hermes-setup.exe``) writes this marker for the + duration of an update so a relaunched desktop parks instead of spawning a + second backend that re-locks the venv (#50238). If that setup process is + killed mid-update — the recovery for the venv-lock wedge — the marker is + left behind with a now-dead PID and can strand the desktop's next launch + gate. ``hermes update`` is the natural recovery action, so sweep a marker + whose owning PID is dead here. A marker owned by a LIVE pid (a genuinely + concurrent update — including our own parent ``hermes-setup.exe`` when the + desktop drives us) is left untouched. Windows-guarded (the wedge is + Windows-only); never raises. + """ + if not _is_windows(): + return + try: + from hermes_constants import get_hermes_home + + marker = Path(get_hermes_home()) / ".hermes-update-in-progress" + except Exception as exc: + logger.debug("Could not resolve update-marker path for sweep: %s", exc) + return + try: + raw = marker.read_text(encoding="utf-8", errors="replace") + except FileNotFoundError: + return + except OSError as exc: + logger.debug("Could not read update marker %s: %s", marker, exc) + return + pid_line = (raw.splitlines() or [""])[0].strip() if raw else "" + try: + pid = int(pid_line) + except (TypeError, ValueError): + pid = None + # A parseable, still-alive owner => a real concurrent update: leave it. + if pid is not None and pid > 0 and _pid_is_alive(pid): + return + try: + marker.unlink() + print( + "→ Cleared a stale update-in-progress marker " + f"({marker.name}; owner PID {pid_line or '?'} not running)" + ) + except FileNotFoundError: + pass + except OSError as exc: + logger.debug("Could not remove stale update marker %s: %s", marker, exc) + + +def _process_is_desktop_backend(cmdline_low: str) -> bool: + """True for the Hermes Desktop app's supervised backend (``hermes_cli.main + serve`` / dashboard). + + That backend is a child of the Electron app, NOT of a gateway, and the app + respawns it within seconds — so it must never be auto-reaped by the update + flow (the venv guard refuses and tells the user to close the app instead). + Used as a safety exclusion when reaping gateway children. + """ + return "serve" in cmdline_low or "dashboard" in cmdline_low + + +def _snapshot_gateway_venv_children( + gateway_pids: list[int], +) -> list[tuple[int, str, str]]: + """Capture venv-resident helper processes spawned by the given gateways. + + A gateway spawns helpers straight off the install venv's python — stdio MCP + servers and the perfmon probe among them. Stopping a gateway PID on Windows + does NOT reap those children: a graceful drain leaves them orphaned, and + they keep native ``.pyd`` files mapped. The venv-process guard in ``hermes + update`` then sees them and refuses the update indefinitely, even though the + only thing still touching the venv is a child of the gateway we just + stopped (the July 2026 ``client_lookup_mcp`` / ``hermes-perfmon`` wedge). + + Snapshot the descendant tree BEFORE the gateways are stopped — once a parent + exits, its children's recorded ppid dangles and an after-the-fact descendant + walk misses them. Returns ``(pid, name, cmdline)`` for each venv holder so + the caller can reap them once the gateways are down. The supervised desktop + backend is deliberately excluded (see ``_process_is_desktop_backend``). + Windows-only; best-effort; never raises. + """ + if not _is_windows(): + return [] + try: + import psutil + except Exception: + return [] + + venv_prefix, root_prefix = _venv_lock_prefixes() + skip = {os.getpid()} + try: + for anc in psutil.Process().parents(): + skip.add(int(anc.pid)) + except Exception: + pass + + collected: dict[int, tuple[int, str, str]] = {} + for gpid in gateway_pids: + try: + descendants = psutil.Process(int(gpid)).children(recursive=True) + except Exception: + # gateway already gone / access denied — nothing to walk here + continue + for proc in descendants: + try: + pid = int(proc.pid) + except Exception: + continue + if pid in skip or pid in collected: + continue + try: + exe = proc.exe() + except Exception: + exe = None + try: + cmdline_raw = " ".join(proc.cmdline() or []) + except Exception: + cmdline_raw = "" + try: + cwd = proc.cwd() + except Exception: + cwd = None + if not _process_holds_install_venv( + exe, cmdline_raw, cwd, venv_prefix, root_prefix + ): + continue + if _process_is_desktop_backend(cmdline_raw.lower()): + # A desktop backend should never be parented to a gateway, but + # refuse to reap one even if the tree happens to look that way. + continue + try: + name = proc.name() + except Exception: + name = Path(exe).name if exe else str(pid) + collected[pid] = (pid, str(name), cmdline_raw[:120]) + return list(collected.values()) + + +def _terminate_gateway_venv_children( + children: list[tuple[int, str, str]], + *, + wait_timeout: float = 4.0, +) -> list[int]: + """Terminate the venv helpers captured by ``_snapshot_gateway_venv_children`` + and wait (bounded) for them to exit. + + Called after the gateways themselves are stopped. These are the gateway's + own children (stdio MCP servers, perfmon, ...); with the gateway down they + are orphans that will NOT respawn until the gateway restarts, so terminating + them is safe — and it is exactly what frees the venv so the update's + dependency sync can proceed. The gateway resume path re-spawns them on + restart. Returns the PIDs we asked to terminate. Best-effort; never raises. + """ + if not _is_windows() or not children: + return [] + try: + from gateway.status import terminate_pid + except Exception: + terminate_pid = None # type: ignore[assignment] + + asked: list[int] = [] + for pid, _name, _cmd in children: + try: + if terminate_pid is not None: + # force=True -> taskkill /T /F: also reaps any grandchildren. + terminate_pid(int(pid), force=True) + else: + import psutil + + psutil.Process(int(pid)).kill() + asked.append(int(pid)) + except Exception: + # already gone / access denied — the venv guard re-probe is the + # backstop, so a failed reap at worst leaves the guard to refuse. + pass + + # taskkill returns before the image is fully unloaded; give the reaped PIDs a + # bounded window to actually disappear so the venv guard that runs next sees + # a clean slate (and the .pyd handles are released). + if asked: + try: + import psutil + + deadline = _time.monotonic() + max(float(wait_timeout), 0.0) + pending = set(asked) + while pending and _time.monotonic() < deadline: + pending = {p for p in pending if psutil.pid_exists(p)} + if pending: + _time.sleep(0.1) + except Exception: + pass + return asked + + def _pause_windows_gateways_for_update() -> dict | None: """Stop running Windows gateways before mutating the checkout or venv. @@ -9024,6 +9268,14 @@ def _pause_windows_gateways_for_update() -> dict | None: ) return None + # Snapshot the venv-resident helpers these gateways supervise (stdio MCP + # servers, perfmon) BEFORE we stop them. Stopping a gateway does not reap + # its children on Windows, so without this they survive as orphans holding + # venv .pyd files locked and the venv-process guard below refuses the update + # forever (#50238 follow-up: the July 2026 client_lookup_mcp/perfmon wedge). + # Captured here because a dead parent's dangling ppid defeats a later walk. + venv_children = _snapshot_gateway_venv_children(running_pids) + profile_processes = {} try: profile_processes = { @@ -9076,10 +9328,20 @@ def _pause_windows_gateways_for_update() -> dict | None: except (ProcessLookupError, PermissionError, OSError): pass + # Reap the gateway's orphaned venv helpers now that the gateways are down. + # They will be re-spawned when the gateway restarts (resume path), so this + # only frees the venv for the dependency sync — it does not lose any state. + reaped_children = _terminate_gateway_venv_children(venv_children) + if profiles: print(f" ✓ Paused gateway profile(s): {', '.join(sorted(profiles))}") if force_killed: print(f" → Force-stopped {len(force_killed)} gateway process(es)") + if reaped_children: + print( + f" → Reaped {len(reaped_children)} venv helper process(es) the " + "gateway left running (MCP servers, perfmon)" + ) if unmapped_pids: respawnable = sum(1 for u in unmapped if u.get("argv")) @@ -9413,6 +9675,12 @@ def _cmd_update_impl(args, gateway_mode: bool): print("⚕ Updating Hermes Agent...") print() + # Clear a stale desktop update marker left by a killed hermes-setup.exe + # before anything else — running `hermes update` is the recovery path for + # the venv-lock wedge, and a dead-owner marker would otherwise strand the + # desktop's next launch gate. No-op unless Windows + a dead-owner marker. + _sweep_stale_update_marker() + # On Windows, abort early if another hermes.exe is holding the venv shim # open. Continuing would result in a string of WinError 32 warnings and # then either a deferred-rename leftover or a failed git-pull fast path diff --git a/tests/hermes_cli/test_update_venv_child_reap.py b/tests/hermes_cli/test_update_venv_child_reap.py new file mode 100644 index 0000000000000..9c1a7502f2268 --- /dev/null +++ b/tests/hermes_cli/test_update_venv_child_reap.py @@ -0,0 +1,283 @@ +"""Tests for the Windows venv-lock wedge fix (July 2026 follow-up). + +When ``hermes update`` pauses the gateway, the gateway's venv-resident helper +children (stdio MCP servers, ``hermes-perfmon``) are NOT reaped on Windows — +they survive as orphans holding native ``.pyd`` files locked, so the +venv-process guard refuses the update forever. This covers the fix: + +1. ``_process_holds_install_venv`` — the shared venv-holder predicate. +2. ``_snapshot_gateway_venv_children`` — capture the gateway's venv children + before the gateway is stopped (excluding the supervised desktop backend). +3. ``_terminate_gateway_venv_children`` — reap the captured helpers. +4. ``_sweep_stale_update_marker`` / ``_pid_is_alive`` — clear a stale + ``.hermes-update-in-progress`` marker left by a killed ``hermes-setup.exe``. + +All Windows-specific paths are exercised via ``_is_windows`` patching so they +run on any host (same approach as ``test_update_venv_health``). +""" + +from __future__ import annotations + +import sys +import types +from unittest.mock import MagicMock, patch + +import pytest + +from hermes_cli import main as cli_main + + +# --------------------------------------------------------------------------- +# _process_holds_install_venv (shared predicate) +# --------------------------------------------------------------------------- + + +def _prefixes(tmp_path): + with patch.object(cli_main, "PROJECT_ROOT", tmp_path): + return cli_main._venv_lock_prefixes() + + +def test_predicate_flags_exe_under_venv(tmp_path): + venv_prefix, root_prefix = _prefixes(tmp_path) + exe = str(tmp_path / "venv" / "Scripts" / "python.exe") + assert cli_main._process_holds_install_venv(exe, "python.exe x", "", venv_prefix, root_prefix) + + +def test_predicate_flags_trampoline_by_cmdline(tmp_path): + venv_prefix, root_prefix = _prefixes(tmp_path) + base_py = "C:\\Python311\\python.exe" + venv_path = str(tmp_path / "venv" / "Scripts" / "python.exe") + assert cli_main._process_holds_install_venv( + base_py, f"{base_py} {venv_path} -m x", "", venv_prefix, root_prefix + ) + + +def test_predicate_ignores_unrelated_python(tmp_path): + venv_prefix, root_prefix = _prefixes(tmp_path) + assert not cli_main._process_holds_install_venv( + "C:\\Python311\\python.exe", "python.exe somescript.py", "C:\\other", venv_prefix, root_prefix + ) + + +def test_predicate_empty_exe_is_false(tmp_path): + venv_prefix, root_prefix = _prefixes(tmp_path) + assert not cli_main._process_holds_install_venv(None, "whatever", "", venv_prefix, root_prefix) + + +# --------------------------------------------------------------------------- +# _snapshot_gateway_venv_children +# --------------------------------------------------------------------------- + + +class _FakeProc: + def __init__(self, pid, *, exe="", cmdline=None, cwd="", name="python.exe", children=None): + self.pid = pid + self._exe = exe + self._cmdline = cmdline or [] + self._cwd = cwd + self._name = name + self._children = children or [] + + def exe(self): + return self._exe + + def cmdline(self): + return self._cmdline + + def cwd(self): + return self._cwd + + def name(self): + return self._name + + def parents(self): + return [] + + def children(self, recursive=False): + return self._children + + +def _fake_psutil(by_pid, *, pid_exists=None): + def Process(pid=None): + if pid is None: + return _FakeProc(-1) # "current" process: parents() -> [] + proc = by_pid.get(int(pid)) + if proc is None: + raise RuntimeError("no such process") + return proc + + ns = types.SimpleNamespace(Process=Process) + if pid_exists is not None: + ns.pid_exists = pid_exists + return ns + + +def test_snapshot_off_windows_is_empty(): + with patch.object(cli_main, "_is_windows", return_value=False): + assert cli_main._snapshot_gateway_venv_children([1]) == [] + + +@patch.object(cli_main, "_is_windows", return_value=True) +def test_snapshot_captures_venv_children_excludes_others_and_backend(_win, tmp_path): + venv_py = str(tmp_path / "venv" / "Scripts" / "python.exe") + other_py = "C:\\Python311\\python.exe" + + mcp = _FakeProc(2000, exe=venv_py, cmdline=[venv_py, "client_lookup_mcp.py"], name="python.exe") + perfmon = _FakeProc(2001, exe=venv_py, cmdline=[venv_py, "hermes-perfmon.py"], name="python.exe") + unrelated = _FakeProc(2002, exe=other_py, cmdline=[other_py, "vs-code.py"], cwd="C:\\code") + # A desktop backend that (wrongly) appears under the gateway must NOT be reaped. + backend = _FakeProc(2003, exe=venv_py, cmdline=[venv_py, "-m", "hermes_cli.main", "serve"]) + + gateway = _FakeProc(1000, children=[mcp, perfmon, unrelated, backend]) + fake = _fake_psutil({1000: gateway}) + + with patch.object(cli_main, "PROJECT_ROOT", tmp_path), patch.dict(sys.modules, {"psutil": fake}): + captured = cli_main._snapshot_gateway_venv_children([1000]) + + assert sorted(pid for pid, _n, _c in captured) == [2000, 2001] + + +@patch.object(cli_main, "_is_windows", return_value=True) +def test_snapshot_dedups_across_gateways(_win, tmp_path): + venv_py = str(tmp_path / "venv" / "Scripts" / "python.exe") + shared = _FakeProc(2000, exe=venv_py, cmdline=[venv_py, "mcp.py"]) + g1 = _FakeProc(1000, children=[shared]) + g2 = _FakeProc(1001, children=[shared]) + fake = _fake_psutil({1000: g1, 1001: g2}) + + with patch.object(cli_main, "PROJECT_ROOT", tmp_path), patch.dict(sys.modules, {"psutil": fake}): + captured = cli_main._snapshot_gateway_venv_children([1000, 1001]) + + assert [pid for pid, _n, _c in captured] == [2000] + + +@patch.object(cli_main, "_is_windows", return_value=True) +def test_snapshot_survives_dead_gateway(_win, tmp_path): + """A gateway PID that no longer exists must not raise, just be skipped.""" + fake = _fake_psutil({}) # Process(1000) raises + with patch.object(cli_main, "PROJECT_ROOT", tmp_path), patch.dict(sys.modules, {"psutil": fake}): + assert cli_main._snapshot_gateway_venv_children([1000]) == [] + + +@patch.object(cli_main, "_is_windows", return_value=True) +def test_snapshot_no_psutil_is_empty(_win, tmp_path): + with patch.object(cli_main, "PROJECT_ROOT", tmp_path), patch.dict(sys.modules, {"psutil": None}): + assert cli_main._snapshot_gateway_venv_children([1000]) == [] + + +# --------------------------------------------------------------------------- +# _terminate_gateway_venv_children +# --------------------------------------------------------------------------- + + +def test_terminate_off_windows_is_empty(): + with patch.object(cli_main, "_is_windows", return_value=False): + assert cli_main._terminate_gateway_venv_children([(1, "p", "c")]) == [] + + +@patch.object(cli_main, "_is_windows", return_value=True) +def test_terminate_empty_is_empty(_win): + assert cli_main._terminate_gateway_venv_children([]) == [] + + +@patch.object(cli_main, "_is_windows", return_value=True) +def test_terminate_force_kills_each_child(_win): + fake_term = MagicMock() + with patch("gateway.status.terminate_pid", fake_term): + asked = cli_main._terminate_gateway_venv_children( + [(2000, "python.exe", "mcp"), (2001, "python.exe", "perfmon")], + wait_timeout=0.0, + ) + assert sorted(asked) == [2000, 2001] + killed = sorted(call.args[0] for call in fake_term.call_args_list) + assert killed == [2000, 2001] + assert all(call.kwargs.get("force") is True for call in fake_term.call_args_list) + + +@patch.object(cli_main, "_is_windows", return_value=True) +def test_terminate_is_best_effort_on_error(_win): + """A kill that raises must not abort the reap of the remaining children.""" + def boom(pid, force=False): + if int(pid) == 2000: + raise OSError("access denied") + + with patch("gateway.status.terminate_pid", side_effect=boom): + asked = cli_main._terminate_gateway_venv_children( + [(2000, "python.exe", "a"), (2001, "python.exe", "b")], + wait_timeout=0.0, + ) + # 2000 raised -> not counted; 2001 still reaped. + assert asked == [2001] + + +# --------------------------------------------------------------------------- +# _pid_is_alive +# --------------------------------------------------------------------------- + + +def test_pid_is_alive_uses_psutil(): + fake = types.SimpleNamespace(pid_exists=lambda p: int(p) == 42) + with patch.dict(sys.modules, {"psutil": fake}): + assert cli_main._pid_is_alive(42) is True + assert cli_main._pid_is_alive(7) is False + + +def test_pid_is_alive_conservative_without_psutil(): + with patch.dict(sys.modules, {"psutil": None}): + assert cli_main._pid_is_alive(12345) is True + + +# --------------------------------------------------------------------------- +# _sweep_stale_update_marker +# --------------------------------------------------------------------------- + + +def _write_marker(home, body): + (home / ".hermes-update-in-progress").write_text(body, encoding="utf-8") + + +@patch.object(cli_main, "_is_windows", return_value=True) +def test_sweep_removes_dead_owner_marker(_win, tmp_path): + _write_marker(tmp_path, "999999\n1700000000\n") + with patch("hermes_constants.get_hermes_home", return_value=tmp_path), patch.object( + cli_main, "_pid_is_alive", return_value=False + ): + cli_main._sweep_stale_update_marker() + assert not (tmp_path / ".hermes-update-in-progress").exists() + + +@patch.object(cli_main, "_is_windows", return_value=True) +def test_sweep_preserves_live_owner_marker(_win, tmp_path): + _write_marker(tmp_path, "4321\n1700000000\n") + with patch("hermes_constants.get_hermes_home", return_value=tmp_path), patch.object( + cli_main, "_pid_is_alive", return_value=True + ): + cli_main._sweep_stale_update_marker() + assert (tmp_path / ".hermes-update-in-progress").exists() + + +@patch.object(cli_main, "_is_windows", return_value=True) +def test_sweep_removes_malformed_marker(_win, tmp_path): + """An unparseable pid line can't name a live owner -> treat as stale.""" + _write_marker(tmp_path, "not-a-pid\n") + with patch("hermes_constants.get_hermes_home", return_value=tmp_path): + cli_main._sweep_stale_update_marker() + assert not (tmp_path / ".hermes-update-in-progress").exists() + + +@patch.object(cli_main, "_is_windows", return_value=True) +def test_sweep_absent_marker_is_noop(_win, tmp_path): + with patch("hermes_constants.get_hermes_home", return_value=tmp_path): + cli_main._sweep_stale_update_marker() # must not raise + assert not (tmp_path / ".hermes-update-in-progress").exists() + + +@patch.object(cli_main, "_is_windows", return_value=False) +def test_sweep_off_windows_is_noop(_win, tmp_path): + _write_marker(tmp_path, "999999\n1\n") + with patch("hermes_constants.get_hermes_home", return_value=tmp_path), patch.object( + cli_main, "_pid_is_alive", return_value=False + ): + cli_main._sweep_stale_update_marker() + # POSIX behavior unchanged: the marker is left exactly as-is. + assert (tmp_path / ".hermes-update-in-progress").exists() From 9489f4fa66538afc6b75956e7635644896a9af78 Mon Sep 17 00:00:00 2001 From: Jeff Watts <186512915+lEWFkRAD@users.noreply.github.com> Date: Sat, 11 Jul 2026 12:03:17 -0400 Subject: [PATCH 2/2] fix(update): match desktop backend command tokens --- hermes_cli/main.py | 12 +++++++++++- tests/hermes_cli/test_update_venv_child_reap.py | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/hermes_cli/main.py b/hermes_cli/main.py index 6e2545f6e56c6..a3b053c498212 100644 --- a/hermes_cli/main.py +++ b/hermes_cli/main.py @@ -9076,7 +9076,17 @@ def _process_is_desktop_backend(cmdline_low: str) -> bool: flow (the venv guard refuses and tells the user to close the app instead). Used as a safety exclusion when reaping gateway children. """ - return "serve" in cmdline_low or "dashboard" in cmdline_low + try: + tokens = [token.strip('"\'').lower() for token in shlex.split(cmdline_low, posix=False)] + except ValueError: + tokens = cmdline_low.lower().split() + + # Match the module invocation and its immediate subcommand. Substring + # checks misclassify helpers such as ``mcp-server-time`` as ``serve``. + for index, token in enumerate(tokens[:-1]): + if token == "hermes_cli.main" and tokens[index + 1] in {"serve", "dashboard"}: + return True + return False def _snapshot_gateway_venv_children( diff --git a/tests/hermes_cli/test_update_venv_child_reap.py b/tests/hermes_cli/test_update_venv_child_reap.py index 9c1a7502f2268..b00c46e199a03 100644 --- a/tests/hermes_cli/test_update_venv_child_reap.py +++ b/tests/hermes_cli/test_update_venv_child_reap.py @@ -137,6 +137,20 @@ def test_snapshot_captures_venv_children_excludes_others_and_backend(_win, tmp_p assert sorted(pid for pid, _n, _c in captured) == [2000, 2001] +@patch.object(cli_main, "_is_windows", return_value=True) +def test_snapshot_captures_helpers_with_serve_in_their_name(_win, tmp_path): + venv_py = str(tmp_path / "venv" / "Scripts" / "python.exe") + mcp = _FakeProc(2000, exe=venv_py, cmdline=[venv_py, "-m", "mcp-server-time"]) + server = _FakeProc(2001, exe=venv_py, cmdline=[venv_py, "server.py"]) + gateway = _FakeProc(1000, children=[mcp, server]) + fake = _fake_psutil({1000: gateway}) + + with patch.object(cli_main, "PROJECT_ROOT", tmp_path), patch.dict(sys.modules, {"psutil": fake}): + captured = cli_main._snapshot_gateway_venv_children([1000]) + + assert sorted(pid for pid, _n, _c in captured) == [2000, 2001] + + @patch.object(cli_main, "_is_windows", return_value=True) def test_snapshot_dedups_across_gateways(_win, tmp_path): venv_py = str(tmp_path / "venv" / "Scripts" / "python.exe")