The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: an unmapped gateway's restart debt is retired only by its own runtime
Teknium74ea8010c034
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.pyindex 8bd8a7bff10..c285babcaa4 100644--- a/hermes_cli/gateway.py+++ b/hermes_cli/gateway.py@@ -977,9 +977,9 @@ def _prepare_profile_gateway_update_restart(profile: str, pid: int) -> str | Nonreturn None-def launch_detached_gateway_restart_by_cmdline(old_pid: int, run_argv: list[str]) -> bool:- """Relaunch a gateway with no profile→PID-file mapping by replaying its captured argv after exit."""- return old_pid > 0 and bool(run_argv) and _spawn_gateway_restart_watcher(old_pid, list(run_argv))+def launch_detached_gateway_restart_by_cmdline(old_pid: int, run_argv: list[str], home: str | None = None) -> bool:+ """Relaunch a gateway with no profile→PID-file mapping by replaying its captured argv (on Windows under ``home``, the one it ran on) after exit."""+ return old_pid > 0 and bool(run_argv) and _spawn_gateway_restart_watcher(old_pid, list(run_argv), home=home)def launch_detached_profile_gateway_restart(profile: str, old_pid: int) -> bool:@@ -1055,7 +1055,7 @@ def _host_gateway_watcher_env() -> dict[str, str]:return env-def _spawn_gateway_restart_watcher(old_pid: int, run_argv: list[str], *, host: bool | None = None) -> bool:+def _spawn_gateway_restart_watcher(old_pid: int, run_argv: list[str], *, host: bool | None = None, home: str | None = None) -> bool:"""Spawn the detached watcher that respawns ``run_argv`` once ``old_pid`` exits. Watcher and respawnboth need platform-appropriate detach: POSIX setsid; on Windows ``start_new_session`` does NOT detach(the watcher would die with the CLI console), so ``windows_detach_popen_kwargs()`` supplies flags."""@@ -1074,7 +1074,7 @@ def _spawn_gateway_restart_watcher(old_pid: int, run_argv: list[str], *, host: bif sys.platform == "win32":try:from hermes_cli.gateway_windows import windowless_gateway_restart_spec- run_argv, respawn_cwd, respawn_env_overlay = windowless_gateway_restart_spec(list(run_argv))+ run_argv, respawn_cwd, respawn_env_overlay = windowless_gateway_restart_spec(list(run_argv), home=home)except Exception:# Fall back to the original argv: a visible window beats a failed respawn.respawn_cwd = ""diff --git a/hermes_cli/gateway_windows.py b/hermes_cli/gateway_windows.pyindex 48219f43e11..5ebccca3120 100644--- a/hermes_cli/gateway_windows.py+++ b/hermes_cli/gateway_windows.py@@ -717,7 +717,7 @@ def _build_gateway_argv(home: Path | None = None) -> tuple[list[str], str, dict[return _gateway_run_argv(python_exe, profile_arg), working_dir, env_overlay-def windowless_gateway_restart_spec(run_argv: list[str]) -> tuple[list[str], str, dict[str, str]]:+def windowless_gateway_restart_spec(run_argv: list[str], home: str | None = None) -> tuple[list[str], str, dict[str, str]]:"""(argv, cwd, env overlay) for a hidden-console gateway respawn; arguments after the interpreterare preserved verbatim. Non-Windows or a non-python argv[0] → argv unchanged, empty overlay.@@ -728,6 +728,8 @@ def windowless_gateway_restart_spec(run_argv: list[str]) -> tuple[list[str], strevery console-subsystem child allocated a visible conhost). This helper now only normalizes theinterpreter via ``_resolve_detached_python`` and supplies the stable cwd + env overlay (HERMES_HOME,VIRTUAL_ENV, PYTHONPATH) so the respawn doesn't depend on the watcher's transient working directory.+ ``HERMES_HOME`` is ``home`` when given: a replayed selectorless argv runs on whatever home its+ environment names, so the paused runtime's home, not the updater's, must come back."""if not run_argv or sys.platform != "win32":return run_argv, "", {}@@ -739,7 +741,7 @@ def windowless_gateway_restart_spec(run_argv: list[str]) -> tuple[list[str], strreturn run_argv, "", {}try:- hermes_home = str(_hermes_home().resolve())+ hermes_home = str(Path(home or _hermes_home()).resolve())except Exception:hermes_home = ""env_overlay: dict[str, str] = {"PYTHONIOENCODING": "utf-8", "HERMES_GATEWAY_DETACHED": "1", "VIRTUAL_ENV": str(venv_dir)}diff --git a/hermes_cli/update_cmd_windows.py b/hermes_cli/update_cmd_windows.pyindex 7bf08484b73..fd9c1c53a8b 100644--- a/hermes_cli/update_cmd_windows.py+++ b/hermes_cli/update_cmd_windows.py@@ -948,15 +948,18 @@ def _pause_windows_gateways_for_update() -> dict | None:if not running_pids:return _cold_start_pause_token(adopted, claims)unmapped_pids = [pid for pid in running_pids if pid not in profile_processes and pid not in service_gateway_pids]+ from gateway.status import get_process_start_time+ from hermes_cli.dashboard_procs import _hermes_home_for_pid+ born = {int(pid): get_process_start_time(int(pid)) for pid in running_pids} # the processes discovered# Snapshot unmapped gateways' argv *before* anything stops so resume (or a later launch) can replay it.- # Unmapped = no profile->PID-file mapping (e.g. Scheduled Task ``pythonw.exe -m ...``).+ # Unmapped = no profile->PID-file mapping (e.g. Scheduled Task ``pythonw.exe -m ...``). Two homes can+ # run identical selectorless argv, so the home and birth identify the runtime the replay must restore.unmapped = [{"pid": int(pid), "argv": _try_call(lambda p=int(pid): _capture_gateway_argv(p),- "Could not capture argv for unmapped gateway %s: %s", int(pid))}+ "Could not capture argv for unmapped gateway %s: %s", int(pid)),+ "home": _hermes_home_for_pid(int(pid)), "ct": born[int(pid)]}for pid in unmapped_pids]- from gateway.status import get_process_start_time- born = {int(pid): get_process_start_time(int(pid)) for pid in running_pids} # the processes discoveredintended = {"resume_needed": True, "unmapped_pids": unmapped_pids, "unmapped": unmapped,"profiles": {str(profile_processes[pid].profile): int(pid) for pid in running_pids@@ -1354,7 +1357,9 @@ def _relaunch_paused_gateways(profiles: dict, unmapped: list) -> tuple[dict, lislaunched_unmapped = []for entry in unmapped:argv, old_pid = entry.get("argv"), entry.get("pid")- if argv and old_pid and _try_call(lambda o=old_pid, a=argv: launch_detached_gateway_restart_by_cmdline(int(o), list(a)),+ # On the paused runtime's home (None on a pre-home record: the updater's own home, as before).+ if argv and old_pid and _try_call(lambda o=old_pid, a=argv, h=entry.get("home"): launch_detached_gateway_restart_by_cmdline(+ int(o), list(a), home=h),"Could not restart unmapped Windows gateway (pid %s) after update: %s", old_pid):launched_unmapped.append(entry)return launched, launched_unmapped@@ -1391,16 +1396,30 @@ def _relaunch_verify_timeout_s(profiles: dict, unmapped: list, pid_exists) -> fldef _unmapped_ready_filter(entry: dict, taken: set):- """``pid_filter`` matching the gateway an unmapped entry's argv replay started: same arguments- after the (normalized) interpreter, not the old pid, not one another entry already vouched for."""+ """``pid_filter`` matching the gateway an unmapped entry's replay started: a gateway running the+ same arguments after the (normalized) interpreter on the entry's home, born after the process it+ replaces, not one another entry already vouched for. Two homes can run identical selectorless argv,+ so argv alone would let home B's gateway retire home A's debt (a service gateway on another home+ included; on A's home only one gateway can run). An entry recorded before ``home`` was captured+ keeps the argv-only match: nothing else identifies it."""import psutil+ from gateway.status import _looks_like_gateway_process, _same_hermes_home, get_process_start_time+ from hermes_cli.dashboard_procs import _hermes_home_for_pidtail, old = list(entry.get("argv") or [])[1:], int(entry.get("pid") or 0)+ home, old_ct = entry.get("home"), entry.get("ct")++ def same_runtime(pid: int) -> bool:+ if not home:+ return True+ live_home, ct = _hermes_home_for_pid(pid), get_process_start_time(pid)+ return live_home is not None and _same_hermes_home(live_home, home) and (old_ct is None or ct is None or ct > old_ct)def matches(pid: int) -> bool:if pid == old or pid in taken:return Falsetry:- return list(psutil.Process(pid).cmdline() or [])[1:] == tail+ return (list(psutil.Process(pid).cmdline() or [])[1:] == tail and _looks_like_gateway_process(pid)+ and same_runtime(pid))except (psutil.Error, OSError, ValueError): # exited, access denied, zombie, invalid pidreturn Falsereturn lambda pids: [pid for pid in _owned_gateway_pids(pids) if matches(int(pid))]diff --git a/tests/hermes_cli/test_update_pause_unmapped_identity.py b/tests/hermes_cli/test_update_pause_unmapped_identity.pynew file mode 100644index 00000000000..43627b97faa--- /dev/null+++ b/tests/hermes_cli/test_update_pause_unmapped_identity.py@@ -0,0 +1,74 @@+"""An unmapped gateway's restart debt is retired only by ITS runtime (#132338 review C).++The pause records an unmapped gateway (no profile PID file, e.g. a Scheduled Task) by the argv it+replays. Two homes can run identical selectorless argv, their environment picking the home, so the+readiness predicate must also match the home the paused runtime ran on: otherwise home B's gateway,+already back after a partial recovery, retires home A's debt while A stays down.++Real processes (argv shaped like ``hermes gateway run``, each under its own ``HERMES_HOME``) and the+real predicate; the fleet discovery that hands it candidate PIDs is the only thing bypassed. The+replay restores that home too: the respawn's ``HERMES_HOME`` is the paused runtime's, not the updater's.+"""++from __future__ import annotations++import os+import subprocess+import sys+import time++import pytest++from gateway.status import get_process_start_time+from hermes_cli.update_cmd_windows import _unmapped_ready_filter+++def spawn(tmp_path):+ entry = tmp_path / "bin" / "hermes" # a ``hermes`` entry token: the cmdline reads as a gateway+ entry.parent.mkdir()+ entry.write_text("import time\ntime.sleep(60)\n", encoding="utf-8")+ argv = [sys.executable, str(entry), "gateway", "run"]+ procs: list[subprocess.Popen] = []++ def _spawn(home) -> subprocess.Popen:+ proc = subprocess.Popen(argv, env={**os.environ, "HERMES_HOME": str(home)})+ procs.append(proc) # Popen returns after exec: the gateway argv and environment are in place+ return proc++ yield _spawn, argv+ for proc in procs:+ proc.kill()+ proc.wait(timeout=10)++[email protected]("linux")[email protected]_gateway_lookalike # stub children that sleep; the fixture reaps them+def test_an_equal_argv_gateway_of_another_home_never_retires_the_unmapped_debt(spawn):+ spawn, argv = spawn+ root = os.environ["HERMES_HOME"] # the sandboxed home this update owns, with two profiles+ home_a, home_b = (os.path.join(root, "profiles", name) for name in ("a", "b"))+ os.makedirs(home_a)+ os.makedirs(home_b)+ old = spawn(home_a)+ entry = {"pid": old.pid, "argv": argv, "home": home_a, "ct": get_process_start_time(old.pid)}+ old.kill()+ old.wait(timeout=10)+ time.sleep(0.05) # a later clock tick: the replacement is born after the process it replaces++ sibling = spawn(home_b)+ assert _unmapped_ready_filter(entry, set())([sibling.pid]) == [], \+ "home B's gateway with A's argv retired A's restart debt"+ replacement = spawn(home_a)+ assert _unmapped_ready_filter(entry, set())([sibling.pid, replacement.pid]) == [replacement.pid]++[email protected]("windows") # the spec overlays the environment only on Windows+def test_an_unmapped_replay_runs_on_the_home_its_runtime_ran_on(tmp_path):+ from hermes_cli.gateway_windows import windowless_gateway_restart_spec++ paused_home = tmp_path / "profiles" / "a"+ paused_home.mkdir(parents=True)+ _argv, _cwd, env = windowless_gateway_restart_spec(+ [sys.executable, "-m", "hermes_cli.main", "gateway", "run"], home=str(paused_home))+ assert env["HERMES_HOME"] == str(paused_home.resolve()), "the replay ran on the updater's home"