The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): Windows shim hand-off child waits for hermes.exe to exit and owns the gateway resume
teknium1168012585edb
diff --git a/hermes_cli/main_install_repair.py b/hermes_cli/main_install_repair.pyindex e4626ae008f..2e3508bced9 100644--- a/hermes_cli/main_install_repair.py+++ b/hermes_cli/main_install_repair.py@@ -356,7 +356,7 @@ def _windows_running_hermes_launcher_locked() -> bool:_UPDATE_REEXEC_ENV = "HERMES_UPDATE_REEXEC"-def _reexec_dependency_sync_off_windows_shim() -> bool:+def _reexec_dependency_sync_off_windows_shim(gateway_resume: dict | None = None) -> bool:"""Hand the dependency sync to the venv interpreter, off the console shim.Returns True when a child was spawned and the caller must exit at once (releasing the@@ -373,12 +373,10 @@ def _reexec_dependency_sync_off_windows_shim() -> bool:date" early return from swallowing the sync. ``.update-incomplete`` is already written, soa child that dies mid-install is finished by the next launch's recovery.- Called at the dependency-sync boundary, NOT at the top of the command — the same placement rule as the- native-module deferral beside it, and for the same reason (#86735): a hand-off that fires before the- fetch detaches every run, including the ``Already up to date!`` no-op that never touches the venv at- all, and it takes the interactive prompts with it. By the time we reach here the code swap is done and- every question — stash, branch switch, config migration — has already been asked and answered in the- user's own console.+ The child owns the Windows gateway resume from the moment it exists: ``gateway_resume``+ travels in its env and this process's copy is disarmed, so the parent exits at once instead+ of relaunching gateways while it still holds the shim (#101600). The child waits for this+ pid before its own pause/venv work (``update_handoff.wait_for_shim_parent_exit``).``venv\\Scripts\\hermes.exe`` is a launcher that runs the interpreter with the shim as its script andholds it open without ``FILE_SHARE_DELETE`` for the whole command, so the quarantine rename is refusedand uv fails to replace it with os error 32 (#88838, #89599).@@ -389,12 +387,16 @@ def _reexec_dependency_sync_off_windows_shim() -> bool:if shim is None:return Falsefrom hermes_constants import venv_python_path+ from hermes_cli.update_handoff import detached_shim_child_envpython_exe = venv_python_path(shim.parent.parent, windows=True)cmd = [str(python_exe), "-m", "hermes_cli.main", *sys.argv[1:]]if python_exe.is_file():try:subprocess.Popen(- cmd, env={**os.environ, _UPDATE_REEXEC_ENV: "1"}, stdin=subprocess.DEVNULL)+ cmd, env=detached_shim_child_env({**os.environ, _UPDATE_REEXEC_ENV: "1"}, gateway_resume),+ stdin=subprocess.DEVNULL)+ if gateway_resume is not None:+ gateway_resume["resume_needed"] = Falseprint(f"→ Windows: {shim.name} cannot replace itself while it runs; ""finishing the dependency install under the venv Python.")diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex 966987d7a4e..8cfe6fad18d 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -1534,6 +1534,11 @@ def _cmd_update_impl(args, gateway_mode: bool):opts = _resolve_update_options(args, gateway_mode)gw_input_fn, assume_yes = opts.gw_input_fn, opts.assume_yes+ # A child spawned off hermes.exe: the parent still holds the shim (and the venv python)+ # until it exits — nothing below may scan holders, pause gateways or rename shims before.+ from hermes_cli.update_handoff import adopt_handed_off_gateway_resume, wait_for_shim_parent_exit+ wait_for_shim_parent_exit()+if getattr(args, "post_swap", None):# Second half of a run whose pre-pull interpreter stopped at the code swap._run_post_swap_phase(args, gateway_mode)@@ -1550,7 +1555,9 @@ def _cmd_update_impl(args, gateway_mode: bool):pre_update_snapshot_id = _m()._run_pre_update_backup(args)_record_pre_update_backup_outcome(args, pre_update_snapshot_id)- _windows_gateway_resume = _m()._pause_windows_gateways_for_update()+ # A legacy re-exec child resumes exactly the fleet its parent stopped; re-running discovery+ # here found the parent's just-relaunched gateway and force-killed it (#101600).+ _windows_gateway_resume = adopt_handed_off_gateway_resume() or _m()._pause_windows_gateways_for_update()if _windows_gateway_resume:import atexit as _atexit_atexit.register(_m()._resume_windows_gateways_after_update, _windows_gateway_resume)diff --git a/hermes_cli/update_cmd_deps.py b/hermes_cli/update_cmd_deps.pyindex dadad722e8f..2bf2c5114ff 100644--- a/hermes_cli/update_cmd_deps.py+++ b/hermes_cli/update_cmd_deps.py@@ -829,14 +829,13 @@ def _abort_dependency_sync_if_self_locked(gateway_resume=None) -> None:locked = _m()._detect_self_loaded_native_modules()if locked:_m()._defer_update_for_self_lock(locked)- exit_code = 2- elif _m()._reexec_dependency_sync_off_windows_shim():- exit_code = 0- else:- return- if gateway_resume is not None:- _m()._resume_windows_gateways_after_update(gateway_resume)- sys.exit(exit_code)+ if gateway_resume is not None:+ _m()._resume_windows_gateways_after_update(gateway_resume)+ sys.exit(2)+ if _m()._reexec_dependency_sync_off_windows_shim(gateway_resume):+ # The child adopted the pause token; resuming here would keep this shim alive+ # (and hermes.exe locked) exactly while the child needs it gone (#101600).+ sys.exit(0)def _defer_update_for_self_lock(loaded: list[str]) -> None:diff --git a/hermes_cli/update_handoff.py b/hermes_cli/update_handoff.pyindex 68cc3aa7ab5..84be98683d2 100644--- a/hermes_cli/update_handoff.py+++ b/hermes_cli/update_handoff.py@@ -23,6 +23,7 @@ import loggingimport osimport subprocessimport sys+import timefrom pathlib import Pathfrom typing import Any@@ -32,6 +33,19 @@ logger = logging.getLogger("hermes_cli.update_cmd")# Set on the post-swap child: the receipt header says "continued", the lock is the parent's.POST_SWAP_ENV = "HERMES_UPDATE_POST_SWAP"+# Set on a child spawned DETACHED off the Windows console shim: the pid of the interpreter+# that still holds ``hermes.exe`` open. The child waits for it before it touches the venv —+# the shim quarantine is a single rename with sub-second retries, and the reporter's runs+# (#101600) reached it while the parent was still alive (relaunching gateways, or just+# tearing down), so the rename failed and the whole install was deferred.+SHIM_PARENT_PID_ENV = "HERMES_UPDATE_SHIM_PARENT_PID"+# Legacy re-exec (``_reexec_dependency_sync_off_windows_shim``, no hand-off file): the Windows+# pause token travels here so the child resumes exactly the fleet the parent stopped instead+# of re-running pause discovery — which found the parent's freshly relaunched gateway before+# its pid file existed and force-killed it as "unmapped" (#101600).+GATEWAY_RESUME_ENV = "HERMES_UPDATE_GATEWAY_RESUME"++SHIM_PARENT_EXIT_TIMEOUT_SECONDS = 30.0def _json_default(value: Any):@@ -103,6 +117,61 @@ def post_swap_child_env() -> dict[str, str]:return env+def detached_shim_child_env(env: dict[str, str], gateway_resume: dict | None = None) -> dict[str, str]:+ """Env for a child that outlives this shim-run process: names us as the shim holder and, for+ the legacy re-exec (no hand-off file), carries the Windows pause token."""+ env = {**env, SHIM_PARENT_PID_ENV: str(os.getpid())}+ if gateway_resume is not None:+ env[GATEWAY_RESUME_ENV] = json.dumps(gateway_resume, default=_json_default)+ return env+++def adopt_handed_off_gateway_resume() -> dict | None:+ """The pause token a shim-run parent handed to this legacy re-exec child, or ``None``.+ Consumed on read so nothing this run spawns (relaunched gateways) inherits it."""+ raw = os.environ.pop(GATEWAY_RESUME_ENV, None)+ if not raw:+ return None+ try:+ token = json.loads(raw)+ except ValueError:+ logger.warning("Ignoring malformed %s from the update hand-off", GATEWAY_RESUME_ENV)+ return None+ return token if isinstance(token, dict) else None+++def wait_for_shim_parent_exit(timeout: float = SHIM_PARENT_EXIT_TIMEOUT_SECONDS) -> bool:+ """Block until the shim-run parent named in :data:`SHIM_PARENT_PID_ENV` has exited.++ Returns True when it is gone (or none was named), False when it outlived ``timeout``; the+ caller proceeds either way — the strict shim quarantine refuses if it still holds the exe.+ A pid younger than this process is a recycled pid, never our parent. Consumed on read.+ """+ raw = os.environ.pop(SHIM_PARENT_PID_ENV, "")+ try:+ pid = int(raw.strip())+ except ValueError:+ return True+ if pid <= 0 or pid == os.getpid():+ return True+ import psutil++ try:+ parent = psutil.Process(pid) # pins (pid, create_time): a recycled pid reads as gone+ if parent.create_time() > psutil.Process().create_time():+ return True+ deadline = time.monotonic() + timeout+ while parent.is_running() and parent.status() != psutil.STATUS_ZOMBIE:+ if time.monotonic() >= deadline:+ print(f" ⚠ The hermes.exe process that started this update (PID {pid}) is still "+ f"running after {int(timeout)}s; continuing.")+ return False+ time.sleep(0.2)+ except psutil.Error:+ pass+ return True++def _print_manual_continuation(cmd: list[str], exc: OSError) -> None:logger.warning("Post-swap hand-off could not start: %s", exc)print(f" ⚠ Could not start the post-update interpreter: {exc}")@@ -134,7 +203,7 @@ def continue_update_in_fresh_interpreter(payload: dict[str, Any], *, argv_tail:if _running_from_windows_shim():try:- subprocess.Popen(cmd, env=env, stdin=subprocess.DEVNULL)+ subprocess.Popen(cmd, env=detached_shim_child_env(env), stdin=subprocess.DEVNULL)except OSError as exc:_print_manual_continuation(cmd, exc)return Nonediff --git a/tests/hermes_cli/test_update_shim_parent_wait.py b/tests/hermes_cli/test_update_shim_parent_wait.pynew file mode 100644index 00000000000..a5b76f54f5e--- /dev/null+++ b/tests/hermes_cli/test_update_shim_parent_wait.py@@ -0,0 +1,72 @@+"""A child spawned off the Windows ``hermes.exe`` shim waits for its parent before touching the venv.++Regression for #101600: the post-swap / re-exec child reached the shim quarantine while the+shim-run parent was still alive (relaunching gateways, or merely tearing down), the single+``os.rename`` failed with a PermissionError and the whole dependency install was deferred. The+wait is host-independent (env pid + psutil), so it is exercised with real processes here.+"""++from __future__ import annotations++import os+import subprocess+import sys+import time+from pathlib import Path++import psutil++from hermes_cli import update_handoff+++def _sleeper(seconds: float) -> subprocess.Popen:+ return subprocess.Popen(+ [sys.executable, "-c", f"import time; time.sleep({seconds})"],+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+++def test_child_waits_until_the_named_shim_parent_has_exited():+ """Real topology: the shim-run parent is OLDER than the child it spawns, so the child is a+ fresh interpreter started after the sleeper and told to wait for it."""+ parent = _sleeper(1.5)+ started = time.monotonic()+ try:+ child = subprocess.run(+ [sys.executable, "-c",+ "import os, sys; from hermes_cli import update_handoff\n"+ "ok = update_handoff.wait_for_shim_parent_exit(timeout=20)\n"+ "sys.exit(0 if ok and update_handoff.SHIM_PARENT_PID_ENV not in os.environ else 3)"],+ cwd=str(Path(__file__).resolve().parents[2]),+ env={**os.environ, update_handoff.SHIM_PARENT_PID_ENV: str(parent.pid)},+ stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=60)+ assert child.returncode == 0, child.stderr+ assert parent.poll() is not None, "the child returned while the parent was still running"+ assert time.monotonic() - started >= 1.0+ finally:+ parent.kill()+ parent.wait()+++def test_wait_is_bounded_and_skips_absent_garbage_and_recycled_pids(monkeypatch):+ # No shim parent named (every non-shim run, incl. Linux): no wait at all.+ monkeypatch.delenv(update_handoff.SHIM_PARENT_PID_ENV, raising=False)+ assert update_handoff.wait_for_shim_parent_exit(timeout=5) is True+ monkeypatch.setenv(update_handoff.SHIM_PARENT_PID_ENV, "not-a-pid")+ assert update_handoff.wait_for_shim_parent_exit(timeout=5) is True++ # A live process YOUNGER than us cannot be our parent: a recycled pid is never waited on.+ younger = _sleeper(30)+ try:+ assert psutil.Process(younger.pid).create_time() >= psutil.Process().create_time()+ monkeypatch.setenv(update_handoff.SHIM_PARENT_PID_ENV, str(younger.pid))+ started = time.monotonic()+ assert update_handoff.wait_for_shim_parent_exit(timeout=5) is True+ assert time.monotonic() - started < 2.0 and younger.poll() is None+ finally:+ younger.kill()+ younger.wait()++ # A parent that never exits only delays the child by the bound; the strict shim quarantine+ # downstream stays the fail-closed guard. Our own parent is older than us and outlives us.+ monkeypatch.setenv(update_handoff.SHIM_PARENT_PID_ENV, str(os.getppid()))+ assert update_handoff.wait_for_shim_parent_exit(timeout=0.5) is Falsediff --git a/tests/hermes_cli/test_update_shim_self_lock.py b/tests/hermes_cli/test_update_shim_self_lock.pyindex bd47d4a2a42..c6a87e509fc 100644--- a/tests/hermes_cli/test_update_shim_self_lock.py+++ b/tests/hermes_cli/test_update_shim_self_lock.py@@ -16,6 +16,7 @@ off at all.from __future__ import annotations+import osimport sysimport typesfrom pathlib import Path@@ -138,14 +139,24 @@ def test_no_shim_without_a_venv(venv, monkeypatch):def test_reexec_runs_same_args_under_venv_python(venv, monkeypatch, capsys):monkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe"), "update", "--yes"])calls = _capture_popen(monkeypatch)+ token = {"resume_needed": True, "profiles": {"default": 4}, "unmapped": []}- assert cli_main._reexec_dependency_sync_off_windows_shim() is True+ assert cli_main._reexec_dependency_sync_off_windows_shim(token) is Truecmd, env, kwargs = calls[0]assert cmd == [str(venv / "python.exe"), "-m", "hermes_cli.main", "update", "--yes",]assert env[cli_main._UPDATE_REEXEC_ENV] == "1"assert "under the venv Python" in capsys.readouterr().out+ # #101600: the child waits for THIS pid and resumes exactly the paused fleet; the parent's+ # copy is disarmed so it exits instead of relaunching gateways while it still holds the shim.+ from hermes_cli import update_handoff+ assert env[update_handoff.SHIM_PARENT_PID_ENV] == str(os.getpid())+ assert token["resume_needed"] is False+ monkeypatch.setenv(update_handoff.GATEWAY_RESUME_ENV, env[update_handoff.GATEWAY_RESUME_ENV])+ assert update_handoff.adopt_handed_off_gateway_resume() == {+ "resume_needed": True, "profiles": {"default": 4}, "unmapped": []}+ assert update_handoff.GATEWAY_RESUME_ENV not in os.environdef test_reexec_child_runs_unattended(venv, monkeypatch):@@ -213,18 +224,22 @@ def test_up_to_date_run_never_hands_off(venv, monkeypatch, capsys):def test_sync_guard_hands_off_when_only_the_shim_is_held(venv, monkeypatch):- """No native module mapped, but we ARE the shim: hand off and exit 0."""+ """No native module mapped, but we ARE the shim: hand off and exit 0 WITHOUT resuming the+ paused fleet here — the child owns the token (#101600)."""from hermes_cli import update_cmdmonkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe"), "update"])monkeypatch.setattr(cli_main, "_detect_self_loaded_native_modules", lambda: [])+ resumed = []+ monkeypatch.setattr(cli_main, "_resume_windows_gateways_after_update", resumed.append)calls = _capture_popen(monkeypatch)with pytest.raises(SystemExit) as excinfo:- update_cmd._abort_dependency_sync_if_self_locked()+ update_cmd._abort_dependency_sync_if_self_locked({"resume_needed": True, "profiles": {}})assert excinfo.value.code == 0assert calls, "expected the dependency sync to be handed to the venv python"+ assert resumed == [], "the shim parent must exit at once, not relaunch gateways"def test_sync_guard_defers_native_lock_before_considering_the_shim(venv, monkeypatch):diff --git a/website/docs/getting-started/updating.md b/website/docs/getting-started/updating.mdindex 9173aabb348..e6fb80376cb 100644--- a/website/docs/getting-started/updating.md+++ b/website/docs/getting-started/updating.md@@ -210,6 +210,10 @@ A second, separate guard refuses to touch the venv while any process is runningBoth guards, the Desktop update preflight, and the dependency repair steps look for the environment at `venv` first and then at the uv-default `.venv`, so a source checkout set up with `uv venv` / `uv sync` updates the same way an installer-created `venv` does. When both directories exist, `venv` is the one that gets updated.+#### Windows: the update finishes under the venv Python++`hermes.exe` itself cannot be replaced while it runs, so an update started from it stops after the code swap and prints `→ Windows: hermes.exe cannot replace itself while it runs; the update continues under the venv Python`. Your shell returns right away; a child interpreter finishes the dependency install and prints its own result. The child first waits (up to 30 s) for the `hermes.exe` process that started the update to exit, and it alone restarts the gateways the update paused — the process that launched it never resumes them while it still holds the shim. If the launcher is still alive after that wait, the child says so and continues; a shim that is still locked at install time is reported as before and the install is deferred to the next `hermes` run.+#### Windows venv recreation is transactionalWhen the Windows installer must recreate an existing `venv`, it first moves the old directory to a unique `venv.stale.*` name, then creates and verifies the replacement. The old tree is deleted only after the dependency install completes and the baseline imports pass in the new tree — until then it is the rollback source (recorded in `venv.pending-backup`).