diff --git a/hermes_cli/_early_recovery.py b/hermes_cli/_early_recovery.py index 7a19167eca..f0d17ce3a9 100644 --- a/hermes_cli/_early_recovery.py +++ b/hermes_cli/_early_recovery.py @@ -25,6 +25,7 @@ from __future__ import annotations import importlib import os +import shutil import subprocess import sys import time @@ -139,12 +140,96 @@ def _probe_broken_packages() -> list[str]: return broken +def _find_uv_binary() -> str | None: + """Locate a ``uv`` binary without importing third-party modules. + + uv-managed base interpreters carry an ``EXTERNALLY-MANAGED`` marker, so + the stdlib ``pip`` fallback below refuses to touch them. In that state + the only sanctioned installer is uv itself, which Hermes already vendors + (``~/.hermes/bin/uv.exe``) or the user has on PATH. Stdlib-only. + """ + exe = "uv.exe" if sys.platform == "win32" else "uv" + candidates = [ + Path.home() / ".hermes" / "bin" / exe, + Path.home() / ".local" / "bin" / exe, + Path.home() / ".cargo" / "bin" / exe, + ] + for path in candidates: + if path.is_file(): + return str(path) + return shutil.which(exe) + + +def _base_interpreter_is_externally_managed() -> bool: + """True when ``sys.executable`` is a uv/standalone-builds managed install. + + Those interpreters ship an ``EXTERNALLY-MANAGED`` marker next to their + stdlib (PEP 668), so ``python -m pip install`` aborts with + ``externally-managed-environment``. The early repair must then go + through uv (or explicitly override pip) or the reinstall no-ops and the + venv stays broken (#83569). + """ + try: + import sysconfig + + stdlib = Path(sysconfig.get_path("stdlib")) + if (stdlib / "EXTERNALLY-MANAGED").exists(): + return True + # uv 0.5+ moved the marker into a ``_uv_managed`` sentinel dir… + if (stdlib.parent / "EXTERNALLY-MANAGED").exists(): + return True + except Exception: + pass + return False + + def _run_repair_install(specs: list[str], project_root: Path) -> bool: - """ensurepip + ``pip install --force-reinstall`` the given specs. + """``uv pip`` (or stdlib ``pip``) force-reinstall of the given specs. Streams nothing to stdout (``hermes acp`` speaks JSON-RPC on stdout); output is captured and replayed to stderr only on failure. Never raises. + + Two installer paths, in priority order: + + 1. ``uv pip install`` with ``VIRTUAL_ENV`` pointed at the project venv — + required when the base interpreter is uv-managed (Windows git checkouts + install exactly this way: uv's Python declares PEP 668 + ``EXTERNALLY-MANAGED`` and plain ``python -m pip`` refuses to run). + 2. ``sys.executable -m pip`` as before, for self-contained venvs whose + interpreter carries no PEP 668 marker. """ + externally_managed = _base_interpreter_is_externally_managed() + if externally_managed: + uv = _find_uv_binary() + if uv: + env = {**os.environ, "VIRTUAL_ENV": str(project_root / "venv")} + env.pop("PYTHONHOME", None) + env.pop("PYTHONPATH", None) + try: + result = subprocess.run( + [uv, "pip", "install", "--force-reinstall", *specs], + cwd=project_root, + capture_output=True, + text=True, encoding="utf-8", errors="replace", + env=env, + ) + if result.returncode == 0: + return True + tail = (result.stderr or result.stdout or "")[-2000:] + if tail: + print(tail, file=sys.stderr) + return False + except Exception as exc: + print(f" ✗ Early venv repair could not run uv: {exc}", file=sys.stderr) + return False + # No uv available: fall through to pip with the PEP 668 override so + # the repair at least attempts to fix the venv instead of no-oping. + print( + " ⚠ Base interpreter is externally managed and no uv binary was " + "found; retrying repair via pip with PEP 668 override.", + file=sys.stderr, + ) + try: subprocess.run( [sys.executable, "-m", "ensurepip", "--upgrade", "--default-pip"], @@ -153,9 +238,13 @@ def _run_repair_install(specs: list[str], project_root: Path) -> bool: ) except Exception: pass + pip_cmd = [sys.executable, "-m", "pip", "install", "--force-reinstall"] + if externally_managed: + pip_cmd.append("--break-system-packages") + pip_cmd.extend(specs) try: result = subprocess.run( - [sys.executable, "-m", "pip", "install", "--force-reinstall", *specs], + pip_cmd, cwd=project_root, capture_output=True, text=True, encoding="utf-8", errors="replace", diff --git a/hermes_cli/main.py b/hermes_cli/main.py index 00fa300204..a619fdc42c 100644 --- a/hermes_cli/main.py +++ b/hermes_cli/main.py @@ -5194,7 +5194,9 @@ from hermes_cli.update_cmd import ( # noqa: F401 _cmd_update_impl, _cold_start_windows_gateway_after_update, _count_commits_between, + _detect_self_loaded_native_modules, _detect_venv_python_processes, + _defer_update_for_self_lock, _discard_lockfile_churn, _discard_stashed_changes, _ensure_acp_launcher, diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py index 5d14193ae8..9a5c994eb6 100644 --- a/hermes_cli/update_cmd.py +++ b/hermes_cli/update_cmd.py @@ -3038,6 +3038,61 @@ def _detect_venv_python_processes( matches.append((int(pid), str(name), cmdline_raw)) return matches +# Native-extension modules that pin files inside the venv once imported. If +# the updater process itself has any of these loaded, the dependency sync +# below cannot rewrite the backing ``.pyd``/``.dll`` — Windows blocks REPLACE +# on a mapped image — and the update dies with ``os error 5`` between +# uninstall and reinstall, stranding the venv half-updated (#83569). +# ``cryptography`` is the canonical case: ``hermes_cli.main`` imports it at +# startup while resolving external secret sources, so EVERY CLI-driven +# ``hermes update`` used to self-lock before that import was made lazy. +# Keep this guard as defence-in-depth against future eager imports (new +# secret sources, plugins absorbed into core, refactors of the startup +# order). Keys are module prefixes in ``sys.modules``; values are display +# names. +_SELF_LOCKING_NATIVE_MODULES: dict[str, str] = { + "cryptography.hazmat.bindings._rust": "cryptography (_rust.pyd)", +} + + +def _detect_self_loaded_native_modules() -> list[str]: + """Native venv extensions already loaded into THIS updater process. + + Returns display names (empty off Windows — POSIX lets a running process + keep using an unlinked inode, so self-locking is a Windows-only hazard). + Never raises. + """ + if not _m()._is_windows(): + return [] + found = [ + display + for prefix, display in _SELF_LOCKING_NATIVE_MODULES.items() + if prefix in sys.modules + ] + return sorted(set(found)) + + +def _defer_update_for_self_lock(loaded: list[str]) -> None: + """Bail out before the dependency sync when the updater holds a lock. + + The install cannot win this race from inside the locked process — even + killing threads would not unmap the image — so defer it: drop the + update-incomplete marker (next launch's fresh process completes the + install before importing anything heavy), explain, and exit 2 like the + other preflight refusals. + """ + print("✗ This updater process has already loaded native venv modules that") + print(" the dependency sync must replace:") + for name in loaded: + print(f" {name}") + print() + print(" On Windows a mapped extension cannot be replaced by the process") + print(" holding it. The update has been deferred: the next `hermes` launch") + print(" will complete it in a fresh process before anything imports these") + print(" modules.") + _m()._write_update_incomplete_marker() + + def _format_venv_python_holders_message(matches: list[tuple[int, str, str]]) -> str: """Explain which venv processes block the update and how to clear them.""" lines = [ @@ -4052,6 +4107,20 @@ def _cmd_update_impl(args, gateway_mode: bool): _m()._resume_windows_gateways_after_update(_windows_gateway_resume) sys.exit(2) + # Self-lock preflight: the venv-holder sweep above excludes this process + # by design (a CLI `hermes update` IS the venv python), so an updater + # that has already imported a native venv extension would sail through + # and lock its own dependency sync — the #83569 failure mode. Refuse + # before touching the checkout; the marker makes the next fresh launch + # finish the install. Deliberately not bypassed by --force-venv: that + # escape hatches external holders; it cannot unmap an image from the + # running process. + _self_locked = _m()._detect_self_loaded_native_modules() + if _self_locked: + _m()._defer_update_for_self_lock(_self_locked) + _m()._resume_windows_gateways_after_update(_windows_gateway_resume) + sys.exit(2) + # Try git-based update first, fall back to ZIP download on Windows # when git file I/O is broken (antivirus, NTFS filter drivers, etc.) use_zip_update = False diff --git a/tests/hermes_cli/test_early_recovery.py b/tests/hermes_cli/test_early_recovery.py index 181d4162fb..a5aead9e4c 100644 --- a/tests/hermes_cli/test_early_recovery.py +++ b/tests/hermes_cli/test_early_recovery.py @@ -184,6 +184,149 @@ def test_marker_plus_broken_probe_repairs_with_pinned_specs(tmp_path, monkeypatc assert not (root / ".update-incomplete.lock").exists() +# --------------------------------------------------------------------------- +# _run_repair_install: uv-managed base interpreters (#83569) +# --------------------------------------------------------------------------- + +def test_repair_install_prefers_uv_when_base_is_externally_managed( + tmp_path, monkeypatch +): + """uv-managed base Pythons carry EXTERNALLY-MANAGED: plain + ``python -m pip`` aborts, so the repair must go through ``uv pip`` with + VIRTUAL_ENV pointed at the project venv.""" + root = _project(tmp_path) + monkeypatch.setattr(er, "_base_interpreter_is_externally_managed", lambda: True) + monkeypatch.setattr(er, "_find_uv_binary", lambda: "/fake/uv") + + calls = [] + + def fake_run(cmd, **kwargs): + calls.append(cmd) + + class R: + returncode = 0 + stderr = "" + stdout = "" + + return R() + + monkeypatch.setattr(er.subprocess, "run", fake_run) + + assert er._run_repair_install(["cryptography==50.0.0"], root) is True + + assert len(calls) == 1 + cmd = calls[0] + assert cmd[:3] == ["/fake/uv", "pip", "install"] + assert "--force-reinstall" in cmd + assert "cryptography==50.0.0" in cmd + + +def test_repair_install_uv_sets_virtual_env_to_project_venv(tmp_path, monkeypatch): + root = _project(tmp_path) + monkeypatch.setattr(er, "_base_interpreter_is_externally_managed", lambda: True) + monkeypatch.setattr(er, "_find_uv_binary", lambda: "/fake/uv") + + seen_env = {} + + def fake_run(cmd, **kwargs): + seen_env.update(kwargs.get("env") or {}) + + class R: + returncode = 0 + stderr = "" + stdout = "" + + return R() + + monkeypatch.setattr(er.subprocess, "run", fake_run) + + assert er._run_repair_install(["PyYAML==6.0.2"], root) is True + assert seen_env.get("VIRTUAL_ENV") == str(root / "venv") + # A leaked PYTHONHOME/PYTHONPATH from the parent shell must not steer + # uv's venv resolution. + assert "PYTHONHOME" not in seen_env + assert "PYTHONPATH" not in seen_env + + +def test_repair_install_falls_back_to_break_system_packages_without_uv( + tmp_path, monkeypatch +): + """No uv anywhere: still attempt the repair with pip's PEP 668 override + instead of no-oping behind externally-managed-environment.""" + root = _project(tmp_path) + monkeypatch.setattr(er, "_base_interpreter_is_externally_managed", lambda: True) + monkeypatch.setattr(er, "_find_uv_binary", lambda: None) + + calls = [] + + def fake_run(cmd, **kwargs): + calls.append(cmd) + + class R: + returncode = 0 + stderr = "" + stdout = "" + + return R() + + monkeypatch.setattr(er.subprocess, "run", fake_run) + + assert er._run_repair_install(["cryptography==50.0.0"], root) is True + + pip_calls = [c for c in calls if "pip" in c] + assert pip_calls, calls + assert any("--break-system-packages" in c for c in pip_calls) + + +def test_repair_install_uses_plain_pip_when_not_externally_managed( + tmp_path, monkeypatch +): + """Self-contained venvs (no PEP 668 marker) keep the original behaviour: + ensurepip + plain pip, no uv lookup, no override flag.""" + root = _project(tmp_path) + monkeypatch.setattr( + er, "_base_interpreter_is_externally_managed", lambda: False + ) + monkeypatch.setattr( + er, "_find_uv_binary", lambda: pytest.fail("uv must not be consulted") + ) + + calls = [] + + def fake_run(cmd, **kwargs): + calls.append(cmd) + + class R: + returncode = 0 + stderr = "" + stdout = "" + + return R() + + monkeypatch.setattr(er.subprocess, "run", fake_run) + + assert er._run_repair_install(["cryptography==50.0.0"], root) is True + + flat = [part for cmd in calls for part in cmd] + assert "--break-system-packages" not in flat + assert any("ensurepip" in part for part in flat) + + +def test_externally_managed_detection(tmp_path, monkeypatch): + """The probe keys off the EXTERNALLY-MANAGED marker next to the stdlib.""" + import sysconfig + + real_get_path = sysconfig.get_path + monkeypatch.setattr( + sysconfig, + "get_path", + lambda key: str(tmp_path) if key == "stdlib" else real_get_path(key), + ) + assert er._base_interpreter_is_externally_managed() is False + (tmp_path / "EXTERNALLY-MANAGED").write_text("", encoding="utf-8") + assert er._base_interpreter_is_externally_managed() is True + + diff --git a/tests/hermes_cli/test_update_self_lock.py b/tests/hermes_cli/test_update_self_lock.py new file mode 100644 index 0000000000..faafff86f9 --- /dev/null +++ b/tests/hermes_cli/test_update_self_lock.py @@ -0,0 +1,149 @@ +"""Regression coverage for the updater self-lock preflight (#83569). + +``_detect_venv_python_processes`` excludes the calling process and its +ancestors by design — a CLI ``hermes update`` IS the venv python. Before +this guard, an updater that had already imported a native venv extension +(e.g. ``cryptography.hazmat.bindings._rust``, mapped the moment +``hermes_cli.main`` resolved external secret sources) sailed through every +preflight and then died mid-sync with ``os error 5`` when ``uv`` tried to +replace the mapped ``.pyd``, stranding the venv half-updated: + +- ``cryptography-48.0.1.dist-info`` left without ``RECORD`` (uninstall + finished, reinstall could not replace ``_rust.pyd``) +- ``.update-incomplete`` marker written but no actionable guidance +- every retry (git path + ZIP fallback) failing identically + +The self-lock preflight refuses the update BEFORE touching the checkout, +writes the update-incomplete marker so the next fresh launch completes the +install, and exits 2 like the other preflight refusals. +""" + +from __future__ import annotations + +import sys +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import pytest + +import hermes_cli.main as cli_main + + +# --------------------------------------------------------------------------- +# _detect_self_loaded_native_modules +# --------------------------------------------------------------------------- + + +@patch.object(cli_main, "_is_windows", return_value=False) +def test_self_lock_detection_is_noop_off_windows(_winp): + with patch.dict(sys.modules, {"cryptography.hazmat.bindings._rust": MagicMock()}): + assert cli_main._detect_self_loaded_native_modules() == [] + + +@patch.object(cli_main, "_is_windows", return_value=True) +def test_self_lock_detection_flags_loaded_rust_module(_winp): + with patch.dict(sys.modules, {"cryptography.hazmat.bindings._rust": MagicMock()}): + assert cli_main._detect_self_loaded_native_modules() == [ + "cryptography (_rust.pyd)" + ] + + +@patch.object(cli_main, "_is_windows", return_value=True) +def test_self_lock_detection_clean_when_rust_not_loaded(_winp): + # The lazy-import startup path (#73381, #83569) must NOT trip the guard: + # no cryptography module in sys.modules → no lock → update proceeds. + sys.modules.pop("cryptography.hazmat.bindings._rust", None) + assert cli_main._detect_self_loaded_native_modules() == [] + + +# --------------------------------------------------------------------------- +# Preflight wiring inside _cmd_update_impl +# --------------------------------------------------------------------------- + + +def _update_args(**overrides): + defaults = dict( + gateway=False, + check=False, + no_backup=True, + backup=False, + yes=True, + branch=None, + force=False, + force_venv=False, + ) + defaults.update(overrides) + return SimpleNamespace(**defaults) + + +def _run_update_until_sync(args, *, self_locked: list[str]): + """Drive _cmd_update_impl to just past the self-lock preflight. + + Everything before the preflight is stubbed. The first statement AFTER it + is ``git_dir = PROJECT_ROOT / ".git"`` — a PROJECT_ROOT sentinel whose + ``__truediv__`` raises marks 'preflight passed'. + """ + + class _PastPreflight(Exception): + pass + + class _RootSentinel: + def __truediv__(self, _other): + raise _PastPreflight + + marker_writes = [] + + with patch.object(cli_main, "_is_windows", return_value=True), patch.object( + cli_main, "_venv_scripts_dir", return_value=None + ), patch.object(cli_main, "_run_pre_update_backup"), patch.object( + cli_main, "_pause_windows_gateways_for_update", return_value=None + ), patch.object( + cli_main, "_resume_windows_gateways_after_update" + ), patch.object( + cli_main, "_detect_venv_python_processes", return_value=[] + ), patch.object( + cli_main, "_detect_self_loaded_native_modules", return_value=self_locked + ), patch.object( + cli_main, + "_write_update_incomplete_marker", + side_effect=lambda: marker_writes.append("written"), + ), patch.object( + cli_main, "PROJECT_ROOT", _RootSentinel() + ): + try: + cli_main._cmd_update_impl(args, gateway_mode=False) + except _PastPreflight: + return "past_preflight", marker_writes + except SystemExit as exc: + return f"exit_{exc.code}", marker_writes + return "returned", marker_writes + + +def test_self_lock_preflight_refuses_and_defers(capsys): + result, markers = _run_update_until_sync( + _update_args(), self_locked=["cryptography (_rust.pyd)"] + ) + assert result == "exit_2" + # Deferral contract: marker dropped so the next fresh launch completes + # the install before anything imports the native extension. + assert markers == ["written"] + out = capsys.readouterr().out + assert "cryptography (_rust.pyd)" in out + assert "deferred" in out + + +def test_self_lock_preflight_not_bypassed_by_force_venv(capsys): + """--force-venv escapes EXTERNAL holders; it cannot unmap an image from + the running process, so the self-lock refusal must stand.""" + result, markers = _run_update_until_sync( + _update_args(force=True, force_venv=True), + self_locked=["cryptography (_rust.pyd)"], + ) + assert result == "exit_2" + assert markers == ["written"] + + +def test_self_lock_preflight_passes_when_nothing_loaded(): + result, markers = _run_update_until_sync(_update_args(), self_locked=[]) + assert result == "past_preflight" + assert markers == []