The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): a contended venv is never mutated — failed shim quarantine now refuses instead of warning (#87331)
Teknium83864c0b5d84
diff --git a/hermes_cli/_install_repair.py b/hermes_cli/_install_repair.pyindex 848d400b0bc..39e5e296846 100644--- a/hermes_cli/_install_repair.py+++ b/hermes_cli/_install_repair.py@@ -185,13 +185,35 @@ def _load_console_script_names(root: Path) -> list[str]:return []-def _quarantine_running_hermes_exe(scripts_dir: Path) -> list[tuple[Path, Path]]:+class ShimQuarantineError(RuntimeError):+ """A live shim could not be renamed aside — the venv is contended (#87331).++ Raised BEFORE the install command runs. Callers (early-pass recovery,+ core-marker recovery) catch it like any install failure: the+ update-incomplete marker survives and a later launch retries once the+ holder exits — the contended venv is never mutated.+ """++ def __init__(self, failed_shims: list[str]):+ self.failed_shims = list(failed_shims)+ super().__init__(+ "could not quarantine live shim(s): " + ", ".join(self.failed_shims)+ )+++def _quarantine_running_hermes_exe(+ scripts_dir: Path, *, failed_out: list[str] | None = None+) -> list[tuple[Path, Path]]:"""Rename live hermes*.exe shims aside so the installer can rewrite them.Windows blocks REPLACE on a running .exe but allows RENAME. Best-effort:silently skips anything that cannot be renamed. Returns (original,quarantined) pairs. stdlib-only — the console-script set comes frompyproject ``[project.scripts]`` (fallback: the well-known trio).++ ``failed_out``: when provided, names of shims that could not be renamed+ are appended so the caller can refuse instead of mutating a contended+ venv (#87331 fail-closed)."""if not _is_windows():return []@@ -211,7 +233,8 @@ def _quarantine_running_hermes_exe(scripts_dir: Path) -> list[tuple[Path, Path]]os.rename(shim, quarantined)moved.append((shim, quarantined))except OSError:- pass+ if failed_out is not None:+ failed_out.append(shim.name)return moved@@ -229,11 +252,24 @@ def _restore_quarantined_exes(moved: list[tuple[Path, Path]]) -> None:def _run_install_cmd(cmd: list[str], *, env: dict | None, root: Path) -> None:"""Run an install command with quarantine protection for venv shims.+ Fail-closed (#87331): when any live shim cannot be renamed aside, the+ venv is contended and the installer would die partway on the same locks+ — raise :class:`ShimQuarantineError` WITHOUT running it. The caller's+ marker-keeping failure handling turns that into "retry next launch".+Raises CalledProcessError on install failure (callers implement theper-extra fallback ladder)."""scripts_dir = _venv_scripts_dir(root) if _is_windows() else None- moved = _quarantine_running_hermes_exe(scripts_dir) if scripts_dir else []+ failed: list[str] = []+ moved = (+ _quarantine_running_hermes_exe(scripts_dir, failed_out=failed)+ if scripts_dir+ else []+ )+ if failed:+ _restore_quarantined_exes(moved)+ raise ShimQuarantineError(failed)try:subprocess.run(cmd, cwd=root, check=True, env=env)finally:diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 448261c6c20..f188279d28e 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -8984,7 +8984,8 @@ def _hermes_exe_shims(scripts_dir: Path) -> list[Path]:def _quarantine_running_hermes_exe(- scripts_dir: Path, *, max_attempts: int = 4+ scripts_dir: Path, *, max_attempts: int = 4,+ failed_out: list[str] | None = None,) -> list[tuple[Path, Path]]:"""Pre-empt Windows file lock on the running ``hermes.exe``.@@ -9014,6 +9015,11 @@ def _quarantine_running_hermes_exe(Returns the list of (original, quarantined) pairs so the caller can rollback if the install itself fails before uv writes a replacement.++ ``failed_out``: when provided, the names of shims whose rename failed on+ every attempt are appended — callers that must not mutate a contended+ venv (the update dependency sync, #87331) check it and refuse instead of+ letting the install run into a half-broken state."""moved: list[tuple[Path, Path]] = []if not _is_windows():@@ -9064,6 +9070,8 @@ def _quarantine_running_hermes_exe(" Close Hermes Desktop, exit other `hermes` REPLs, stop the ""gateway, or pause AV scanning, then re-run `hermes update`.")+ if failed_out is not None:+ failed_out.append(shim.name)return moved@@ -9152,11 +9160,29 @@ def _restore_quarantined_exes(moved: list[tuple[Path, Path]]) -> None:pass+class ShimQuarantineError(RuntimeError):+ """A live ``hermes*.exe`` shim could not be renamed aside (#87331).++ Raised by :func:`_run_quarantined_install` in ``strict_quarantine`` mode+ BEFORE the install command runs. A shim that cannot even be renamed means+ another process holds the venv hard enough that the dependency sync would+ die partway and strand the install half-updated — the update must refuse,+ not warn-and-continue.+ """++ def __init__(self, failed_shims: list[str]):+ self.failed_shims = list(failed_shims)+ super().__init__(+ "could not quarantine live shim(s): " + ", ".join(self.failed_shims)+ )++def _run_quarantined_install(cmd: list[str],*,env: dict[str, str] | None = None,scripts_dir: Path | None = None,+ strict_quarantine: bool = False,) -> None:"""Run an editable install, quarantining the running ``hermes.exe`` first.@@ -9171,11 +9197,24 @@ def _run_quarantined_install(:func:`_verify_core_dependencies_installed`, which previously called``_run_install_with_heartbeat`` directly and bypassed quarantine.+ ``strict_quarantine=True`` (the update dependency sync, #87331): a shim+ whose rename failed every retry means a process is holding the venv+ without ``FILE_SHARE_DELETE`` — the install WILL hit the same lock on+ .pyd files and strand the venv between versions. Roll the successful+ renames back and raise :class:`ShimQuarantineError` WITHOUT running the+ install. Non-strict callers (post-sync entry-point repair) keep the old+ warn-and-try behavior: their venv is already mutated, so refusing buys+ nothing.+Off-Windows (``scripts_dir is None``) this is a thin pass-through."""moved: list[tuple[Path, Path]] = []+ failed: list[str] = []if scripts_dir is not None:- moved = _quarantine_running_hermes_exe(scripts_dir)+ moved = _quarantine_running_hermes_exe(scripts_dir, failed_out=failed)+ if strict_quarantine and failed:+ _restore_quarantined_exes(moved)+ raise ShimQuarantineError(failed)try:_run_install_with_heartbeat(cmd, env=env)finally:@@ -9450,8 +9489,14 @@ def _install_python_dependencies_with_optional_fallback(scripts_dir = _venv_scripts_dir() if _is_windows() else Nonedef _install(args: list[str]) -> None:+ # strict_quarantine: this is the UPDATE dependency sync. A shim that+ # cannot be renamed aside proves a hard venv hold; running uv anyway+ # is how installs strand half-updated (#87331). ShimQuarantineError+ # propagates to the update's sync boundary, which defers via the+ # update-incomplete marker instead of mutating a contended venv._run_quarantined_install(- install_cmd_prefix + args, env=env, scripts_dir=scripts_dir+ install_cmd_prefix + args, env=env, scripts_dir=scripts_dir,+ strict_quarantine=True,)try:diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex 8bdecc94469..2509e207eb0 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -1216,6 +1216,48 @@ def _format_update_failure_stage(exc: subprocess.CalledProcessError) -> str:return "Update step failed"+def _shim_quarantine_error_type() -> "type[BaseException]":+ """The strict-quarantine refusal type, resolved lazily through ``_m()``.++ Falls back to a never-raised private type when main.py lacks it (torn+ mid-update tree), so the ``except`` clause stays valid.+ """+ cls = getattr(_m(), "ShimQuarantineError", None)+ if isinstance(cls, type) and issubclass(cls, BaseException):+ return cls++ class _Never(Exception):+ pass++ return _Never+++def _refuse_update_for_contended_shims(exc: BaseException) -> None:+ """Refuse the dependency sync when live shims could not be quarantined.++ #87331 fail-closed half: a shim rename that failed every retry proves a+ process holds the venv without FILE_SHARE_DELETE — running the installer+ anyway is exactly how the venv ends up stranded between versions. The+ code swap (when one happened) is already committed; only the dependency+ install is deferred, via the update-incomplete marker, to the next fresh+ launch after the holder exits. Exits 2 (refused) so the command-boundary+ receipt net records it as a refusal, not a failure.+ """+ print("✗ Cannot continue the update: live Hermes launcher(s) could not be")+ print(" moved aside:")+ for name in getattr(exc, "failed_shims", []) or ["hermes.exe"]:+ print(f" {name}")+ print(" Another process is holding this install's venv open (Hermes")+ print(" Desktop, a gateway, or another hermes REPL) — mutating the venv")+ print(" now would strand it half-updated.")+ print(" The dependency install has been deferred: close the process(es)")+ print(" above, then run any `hermes` command to finish it automatically.")+ # Idempotent: the git path already dropped the marker before the sync;+ # this covers the ZIP/repair paths so the deferral is never silent.+ _write_update_incomplete_marker()+ sys.exit(2)++def _should_zip_fallback_on_update_error(exc: BaseException) -> bool:"""ZIP fallback is for Windows git file-I/O breakage, not later stages.@@ -1627,7 +1669,13 @@ def _update_via_zip(args, *, had_desktop_app_before_update: bool = False) -> booif _m()._is_termux_env(uv_env):uv_env.pop("PYTHONPATH", None)uv_env.pop("PYTHONHOME", None)- _m()._install_python_dependencies_with_optional_fallback([uv_bin, "pip"], env=uv_env)+ try:+ _m()._install_python_dependencies_with_optional_fallback([uv_bin, "pip"], env=uv_env)+ except _shim_quarantine_error_type() as _sqe:+ # #87331: this runs inside the ZIP-fallback error handler, so the+ # boundary except clause in cmd_update cannot catch it — refuse+ # here with the same defer-via-marker contract.+ _refuse_update_for_contended_shims(_sqe)else:# Use sys.executable to explicitly call the venv's pip module,# avoiding PEP 668 'externally-managed-environment' errors on Debian/Ubuntu.@@ -7990,6 +8038,10 @@ def _cmd_update_impl(args, gateway_mode: bool):# automation / operators do not treat the fleet as healthy.sys.exit(1)+ except _shim_quarantine_error_type() as e:+ # Fail-closed shim contention (#87331): strict quarantine refused+ # BEFORE any installer ran — defer via marker, exit 2, no ZIP.+ _refuse_update_for_contended_shims(e)except subprocess.CalledProcessError as e:stage = _format_update_failure_stage(e)if _should_zip_fallback_on_update_error(e):diff --git a/tests/hermes_cli/test_shim_fail_closed_windows_live.py b/tests/hermes_cli/test_shim_fail_closed_windows_live.pynew file mode 100644index 00000000000..a3474fc10ac--- /dev/null+++ b/tests/hermes_cli/test_shim_fail_closed_windows_live.py@@ -0,0 +1,140 @@+"""LIVE Windows E2E for the fail-closed shim quarantine (#87331).++Runs ONLY on a real Windows host (the on-demand ``windows-venv-e2e.yml``+lane). Reproduces the REAL lock shape from the field report: a process+holding ``hermes.exe`` open WITHOUT FILE_SHARE_DELETE, exactly like a+running launcher — then proves the strict quarantine refuses before any+installer runs, and that the non-contended path still installs.++No mocks: real files, a real child process holding a real Windows handle,+the real rename attempt hitting the real sharing violation.+"""++from __future__ import annotations++import os+import subprocess+import sys+import time+from pathlib import Path++import pytest++pytestmark = pytest.mark.skipif(+ sys.platform != "win32", reason="live Windows shim-lock E2E"+)++PROJECT_ROOT = Path(__file__).resolve().parents[2]++# Child that opens a file with GENERIC_READ and NO FILE_SHARE_DELETE —+# the exact sharing mode a running .exe image / desktop backend exhibits.+_HOLDER_CODE = r"""+import ctypes, sys, time+GENERIC_READ = 0x80000000+FILE_SHARE_READ = 0x1 # note: NO FILE_SHARE_DELETE+OPEN_EXISTING = 3+h = ctypes.windll.kernel32.CreateFileW(+ sys.argv[1], GENERIC_READ, FILE_SHARE_READ, None, OPEN_EXISTING, 0, None+)+if h == -1 or h == 0xFFFFFFFF:+ print("OPEN_FAILED", flush=True)+ sys.exit(1)+print("HOLDING", flush=True)+time.sleep(120)+"""+++def held_shim(tmp_path: Path):+ scripts = tmp_path / "venv" / "Scripts"+ scripts.mkdir(parents=True)+ shim = scripts / "hermes.exe"+ shim.write_bytes(b"MZ fake shim")+ (scripts / "hermes-gateway.exe").write_bytes(b"MZ fake shim")+ holder = subprocess.Popen(+ [sys.executable, "-c", _HOLDER_CODE, str(shim)],+ stdout=subprocess.PIPE,+ text=True,+ )+ line = holder.stdout.readline().strip()+ if line != "HOLDING":+ holder.kill()+ pytest.fail(f"lock-holder child failed: {line!r}")+ yield scripts, shim+ holder.kill()+ holder.wait()+++def test_locked_shim_really_cannot_be_renamed(held_shim):+ """Premise check: the no-FILE_SHARE_DELETE handle blocks rename."""+ _scripts, shim = held_shim+ with pytest.raises(OSError):+ os.rename(shim, shim.with_name("hermes.exe.old.premise"))+++def test_strict_quarantine_refuses_against_real_lock(held_shim, monkeypatch):+ import hermes_cli.main as cli_main++ scripts, _shim = held_shim+ install_ran: list = []+ monkeypatch.setattr(+ cli_main,+ "_run_install_with_heartbeat",+ lambda cmd, env=None: install_ran.append(cmd),+ )++ with pytest.raises(cli_main.ShimQuarantineError) as exc_info:+ cli_main._run_quarantined_install(+ ["would-be", "uv", "pip", "install"],+ scripts_dir=scripts,+ strict_quarantine=True,+ )++ assert install_ran == [], "installer ran against a contended venv"+ assert "hermes.exe" in exc_info.value.failed_shims+ # The unlocked sibling's rename was rolled back — venv untouched.+ assert (scripts / "hermes-gateway.exe").exists()+ assert not list(scripts.glob("*.old.*"))+++def test_recovery_installer_refuses_against_real_lock(held_shim, monkeypatch):+ import hermes_cli._install_repair as ir++ scripts, _shim = held_shim+ monkeypatch.setattr(ir, "_venv_scripts_dir", lambda root: scripts)+ run_calls: list = []+ monkeypatch.setattr(ir.subprocess, "run", lambda *a, **k: run_calls.append(a))++ with pytest.raises(ir.ShimQuarantineError):+ ir._run_install_cmd(["fake"], env=None, root=scripts.parent.parent)+ assert run_calls == []+++def test_release_then_strict_quarantine_succeeds(tmp_path, monkeypatch):+ """After the holder exits, the same strict path proceeds normally."""+ import hermes_cli.main as cli_main++ scripts = tmp_path / "venv" / "Scripts"+ scripts.mkdir(parents=True)+ (scripts / "hermes.exe").write_bytes(b"MZ fake shim")++ holder = subprocess.Popen(+ [sys.executable, "-c", _HOLDER_CODE, str(scripts / "hermes.exe")],+ stdout=subprocess.PIPE,+ text=True,+ )+ assert holder.stdout.readline().strip() == "HOLDING"+ holder.kill()+ holder.wait()+ time.sleep(0.3) # handle teardown++ install_ran: list = []+ monkeypatch.setattr(+ cli_main,+ "_run_install_with_heartbeat",+ lambda cmd, env=None: install_ran.append(cmd),+ )+ cli_main._run_quarantined_install(+ ["fake"], scripts_dir=scripts, strict_quarantine=True+ )+ assert install_ran == [["fake"]]diff --git a/tests/hermes_cli/test_update_shim_fail_closed.py b/tests/hermes_cli/test_update_shim_fail_closed.pynew file mode 100644index 00000000000..7b04dbe189f--- /dev/null+++ b/tests/hermes_cli/test_update_shim_fail_closed.py@@ -0,0 +1,210 @@+"""Fail-closed shim quarantine (#87331): a contended venv is never mutated.++The bug class: on Windows, when `hermes.exe`/sibling shims could not be+renamed aside (another process holds them without FILE_SHARE_DELETE), the+updater printed a warning and ran the installer anyway — which then died+partway on the same locks and stranded the venv between versions (3x field+reports on one machine, #87331).++Contract pinned here:+- `_run_quarantined_install(strict_quarantine=True)` raises+ ShimQuarantineError BEFORE running any install command, and rolls back the+ renames that did succeed.+- Non-strict callers keep the old warn-and-try behavior.+- The recovery installer's `_run_install_cmd` is strict unconditionally.+- The update boundary turns the error into a refusal (exit 2) + marker,+ never a ZIP fallback.+"""++import os+import sys+from pathlib import Path+from unittest import mock++import pytest++import hermes_cli.main as cli_main+import hermes_cli._install_repair as ir+import hermes_cli.update_cmd as update_cmd+++def _make_shims(scripts_dir: Path, names=("hermes", "hermes-gateway")) -> list[Path]:+ scripts_dir.mkdir(parents=True, exist_ok=True)+ shims = []+ for name in names:+ p = scripts_dir / f"{name}.exe"+ p.write_bytes(b"MZ fake")+ shims.append(p)+ return shims+++def windows(monkeypatch):+ monkeypatch.setattr(cli_main, "_is_windows", lambda: True)+ monkeypatch.setattr(ir, "_is_windows", lambda: True)+++# ---------------------------------------------------------------------------+# main.py: _run_quarantined_install strict mode+# ---------------------------------------------------------------------------++def test_strict_quarantine_refuses_before_install(windows, tmp_path, monkeypatch):+ scripts = tmp_path / "venv" / "Scripts"+ shims = _make_shims(scripts)+ # hermes.exe cannot be renamed; hermes-gateway.exe can+ real_rename = Path.rename++ def deny_hermes(self, target):+ if self.name == "hermes.exe":+ raise PermissionError(13, "held open")+ return real_rename(self, target)++ monkeypatch.setattr(Path, "rename", deny_hermes)+ monkeypatch.setattr(cli_main, "_hermes_exe_shims", lambda d: shims)++ install_ran = []+ monkeypatch.setattr(+ cli_main, "_run_install_with_heartbeat",+ lambda cmd, env=None: install_ran.append(cmd),+ )++ with pytest.raises(cli_main.ShimQuarantineError) as exc_info:+ cli_main._run_quarantined_install(+ ["uv", "pip", "install", "-e", "."],+ scripts_dir=scripts,+ strict_quarantine=True,+ )++ # The installer NEVER ran — that is the whole fix.+ assert install_ran == []+ assert "hermes.exe" in exc_info.value.failed_shims+ # The successful rename (hermes-gateway.exe) was rolled back.+ assert (scripts / "hermes-gateway.exe").exists()+ assert not list(scripts.glob("hermes-gateway.exe.old.*"))+++def test_non_strict_keeps_warn_and_try(windows, tmp_path, monkeypatch):+ scripts = tmp_path / "venv" / "Scripts"+ shims = _make_shims(scripts, names=("hermes",))+ monkeypatch.setattr(+ Path, "rename",+ mock.Mock(side_effect=PermissionError(13, "held open")),+ )+ monkeypatch.setattr(cli_main, "_hermes_exe_shims", lambda d: shims)++ install_ran = []+ monkeypatch.setattr(+ cli_main, "_run_install_with_heartbeat",+ lambda cmd, env=None: install_ran.append(cmd),+ )++ # Default (non-strict): installer still runs — old behavior for repair+ # paths whose venv is already mutated.+ cli_main._run_quarantined_install(["fake"], scripts_dir=scripts)+ assert install_ran == [["fake"]]+++def test_strict_all_renames_ok_runs_install(windows, tmp_path, monkeypatch):+ scripts = tmp_path / "venv" / "Scripts"+ shims = _make_shims(scripts)+ monkeypatch.setattr(cli_main, "_hermes_exe_shims", lambda d: shims)++ install_ran = []+ monkeypatch.setattr(+ cli_main, "_run_install_with_heartbeat",+ lambda cmd, env=None: install_ran.append(cmd),+ )+ cli_main._run_quarantined_install(+ ["fake"], scripts_dir=scripts, strict_quarantine=True+ )+ assert install_ran == [["fake"]]+++def test_update_sync_installs_are_strict(windows, tmp_path, monkeypatch):+ """_install_python_dependencies_with_optional_fallback must pass+ strict_quarantine=True — the #87331 site."""+ seen = {}++ def spy(cmd, *, env=None, scripts_dir=None, strict_quarantine=False):+ seen["strict"] = strict_quarantine++ monkeypatch.setattr(cli_main, "_run_quarantined_install", spy)+ monkeypatch.setattr(cli_main, "_venv_scripts_dir", lambda: tmp_path)+ monkeypatch.setattr(+ cli_main, "_verify_console_scripts_installed",+ lambda prefix, env=None: None,+ )+ monkeypatch.setattr(+ cli_main, "_verify_core_dependencies_installed",+ lambda prefix, env=None, group="all": None,+ )+ cli_main._install_python_dependencies_with_optional_fallback(["uv", "pip"])+ assert seen["strict"] is True+++# ---------------------------------------------------------------------------+# _install_repair.py: recovery installer is strict unconditionally+# ---------------------------------------------------------------------------++def test_recovery_install_cmd_fail_closed(windows, tmp_path, monkeypatch):+ root = tmp_path+ scripts = root / "venv" / "Scripts"+ _make_shims(scripts, names=("hermes",))++ monkeypatch.setattr(ir, "_venv_scripts_dir", lambda r: scripts)+ monkeypatch.setattr(+ Path.__module__ and os, "rename",+ mock.Mock(side_effect=PermissionError(13, "held open")),+ )++ run_calls = []+ monkeypatch.setattr(+ ir.subprocess, "run", lambda *a, **k: run_calls.append(a)+ )++ with pytest.raises(ir.ShimQuarantineError):+ ir._run_install_cmd(["fake"], env=None, root=root)+ assert run_calls == [] # contended venv never mutated+++def test_recovery_install_cmd_ok_when_uncontended(windows, tmp_path, monkeypatch):+ root = tmp_path+ scripts = root / "venv" / "Scripts"+ _make_shims(scripts, names=("hermes",))+ monkeypatch.setattr(ir, "_venv_scripts_dir", lambda r: scripts)++ run_calls = []+ monkeypatch.setattr(+ ir.subprocess, "run",+ lambda *a, **k: run_calls.append(a) or mock.Mock(returncode=0),+ )+ ir._run_install_cmd(["fake"], env=None, root=root)+ assert len(run_calls) == 1+++# ---------------------------------------------------------------------------+# update_cmd.py: boundary refusal — marker + exit 2, no ZIP fallback+# ---------------------------------------------------------------------------++def test_refusal_writes_marker_and_exits_2(monkeypatch, capsys):+ wrote = []+ monkeypatch.setattr(+ update_cmd, "_write_update_incomplete_marker", lambda: wrote.append(1)+ )+ exc = cli_main.ShimQuarantineError(["hermes.exe"])+ with pytest.raises(SystemExit) as exit_info:+ update_cmd._refuse_update_for_contended_shims(exc)+ assert exit_info.value.code == 2+ assert wrote == [1]+ out = capsys.readouterr().out+ assert "hermes.exe" in out+ assert "deferred" in out+++def test_shim_error_type_resolves_real_class():+ assert update_cmd._shim_quarantine_error_type() is cli_main.ShimQuarantineError+++def test_shim_error_is_not_a_zip_fallback_trigger():+ exc = cli_main.ShimQuarantineError(["hermes.exe"])+ assert update_cmd._should_zip_fallback_on_update_error(exc) is False