Skip to content

The agent that grows with you

fix(update): shim hand-off child outwaits the launcher pid before the update lock and pins the wiring

teknium16f0dae8b6fae
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index 581491f0ed9..07e7456315d 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -2375,6 +2375,15 @@ def cmd_update(args):
describe_holder,
)
+ # 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.
+ # Waiting BEFORE the lock matters: the parent's exit releases ITS marker, so a child that
+ # merely ran under the parent's claim would finish the install with no lock at all
+ # (#101600); once the parent is gone the child claims a marker of its own.
+ from hermes_cli.update_handoff import wait_for_shim_parent_exit
+
+ wait_for_shim_parent_exit()
+
_update_lock = UpdateLock()
if not _update_lock.acquire():
print(describe_holder(_update_lock.holder))
diff --git a/hermes_cli/main_install_repair.py b/hermes_cli/main_install_repair.py
index 2e3508bced9..6e1fd553530 100644
--- a/hermes_cli/main_install_repair.py
+++ b/hermes_cli/main_install_repair.py
@@ -310,6 +310,26 @@ def _windows_shim_in_process_chain() -> Path | None:
See #88838, #89599.
"""
+ _match = _venv_shim_matcher()
+ if _match is None:
+ return None
+
+ main_mod = sys.modules.get("__main__")
+ candidates = [*sys.argv[:1], *filter(None, (
+ getattr(main_mod, "__file__", None),
+ getattr(getattr(main_mod, "__spec__", None), "origin", None)))]
+ for candidate in candidates:
+ matched = _match(candidate)
+ if matched is not None:
+ return matched
+
+ ancestor = _windows_shim_ancestor(_match)
+ return None if ancestor is None else ancestor[0]
+
+
+def _venv_shim_matcher():
+ """``candidate -> shim | None`` against the project venv's own console shims, or ``None`` when
+ there is nothing to match (not Windows, no venv, no shims)."""
if not _is_windows():
return None
scripts_dir = _venv_scripts_dir()
@@ -325,15 +345,11 @@ def _windows_shim_in_process_chain() -> Path | None:
path = path.parent
return shims.get(_norm_exe_path(path))
- main_mod = sys.modules.get("__main__")
- candidates = [*sys.argv[:1], *filter(None, (
- getattr(main_mod, "__file__", None),
- getattr(getattr(main_mod, "__spec__", None), "origin", None)))]
- for candidate in candidates:
- matched = _match(candidate)
- if matched is not None:
- return matched
+ return _match
+
+def _windows_shim_ancestor(_match) -> tuple[Path, int] | None:
+ """``(shim, pid)`` of the nearest process in our chain (self first) whose executable IS a shim."""
with contextlib.suppress(Exception):
import psutil
me = psutil.Process()
@@ -343,10 +359,19 @@ def _windows_shim_in_process_chain() -> Path | None:
except Exception:
continue
if matched is not None:
- return matched
+ return matched, proc.pid
return None
+def _windows_shim_holder_pid() -> int:
+ """Pid a detached child must outwait before touching the venv: the ``hermes.exe`` launcher
+ ancestor that holds the shim image open (it spawns this interpreter and exits only after
+ reaping it), else this process — argv names the shim but it is the launcher that locks it."""
+ _match = _venv_shim_matcher()
+ ancestor = _windows_shim_ancestor(_match) if _match is not None else None
+ return os.getpid() if ancestor is None else ancestor[1]
+
+
def _windows_running_hermes_launcher_locked() -> bool:
"""True when a venv ``hermes*.exe`` shim is this process or an ancestor (best-effort)."""
return _windows_shim_in_process_chain() is not None
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index 8cfe6fad18d..60264fb7a5b 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -1534,10 +1534,9 @@ 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()
+ # A child spawned off hermes.exe already outwaited its parent in ``cmd_update`` (before the
+ # update lock, so the lock it now holds is its own — the parent's marker left with it).
+ from hermes_cli.update_handoff import adopt_handed_off_gateway_resume
if getattr(args, "post_swap", None):
# Second half of a run whose pre-pull interpreter stopped at the code swap.
diff --git a/hermes_cli/update_handoff.py b/hermes_cli/update_handoff.py
index 84be98683d2..6d1b5980432 100644
--- a/hermes_cli/update_handoff.py
+++ b/hermes_cli/update_handoff.py
@@ -33,8 +33,9 @@ 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 —
+# Set on a child spawned DETACHED off the Windows console shim: the pid of the process that
+# still holds ``hermes.exe`` open (the launcher, or the interpreter it ran). 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.
@@ -118,9 +119,12 @@ def post_swap_child_env() -> dict[str, str]:
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())}
+ """Env for a child that outlives this shim-run process: names the process holding the shim
+ open (the ``hermes.exe`` launcher above us when psutil sees it, else this interpreter) and,
+ for the legacy re-exec (no hand-off file), carries the Windows pause token."""
+ from hermes_cli.main_install_repair import _windows_shim_holder_pid
+
+ env = {**env, SHIM_PARENT_PID_ENV: str(_windows_shim_holder_pid())}
if gateway_resume is not None:
env[GATEWAY_RESUME_ENV] = json.dumps(gateway_resume, default=_json_default)
return env
diff --git a/tests/hermes_cli/test_update_shim_parent_wait.py b/tests/hermes_cli/test_update_shim_parent_wait.py
index a5b76f54f5e..8d6ef337174 100644
--- a/tests/hermes_cli/test_update_shim_parent_wait.py
+++ b/tests/hermes_cli/test_update_shim_parent_wait.py
@@ -3,11 +3,13 @@
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.
+wait is host-independent (env pid + psutil), so it is exercised with real processes here,
+through the production entry point (``cmd_update``) rather than the helpers alone.
"""
from __future__ import annotations
+import json
import os
import subprocess
import sys
@@ -16,38 +18,127 @@ from pathlib import Path
import psutil
-from hermes_cli import update_handoff
+from hermes_cli import main_install_repair, update_handoff, update_lock
+REPO_ROOT = Path(__file__).resolve().parents[2]
-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)
+# Runs ``cmd_update`` as the detached child would, with every phase past the hand-off boundary
+# stubbed; the first thing after the Windows pause step (``_desktop_app_present``) reports what
+# the child saw and stops the run.
+_CHILD = r"""
+import atexit, json, os, sys
+from pathlib import Path
+from types import SimpleNamespace
+import psutil
+from hermes_cli import main as cli_main, update_cmd, update_handoff, update_lock
+
+seen = {"paused": 0, "registered": None}
+parent_pid = int(os.environ[update_handoff.SHIM_PARENT_PID_ENV])
+cli_main._update_preflight_handled = lambda args: False
+cli_main._install_hangup_protection = lambda **kw: None
+cli_main._finalize_update_output = lambda state: None
+cli_main._finalize_update_receipt = lambda *a, **kw: None
+cli_main._run_pre_update_backup = lambda args: None
+update_cmd._resolve_update_options = lambda args, gateway_mode: SimpleNamespace(gw_input_fn=None, assume_yes=True)
+update_cmd._begin_update_receipt_and_plan = lambda args: None
+update_cmd._record_pre_update_backup_outcome = lambda args, snapshot_id: None
+
+def _pause():
+ seen["paused"] += 1
+ return {"resume_needed": True, "profiles": {"rediscovered": 1}}
+
+cli_main._pause_windows_gateways_for_update = _pause
+_register = atexit.register
+def _capture(fn, *a, **kw):
+ if a and isinstance(a[0], dict):
+ seen["registered"] = a[0]
+ else:
+ _register(fn, *a, **kw)
+atexit.register = _capture
+class Stop(Exception):
+ pass
-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()
+def _phase(desktop_dir):
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
+ seen["parent_status"] = psutil.Process(parent_pid).status()
+ except psutil.NoSuchProcess:
+ seen["parent_status"] = "gone"
+ try:
+ seen["lock_owner"] = int(update_lock.update_marker_path().read_text().split()[0])
+ except OSError:
+ seen["lock_owner"] = None
+ seen["env_left"] = [k for k in (update_handoff.SHIM_PARENT_PID_ENV, update_handoff.GATEWAY_RESUME_ENV) if k in os.environ]
+ raise Stop
+
+update_cmd._desktop_app_present = _phase
+
+Path(os.environ["HERMES_TEST_READY"]).touch()
+try:
+ cli_main.cmd_update(SimpleNamespace(post_swap=None, yes=True, gateway=False))
+except Stop:
+ pass
+seen["marker_after"] = update_lock.update_marker_path().exists()
+print(json.dumps(seen))
+"""
+
+
+def test_update_child_outwaits_shim_parent_then_owns_the_lock_and_the_resume_token(tmp_path):
+ """Real topology: the shim-run parent is OLDER than the child and holds the update marker;
+ the child (a fresh ``hermes update``) must not pause gateways, scan holders or claim the
+ lock until the parent is gone — then it runs under its OWN marker, with the parent's pause
+ token instead of a fresh discovery (#101600)."""
+ hermes_home = tmp_path / "home"
+ hermes_home.mkdir()
+ ready = tmp_path / "ready"
+ token = {"resume_needed": True, "profiles": {"default": 4}, "unmapped": []}
+ # The parent lives until we close its stdin — the marker is its claim, as in a real run.
+ parent = subprocess.Popen(
+ [sys.executable, "-c", "import sys; sys.stdin.read()"],
+ stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ marker = hermes_home / update_lock.MARKER_NAME
+ marker.write_text(f"{parent.pid}\n{int(time.time())}\n", encoding="utf-8")
+ env = {
+ **os.environ, "HERMES_HOME": str(hermes_home), "HERMES_TEST_READY": str(ready),
+ update_lock.HANDOFF_PID_ENV: str(parent.pid),
+ update_handoff.SHIM_PARENT_PID_ENV: str(parent.pid),
+ update_handoff.GATEWAY_RESUME_ENV: json.dumps(token),
+ }
+ child = subprocess.Popen(
+ [sys.executable, "-c", _CHILD], cwd=str(REPO_ROOT), env=env,
+ stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ try:
+ deadline = time.monotonic() + 60
+ while not ready.exists():
+ assert child.poll() is None, child.communicate()[1]
+ assert time.monotonic() < deadline, "child never reached cmd_update"
+ time.sleep(0.05)
+ # The child is inside cmd_update now; give a child that does NOT wait ample time to
+ # reach the phase while the parent is still alive.
+ time.sleep(1.0)
+ assert child.poll() is None, child.communicate()[1]
+ # Parent exits: its lock release removes the marker, exactly as cmd_update's finally does.
+ parent.stdin.close()
+ parent.wait(timeout=30)
+ marker.unlink(missing_ok=True)
+ out, err = child.communicate(timeout=60)
finally:
parent.kill()
parent.wait()
+ assert child.returncode == 0, err
+ seen = json.loads(out.strip().splitlines()[-1])
+ assert seen["parent_status"] in ("gone", psutil.STATUS_ZOMBIE), seen
+ assert seen["lock_owner"] == child.pid, seen # its own claim, not the departed parent's
+ assert seen["paused"] == 0 and seen["registered"] == token, seen
+ assert seen["env_left"] == [] and seen["marker_after"] is False, seen
def test_wait_is_bounded_and_skips_absent_garbage_and_recycled_pids(monkeypatch):
+ 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)
+
# 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
@@ -70,3 +161,17 @@ def test_wait_is_bounded_and_skips_absent_garbage_and_recycled_pids(monkeypatch)
# 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 False
+
+
+def test_shim_holder_is_the_launcher_ancestor_not_the_interpreter_it_ran():
+ """``hermes.exe`` spawns python.exe with the shim as argv[0] and exits only after reaping it,
+ so the pid the child outwaits must be the ancestor whose EXECUTABLE is the shim."""
+ me = psutil.Process()
+ launcher = next((p for p in me.parents() if p.exe() != me.exe()), None)
+ assert launcher is not None, "test runner has no ancestor with a different executable"
+
+ def match(candidate):
+ return Path(candidate) if str(candidate) == launcher.exe() else None
+
+ assert main_install_repair._windows_shim_ancestor(match) == (Path(launcher.exe()), launcher.pid)
+ assert main_install_repair._windows_shim_ancestor(lambda candidate: None) is None
diff --git a/tests/hermes_cli/test_update_shim_self_lock.py b/tests/hermes_cli/test_update_shim_self_lock.py
index c6a87e509fc..19ed523f911 100644
--- a/tests/hermes_cli/test_update_shim_self_lock.py
+++ b/tests/hermes_cli/test_update_shim_self_lock.py
@@ -51,8 +51,8 @@ def _fake_psutil(monkeypatch, ancestor_exes: list[str]):
"""Stand in for psutil with a fixed self+ancestor executable chain."""
class _Proc:
- def __init__(self, exe=None):
- self._exe = exe
+ def __init__(self, exe=None, pid=os.getpid()):
+ self._exe, self.pid = exe, pid
def exe(self):
if self._exe is None:
@@ -60,7 +60,7 @@ def _fake_psutil(monkeypatch, ancestor_exes: list[str]):
return self._exe
def parents(self):
- return [_Proc(exe) for exe in ancestor_exes]
+ return [_Proc(exe, 1000 + i) for i, exe in enumerate(ancestor_exes)]
monkeypatch.setitem(sys.modules, "psutil", types.SimpleNamespace(Process=_Proc))
@@ -108,6 +108,8 @@ def test_detects_shim_in_ancestor_chain(venv, monkeypatch):
"""The launcher is usually a separate parent process, not argv[0]."""
_fake_psutil(monkeypatch, [str(venv / "hermes.exe")])
assert main_install_repair._windows_shim_in_process_chain() == venv / "hermes.exe"
+ # ...and it is that launcher's pid, not ours, a detached child must outwait (#101600).
+ assert main_install_repair._windows_shim_holder_pid() == 1000
def test_ignores_hermes_exe_outside_the_project_venv(venv, monkeypatch, tmp_path):
diff --git a/website/docs/getting-started/updating.md b/website/docs/getting-started/updating.md
index e6fb80376cb..cf310ee4efd 100644
--- a/website/docs/getting-started/updating.md
+++ b/website/docs/getting-started/updating.md
@@ -212,7 +212,7 @@ Both guards, the Desktop update preflight, and the dependency repair steps look
#### 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.
+`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 process that started the update — the `hermes.exe` launcher when it can be identified, otherwise the interpreter it ran — to exit, then takes over the update lock; 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 transactional