Skip to content

The agent that grows with you

fix(update): judge Windows gateway ownership by home, warn on unreadable ones

teknium1878d902147a9
diff --git a/hermes_cli/update_cmd_windows.py b/hermes_cli/update_cmd_windows.py
index c10533a35f4..eebd3d2ead8 100644
--- a/hermes_cli/update_cmd_windows.py
+++ b/hermes_cli/update_cmd_windows.py
@@ -833,100 +833,13 @@ def _pause_windows_gateway_services(service_gateways, token: dict, profiles: dic
raise RuntimeError(detail) from exc
-def _gateway_process_install_match(pid: int, project_root: Path, home_root: Path | None) -> bool | None:
- """True/False for proven current/foreign ownership; None when the process cannot prove either."""
- psutil = _psutil()
- if psutil is None:
- return None
- try:
- proc = psutil.Process(int(pid))
- except Exception:
- return None
-
- def _under(raw, root: Path | None) -> bool:
- if not raw or root is None:
- return False
- try:
- Path(raw).resolve().relative_to(root.resolve())
- return True
- except (OSError, RuntimeError, ValueError):
- return False
-
- home_match = None
- try:
- raw_home = (proc.environ() or {}).get("HERMES_HOME")
- if raw_home and Path(raw_home).is_absolute():
- home_match = _under(raw_home, home_root)
- if home_match:
- return True
- except Exception:
- pass
-
- try:
- if _under(proc.exe(), project_root):
- return True
- except Exception:
- pass
- try:
- argv = proc.cmdline() or []
- if argv and _under(argv[0], project_root):
- return True
- except Exception:
- pass
- return False if home_match is False else None
-
-
-def _classify_current_install_gateway_pids(pids, *, known_owned=()) -> tuple[list[int], list[int]]:
- """Return (owned, unknown); candidates proven foreign are intentionally omitted."""
- candidates: list[int] = []
- for value in pids:
- try:
- pid = int(value)
- except (TypeError, ValueError):
- continue
- if pid > 0 and pid not in candidates:
- candidates.append(pid)
- if not candidates:
- return [], []
-
- candidate_set = set(candidates)
- owned = {int(pid) for pid in known_owned if int(pid) in candidate_set}
- from hermes_cli.update_cmd import _m
- project_root = Path(_m().PROJECT_ROOT)
-
- try:
- from hermes_cli.process_identity import ledger_entries
- for entry in ledger_entries(project_root=project_root, verified_only=True):
- pid = entry.get("pid")
- if entry.get("purpose") == "gateway" and isinstance(pid, int) and pid in candidate_set:
- owned.add(pid)
- except Exception as exc:
- logger.debug("Could not read current-install gateway ledger: %s", exc)
-
- try:
- from hermes_constants import get_default_hermes_root
- home_root = Path(get_default_hermes_root())
- except Exception:
- home_root = None
-
- unknown: set[int] = set()
- for pid in candidates:
- if pid in owned:
- continue
- match = _gateway_process_install_match(pid, project_root, home_root)
- if match is True:
- owned.add(pid)
- elif match is None:
- unknown.add(pid)
- return (
- [pid for pid in candidates if pid in owned],
- [pid for pid in candidates if pid in unknown],
- )
-
-
-def _current_install_gateway_pids(pids, *, known_owned=()) -> list[int]:
- """Owned half of the install-scoped gateway classification, suitable for mutation/readiness."""
- return _classify_current_install_gateway_pids(pids, known_owned=known_owned)[0]
+def _owned_gateway_pids(pids, *, keep=(), quiet: bool = True) -> list[int]:
+ """*pids* whose live home this update owns, plus *keep* (PIDs mapped to this install's profile
+ PID files / services). The same home scope the POSIX fleet restart uses (#93349): a gateway of
+ another Hermes install, or one whose home cannot be read, is named (unless *quiet*) and left
+ running, never paused, force-killed or replayed (#124659)."""
+ from hermes_cli.update_cmd_fleet import _scoped_manual_gateway_pids
+ return _scoped_manual_gateway_pids(list(pids), keep=keep, quiet=quiet)
def _discover_windows_gateways():
@@ -939,12 +852,10 @@ def _discover_windows_gateways():
service_gateways = find_windows_gateway_services(profile_processes=profile_process_list)
service_gateway_pids = {int(service.gateway_pid) for service in service_gateways}
with _abort_on_error("Could not discover Windows gateway PIDs before update"):
- machine_pids = list(dict.fromkeys(
+ # find_gateway_pids(all_profiles=True) is a HOST-wide scan; only this install's fleet is paused.
+ running_pids = _owned_gateway_pids(dict.fromkeys(
[*find_gateway_pids(all_profiles=True), *sorted(profile_processes), *sorted(service_gateway_pids)]
- ))
- running_pids = _current_install_gateway_pids(
- machine_pids, known_owned=set(profile_processes) | service_gateway_pids
- )
+ ), keep=set(profile_processes) | service_gateway_pids, quiet=False)
return profile_processes, service_gateways, service_gateway_pids, running_pids
@@ -1136,16 +1047,8 @@ def _cold_start_windows_gateway_after_update(token: dict | None = None) -> bool:
from hermes_cli import gateway_windows
from hermes_cli.gateway import find_gateway_pids
with _abort_on_error("Could not re-check gateway liveness before cold-start"):
- owned_pids, unknown_pids = _classify_current_install_gateway_pids(
- find_gateway_pids(all_profiles=True)
- )
- if owned_pids:
- return True
- if unknown_pids:
- logger.debug(
- "Skipping Windows gateway cold-start: ownership is indeterminate for PID(s) %s",
- ", ".join(map(str, unknown_pids)),
- )
+ # Another install's live gateway must not suppress this install's cold start (#124659).
+ if _owned_gateway_pids(find_gateway_pids(all_profiles=True)):
return True
token = token or {}
generation = token.get("attested_generation")
@@ -1361,7 +1264,7 @@ def _verify_relaunched_gateways_alive(token: dict, profiles: dict, unmapped: lis
from hermes_cli import gateway_windows
timeout_s = _relaunch_verify_timeout_s(profiles, unmapped, _pid_exists)
ready_pids = gateway_windows._wait_for_gateway_ready(
- timeout_s=timeout_s, all_profiles=True, pid_filter=_current_install_gateway_pids
+ timeout_s=timeout_s, all_profiles=True, pid_filter=_owned_gateway_pids
)
if not ready_pids:
token["profiles"] = dict(profiles)
diff --git a/hermes_cli/update_fleet_scope.py b/hermes_cli/update_fleet_scope.py
index 6c74c5d3e25..54360c7d39a 100644
--- a/hermes_cli/update_fleet_scope.py
+++ b/hermes_cli/update_fleet_scope.py
@@ -53,13 +53,26 @@ def home_in_update_scope(home, scope: set[Path] | None = None) -> bool:
return resolved in (update_scope_homes() if scope is None else scope)
+def _ledger_gateway_home(pid: int) -> str | None:
+ """Home this install's spawn ledger records for gateway *pid* (``register_self`` at gateway boot),
+ only for an exact live ``(pid, create_time)`` match. Proof for a gateway whose environment is
+ unreadable (elevated, or another account's service) while its create time still is."""
+ with suppress(Exception):
+ from hermes_cli.process_identity import ledger_entries
+ for entry in ledger_entries(verified_only=True):
+ if entry.get("pid") == pid and entry.get("purpose") == "gateway":
+ return entry.get("hermes_home") or None
+ return None
+
+
def gateway_pid_in_update_scope(pid: int, scope: set[Path] | None = None) -> bool | None:
"""Does gateway *pid* run on a home this update owns? ``None`` when its home cannot be read."""
from hermes_cli.dashboard_procs import _hermes_home_for_pid
try:
home = _hermes_home_for_pid(pid)
except Exception:
- return None
+ home = None
+ home = home or _ledger_gateway_home(pid)
if home is None:
return None
return home_in_update_scope(home, scope)
diff --git a/tests/e2e/core/windows_update/_machine.py b/tests/e2e/core/windows_update/_machine.py
index 890a6524e01..c85c463ddbd 100644
--- a/tests/e2e/core/windows_update/_machine.py
+++ b/tests/e2e/core/windows_update/_machine.py
@@ -28,9 +28,10 @@ carries 159-character paths, so a profile any deeper than a real one would hit M
where no user does. The installer also prepends its bin dir to the user PATH in HKCU;
the machine restores that value on teardown.
-Machines run in parallel, but ``hermes update`` on Windows pauses every gateway on the
-host, including other installs' (#124659). Updates and gateway lifetimes therefore take
-a job-wide lock (``gateway_phase``); installs, turns and everything else stay parallel.
+Machines run in parallel. Updates and gateway lifetimes take a job-wide lock
+(``gateway_phase``) so each journey's gateway hand-off is deterministic; installs, turns and
+everything else stay parallel. One install's update sparing another's gateway (#124659) is
+its own journey (test_update_spares_other_installs.py).
The suite mutates HKCU and downloads a toolchain per machine, so it only runs where
``HERMES_E2E_WINDOWS_INSTALL=1`` (the CI job sets it).
@@ -327,11 +328,8 @@ class Machine:
@contextlib.contextmanager
def gateway_phase(self):
- """Job-wide mutex for updates and gateway lifetimes (reentrant within a machine).
-
- ``hermes update`` on Windows discovers gateways host-wide and stops ones it cannot map
- to its own profiles (#124659), so one machine's update would kill another machine's
- gateway. Real users rarely run two installs side by side; this suite always does."""
+ """Job-wide mutex for updates and gateway lifetimes (reentrant within a machine), so no
+ journey's gateway hand-off races another machine's update."""
if self._lock_depth:
self._lock_depth += 1
try:
diff --git a/tests/e2e/core/windows_update/test_update_spares_other_installs.py b/tests/e2e/core/windows_update/test_update_spares_other_installs.py
new file mode 100644
index 00000000000..3f9e4e4b0dd
--- /dev/null
+++ b/tests/e2e/core/windows_update/test_update_spares_other_installs.py
@@ -0,0 +1,88 @@
+"""Two Hermes installs on one Windows host: one install's ``hermes update`` leaves the other's
+gateway alone (#124659).
+
+Failure class: update blast radius. The updater's gateway discovery scans the whole process
+table; a gateway of another install (its own ``%LOCALAPPDATA%\\hermes``, its own checkout and
+venv) holds none of the updating install's files, so the update must neither stop it nor try to
+replay it. ``neighbour`` updates while ``host`` serves a gateway; both are real installs.
+"""
+
+from __future__ import annotations
+
+from concurrent.futures import ThreadPoolExecutor
+
+import psutil
+import pytest
+
+from tests.e2e.core.windows_update._machine import (
+ REQUIRES_OPT_IN,
+ UPDATE_TIMEOUT,
+ Journey,
+ fail_with,
+ new_machine,
+)
+from tests.fakes.fake_llm_provider import FakeLLMServer
+
+pytestmark = [pytest.mark.platforms("windows"), pytest.mark.integration,
+ pytest.mark.live_system_guard_bypass, REQUIRES_OPT_IN]
+
+_FOREIGN_STOP = ("without profile mapping", "Force-stopped")
+
+
+def _alive(pid: int) -> bool:
+ try:
+ proc = psutil.Process(pid)
+ return proc.is_running() and proc.status() != psutil.STATUS_ZOMBIE
+ except psutil.Error:
+ return False
+
+
[email protected](scope="module")
+def journey(tmp_path_factory):
+ with FakeLLMServer() as srv:
+ host = new_machine(tmp_path_factory.mktemp("host"), srv.base_url, label="host", system_git=True)
+ neighbour = new_machine(tmp_path_factory.mktemp("nbr"), srv.base_url, label="nbr", system_git=True)
+ j = Journey(host)
+ j.results["neighbour"] = neighbour
+ try:
+ with ThreadPoolExecutor(2) as pool:
+ installs = list(pool.map(lambda m: m.install(), (host, neighbour)))
+ j.step("installs_ok", lambda: [j.require(m.profile_name, run.returncode == 0,
+ f"install.ps1 exited {run.returncode}", run)
+ for m, run in zip((host, neighbour), installs)])
+ if j.ok("installs_ok"):
+ # One job-wide gateway phase for both machines; ``neighbour.hermes`` (not ``.update``)
+ # because the phase lock is per machine and this module holds it through ``host``.
+ with host.gateway_phase():
+ j.step("spawn", host.spawn_gateway)
+ j.step("host_before", host.wait_gateway_running)
+ neighbour.advance()
+ j.step("neighbour_update", lambda: neighbour.hermes(
+ "update", "--yes", label="update", timeout=UPDATE_TIMEOUT))
+ # Liveness is read here, before ``kill_owned`` tears the gateway down.
+ j.step("host_after", lambda: {**host.gateway_state(),
+ "alive": _alive(int(j["host_before"].get("pid") or 0))})
+ host.kill_owned()
+ neighbour.kill_owned()
+ yield j
+ finally:
+ neighbour.teardown()
+ host.teardown()
+
+
+def test_neighbour_update_leaves_this_installs_gateway_running(journey: Journey) -> None:
+ m, before, run = journey.machine, journey["host_before"], journey["neighbour_update"]
+ pid = int(before.get("pid") or 0)
+ after = journey["host_after"]
+ assert after["alive"] and after.get("pid") == pid and after.get("gateway_state") == "running", fail_with(
+ m, f"another install's `hermes update` stopped this install's gateway (pid {pid}); "
+ f"alive={after['alive']}, gateway_state after: {after.get('gateway_state')!r} pid {after.get('pid')}", run)
+
+
+def test_neighbour_update_stops_no_foreign_gateway(journey: Journey) -> None:
+ n, run = journey["neighbour"], journey["neighbour_update"]
+ journey["host_before"] # a foreign gateway was running during the update
+ stopped = [line.strip() for line in run.stdout.splitlines() if any(s in line for s in _FOREIGN_STOP)]
+ assert run.returncode == 0 and not stopped, fail_with(
+ n, f"`hermes update` without a gateway of its own reported stopping gateways "
+ f"(rc={run.returncode}): {stopped}", run)
diff --git a/tests/hermes_cli/test_update_windows_cross_install_gateway.py b/tests/hermes_cli/test_update_windows_cross_install_gateway.py
index e9a3a43bcc4..c1b16e3da64 100644
--- a/tests/hermes_cli/test_update_windows_cross_install_gateway.py
+++ b/tests/hermes_cli/test_update_windows_cross_install_gateway.py
@@ -1,176 +1,72 @@
-"""Windows update gateway ownership is install-scoped, not machine-scoped (#124659)."""
+"""``hermes update`` on Windows pauses only its own install's gateways (#124659).
-from types import SimpleNamespace
+The host-wide gateway scan sees every install's gateway. Each process below carries the live
+environment a gateway of one install has; ownership is read from it by the same home scope the
+POSIX fleet restart uses, so a gateway of another install is never stopped and never suppresses
+this install's cold start.
+"""
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+import hermes_cli.main_install_repair as main_install_repair
from hermes_cli import gateway as gateway_mod
from hermes_cli import gateway_windows
from hermes_cli import main as cli_main
-import hermes_cli.main_install_repair as main_install_repair
-from hermes_cli import process_identity
from hermes_cli import update_cmd
from hermes_cli import update_cmd_windows
-def test_current_install_filter_keeps_ledger_owned_unmapped_gateway(monkeypatch, tmp_path):
- root = tmp_path / "checkout"
- home = tmp_path / "home"
- root.mkdir()
- home.mkdir()
- monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)
- monkeypatch.setenv("HERMES_HOME", str(home))
- monkeypatch.setattr(
- process_identity, "ledger_entries", lambda **_kwargs: [{"pid": 101, "purpose": "gateway"}]
- )
- monkeypatch.setattr(update_cmd_windows, "_psutil", lambda: None)
-
- assert update_cmd_windows._current_install_gateway_pids([101, 202]) == [101]
-
-
-def test_legacy_home_proves_owned_unmapped_gateway(monkeypatch, tmp_path):
- root = tmp_path / "checkout"
- home = tmp_path / "hermes"
- foreign = tmp_path / "foreign"
- for path in (root, home, foreign):
- path.mkdir()
- profile_home = home / "profiles" / "work"
- profile_home.mkdir(parents=True)
- monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)
- monkeypatch.setenv("HERMES_HOME", str(home))
- monkeypatch.setattr(process_identity, "ledger_entries", lambda **_kwargs: [])
-
- class Proc:
- def __init__(self, pid):
- self.pid = pid
-
- def environ(self):
- return {"HERMES_HOME": str(profile_home if self.pid == 101 else foreign)}
-
- def exe(self):
- return str(foreign / "python.exe")
-
- def cmdline(self):
- return [str(foreign / "python.exe")]
-
- monkeypatch.setattr(update_cmd_windows, "_psutil", lambda: SimpleNamespace(Process=Proc))
-
- owned, unknown = update_cmd_windows._classify_current_install_gateway_pids([101, 202])
- assert owned == [101]
- assert unknown == []
-
-
-def test_cwd_alone_is_not_destructive_ownership(monkeypatch, tmp_path):
- root = tmp_path / "checkout"
- home = tmp_path / "hermes"
- foreign = tmp_path / "foreign"
- for path in (root, home, foreign):
- path.mkdir()
- monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)
- monkeypatch.setenv("HERMES_HOME", str(home))
- monkeypatch.setattr(process_identity, "ledger_entries", lambda **_kwargs: [])
-
- proc = SimpleNamespace(
- environ=lambda: {},
- exe=lambda: str(foreign / "python.exe"),
- cmdline=lambda: [str(foreign / "python.exe")],
- cwd=lambda: str(root),
- )
- monkeypatch.setattr(
- update_cmd_windows, "_psutil", lambda: SimpleNamespace(Process=lambda _pid: proc)
- )
-
- owned, unknown = update_cmd_windows._classify_current_install_gateway_pids([202])
- assert owned == []
- assert unknown == [202]
-
-
-def test_discovery_keeps_owned_unmapped_and_excludes_foreign(monkeypatch):
- monkeypatch.setattr(gateway_mod, "find_profile_gateway_processes", lambda **_kwargs: [])
- monkeypatch.setattr(gateway_mod, "find_windows_gateway_services", lambda **_kwargs: [])
- monkeypatch.setattr(gateway_mod, "find_gateway_pids", lambda **_kwargs: [101, 202])
- monkeypatch.setattr(
- update_cmd_windows,
- "_current_install_gateway_pids",
- lambda pids, **_kwargs: [pid for pid in pids if pid == 101],
- )
-
- profiles, services, service_pids, running = update_cmd_windows._discover_windows_gateways()
-
- assert profiles == {}
- assert services == []
- assert service_pids == set()
- assert running == [101]
-
-
-def test_foreign_gateway_does_not_suppress_current_install_cold_start(monkeypatch):
+def host_gateways(tmp_path):
+ """``{name: pid}`` of one long-lived process per install on the host."""
+ other = tmp_path / "other-user"
+ installs = {
+ "own": {"HERMES_HOME": os.environ["HERMES_HOME"]},
+ "foreign": {"HERMES_HOME": str(other / ".hermes")},
+ # Another install at its platform default home: no HERMES_HOME in its environment.
+ "foreign_default": {"HOME": str(other), "USERPROFILE": str(other),
+ "LOCALAPPDATA": str(other / "AppData" / "Local")},
+ }
+ base = {k: v for k, v in os.environ.items()
+ if k not in ("HERMES_HOME", "HOME", "USERPROFILE", "LOCALAPPDATA")}
+ procs = {
+ name: subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"],
+ env={**base, **extra}, stdin=subprocess.DEVNULL)
+ for name, extra in installs.items()
+ }
+ try:
+ yield {name: proc.pid for name, proc in procs.items()}
+ finally:
+ for proc in procs.values():
+ proc.kill()
+ proc.wait()
+
+
+def test_update_pause_takes_only_this_installs_gateways(monkeypatch, host_gateways):
+ monkeypatch.setattr(gateway_mod, "find_profile_gateway_processes", lambda **_kw: [])
+ monkeypatch.setattr(gateway_mod, "find_windows_gateway_services", lambda **_kw: [])
+ monkeypatch.setattr(gateway_mod, "find_gateway_pids", lambda **_kw: list(host_gateways.values()))
+
+ running_pids = update_cmd_windows._discover_windows_gateways()[3]
+
+ assert running_pids == [host_gateways["own"]]
+
+
+def test_foreign_gateways_do_not_suppress_cold_start(monkeypatch, host_gateways):
monkeypatch.setattr(cli_main, "_is_windows", lambda: True)
monkeypatch.setattr(main_install_repair, "_is_windows", lambda: True)
- monkeypatch.setattr(gateway_mod, "find_gateway_pids", lambda **_kwargs: [202])
- monkeypatch.setattr(
- update_cmd_windows,
- "_classify_current_install_gateway_pids",
- lambda _pids, **_kwargs: ([], []),
- )
monkeypatch.setattr(update_cmd, "_desktop_owns_gateway_lifecycle", lambda: False)
-
+ monkeypatch.setattr(gateway_mod, "find_gateway_pids",
+ lambda **_kw: [host_gateways["foreign"], host_gateways["foreign_default"]])
spawned = []
- monkeypatch.setattr(gateway_windows, "_spawn_detached", lambda: spawned.append(True) or 4242)
- monkeypatch.setattr(gateway_windows, "_wait_for_gateway_ready", lambda *a, **k: [4242])
- monkeypatch.setattr(gateway_windows, "_write_start_attestation", lambda *a, **k: None)
+ monkeypatch.setattr(gateway_windows, "_spawn_detached", lambda: spawned.append(4242) or 4242)
+ monkeypatch.setattr(gateway_windows, "_wait_for_gateway_ready", lambda *_a, **_kw: [4242])
+ monkeypatch.setattr(gateway_windows, "_write_start_attestation", lambda *_a, **_kw: None)
assert update_cmd_windows._cold_start_windows_gateway_after_update({"attested_generation": None})
- assert spawned == [True]
-
-
-def test_unknown_gateway_conservatively_suppresses_cold_start(monkeypatch):
- monkeypatch.setattr(cli_main, "_is_windows", lambda: True)
- monkeypatch.setattr(main_install_repair, "_is_windows", lambda: True)
- monkeypatch.setattr(gateway_mod, "find_gateway_pids", lambda **_kwargs: [303])
- monkeypatch.setattr(
- update_cmd_windows,
- "_classify_current_install_gateway_pids",
- lambda _pids, **_kwargs: ([], [303]),
- )
- monkeypatch.setattr(update_cmd, "_desktop_owns_gateway_lifecycle", lambda: False)
- monkeypatch.setattr(
- gateway_windows,
- "_spawn_detached",
- lambda: (_ for _ in ()).throw(AssertionError("must not spawn with unknown ownership")),
- )
-
- assert update_cmd_windows._cold_start_windows_gateway_after_update(
- {"attested_generation": None}
- )
-
-
-def test_readiness_filter_waits_past_foreign_gateway(monkeypatch):
- snapshots = iter(([202], [202, 4242]))
- monkeypatch.setattr(
- gateway_mod, "find_gateway_pids", lambda **_kwargs: next(snapshots, [202, 4242])
- )
- monkeypatch.setattr(gateway_windows.time, "sleep", lambda _seconds: None)
-
- ready = gateway_windows._wait_for_gateway_ready(
- timeout_s=1.0,
- confirm_s=0,
- all_profiles=True,
- pid_filter=lambda pids: [pid for pid in pids if pid == 4242],
- )
-
- assert ready == [4242]
-
-
-def test_post_relaunch_verification_uses_install_filter(monkeypatch):
- captured = {}
-
- def wait_for_ready(**kwargs):
- captured.update(kwargs)
- return [4242]
-
- monkeypatch.setattr(gateway_windows, "_wait_for_gateway_ready", wait_for_ready)
- monkeypatch.setattr(gateway_windows, "_write_start_attestation", lambda *a, **k: None)
- monkeypatch.setattr(update_cmd_windows, "_relaunch_verify_timeout_s", lambda *_args: 1.0)
-
- update_cmd_windows._verify_relaunched_gateways_alive({}, {}, [])
-
- assert captured["all_profiles"] is True
- assert captured["pid_filter"] is update_cmd_windows._current_install_gateway_pids
+ assert spawned == [4242]