The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): make the self-lock deferral honest — fire only when the swap is at risk (#86735, #86780, #86781)
Teknium8711f2c00516
diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 5356b8dce77..93758d0c008 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -4382,6 +4382,7 @@ _LAZY_COMMAND_EXPORTS = {"_scan_dashboard_processes",),"hermes_cli.update_cmd": (+ "_abort_dependency_sync_if_self_locked","_add_upstream_remote","_atomic_replace_dir","_capture_active_lazy_features",@@ -4391,6 +4392,7 @@ _LAZY_COMMAND_EXPORTS = {"_cmd_update_impl","_cold_start_windows_gateway_after_update","_count_commits_between",+ "_dependency_sync_would_rewrite","_detect_self_loaded_native_modules","_detect_venv_python_processes","_defer_update_for_self_lock",diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex 9ba5091ee53..a91b8909de0 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -947,6 +947,11 @@ def _update_via_zip(args, *, had_desktop_app_before_update: bool = False):# Reinstall Python dependencies. Prefer .[all], but if one optional extra# breaks on this machine, keep base deps and reinstall the remaining extras# individually so update does not silently strip working capabilities.+ #+ # Self-lock deferral (relocated preflight — #86735): the ZIP code swap+ # above is already committed; defer only the dependency sync when this+ # process holds a native extension the sync must rewrite.+ _m()._abort_dependency_sync_if_self_locked()print("→ Updating Python dependencies...")from hermes_cli.managed_uv import ensure_uv, update_managed_uv@@ -3166,35 +3171,144 @@ def _detect_venv_python_processes(# 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.+# ``cryptography`` is the canonical case: ``hermes_cli.main`` used to import+# it at startup while resolving external secret sources; ``PyYAML``'s+# ``_yaml`` C extension is loaded by every CLI process (config parsing).# 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)",+# order) — but the guard must be HONEST (#86735/#86780/#86781: a preflight+# that fired on every run, before the fetch, re-bricked the exact flow it+# was meant to protect). Two honesty gates:+#+# 1. It only fires when the dependency sync would actually REWRITE the+# loaded distribution (``_dependency_sync_would_rewrite``): if the+# installed version already satisfies the on-disk pyproject pins, uv/pip+# will not touch the mapped ``.pyd``, so there is no lock to trip.+# 2. It runs AFTER the code swap (git pull / ZIP commit), immediately+# before the venv rewrite — so the on-disk pyproject is the NEW one+# (gate 1 compares against the right target) and a deferral no longer+# strands the user on the old checkout: the next launch's marker+# recovery completes the dependency install against the already-updated+# pyproject.+#+# Keys are module prefixes in ``sys.modules``; values are+# ``(display name, PyPI distribution name)``.+_SELF_LOCKING_NATIVE_MODULES: dict[str, tuple[str, str]] = {+ "cryptography.hazmat.bindings._rust": ("cryptography (_rust.pyd)", "cryptography"),+ "yaml._yaml": ("PyYAML (_yaml.pyd)", "pyyaml"),}+def _dependency_sync_would_rewrite(dist_name: str) -> bool | None:+ """Whether ``uv pip install -e .[all]`` would replace *dist_name*'s files.++ Compares the installed distribution version against every applicable+ requirement for it in the on-disk ``pyproject.toml`` (base dependencies+ plus all optional extras). Returns:++ - ``False`` — installed version satisfies every pin: the resolver will+ leave the wheel alone, so a mapped extension is NOT at risk.+ - ``True`` — some pin is not satisfied (or the distribution is+ missing): the sync will rewrite it.+ - ``None`` — could not determine (parse failure, unparseable pins).++ Never raises. Callers treat ``None`` as fail-OPEN (no deferral): a+ module in the registry can be loaded by every process (PyYAML), so+ deferring on uncertainty would recreate the #86735 always-firing loop.+ """+ try:+ from importlib import metadata as _ilmd++ installed = _ilmd.version(dist_name)+ except Exception:+ return True # not installed → the sync will definitely install it+ try:+ import tomllib++ from packaging.requirements import Requirement+ from packaging.utils import canonicalize_name+ from packaging.version import Version++ pyproject = _m().PROJECT_ROOT / "pyproject.toml"+ data = tomllib.loads(pyproject.read_text(encoding="utf-8"))+ project = data.get("project") or {}+ req_strings: list[str] = list(project.get("dependencies") or [])+ for extra_reqs in (project.get("optional-dependencies") or {}).values():+ req_strings.extend(extra_reqs or [])++ target = canonicalize_name(dist_name)+ installed_v = Version(installed)+ saw_pin = False+ for req_str in req_strings:+ try:+ req = Requirement(req_str)+ except Exception:+ continue+ if canonicalize_name(req.name) != target:+ continue+ if req.marker is not None and not req.marker.evaluate():+ continue+ saw_pin = True+ if installed_v not in req.specifier:+ return True+ if saw_pin:+ return False+ # Not pinned anywhere in pyproject: the resolver may still move it+ # as a transitive — we cannot cheaply predict that, so stay honest+ # about the uncertainty.+ return None+ except Exception:+ return None++def _detect_self_loaded_native_modules() -> list[str]:- """Native venv extensions already loaded into THIS updater process.+ """Native venv extensions loaded into THIS process that the sync would rewrite.Returns display names (empty off Windows — POSIX lets a running processkeep using an unlinked inode, so self-locking is a Windows-only hazard).- Never raises.+ A loaded module whose installed version already satisfies the on-disk+ pyproject pins is NOT reported: the dependency sync will not touch its+ files, so there is no swap at risk (#86735 — the always-firing variant+ of this preflight bricked every Windows update). Never raises."""if not _m()._is_windows():return []- found = [- display- for prefix, display in _SELF_LOCKING_NATIVE_MODULES.items()- if prefix in sys.modules- ]+ found = []+ for prefix, (display, dist) in _SELF_LOCKING_NATIVE_MODULES.items():+ if prefix not in sys.modules:+ continue+ # Defer ONLY on a CONFIRMED pending rewrite. An "unknown" result+ # (unreadable/unparseable pyproject, no pin found) must fail OPEN:+ # PyYAML is loaded in every CLI process, so treating unknown as+ # at-risk would re-create the exact always-firing loop this guard's+ # first version caused (#86735). The downside of a missed deferral+ # is the pre-existing failure mode — a mid-sync os error 5 that the+ # marker recovery already handles — which is strictly less harmful+ # than an update that can never run.+ if _m()._dependency_sync_would_rewrite(dist) is not True:+ continue+ found.append(display)return sorted(set(found))+def _abort_dependency_sync_if_self_locked(gateway_resume=None) -> None:+ """Defer (exit 2) when THIS process holds a native module the sync must replace.++ Runs at the last moment before the venv rewrite — after the code swap —+ so the on-disk pyproject reflects the update target and a deferral+ leaves the user on NEW code with only the dependency install pending+ (completed by the next launch's marker recovery). No-op when nothing+ at-risk is loaded.+ """+ locked = _m()._detect_self_loaded_native_modules()+ if not locked:+ return+ _m()._defer_update_for_self_lock(locked)+ if gateway_resume is not None:+ _m()._resume_windows_gateways_after_update(gateway_resume)+ sys.exit(2)++def _defer_update_for_self_lock(loaded: list[str]) -> None:"""Bail out before the dependency sync when the updater holds a lock.@@ -3210,9 +3324,9 @@ def _defer_update_for_self_lock(loaded: list[str]) -> None: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.")+ print(" holding it. The code update has been applied; only the dependency")+ print(" sync has been deferred: the next `hermes` launch will complete it")+ print(" in a fresh process before anything imports these modules.")_m()._write_update_incomplete_marker()@@ -4313,19 +4427,17 @@ 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)+ # Self-lock deferral moved: the venv-holder sweep above excludes this+ # process by design (a CLI `hermes update` IS the venv python), and an+ # updater that has imported a native venv extension cannot rewrite its+ # own mapped .pyd (#83569). That check used to run HERE — before the+ # fetch — but firing pre-fetch meant a deferral stranded the user on the+ # OLD checkout, and any startup path that eagerly loaded cryptography+ # turned every Windows update into an exit-2 loop (#86735/#86780/#86781).+ # It now runs via _abort_dependency_sync_if_self_locked() after the code+ # swap, immediately before the dependency sync — the only phase the lock+ # can actually break — and only when the sync would truly rewrite the+ # loaded distribution.# Capture this after every fail-closed venv guard, but before either# update path can remove the ignored release tree.@@ -4594,6 +4706,9 @@ def _cmd_update_impl(args, gateway_mode: bool):print("⚠ Checkout is current, but the venv is unhealthy:")print(f" {detail}")print("→ Repairing Python dependencies...")+ # Self-lock deferral (#86735): the repair rewrites the venv+ # too — same mapped-extension hazard as the update sync.+ _m()._abort_dependency_sync_if_self_locked(_windows_gateway_resume)_write_update_incomplete_marker()from hermes_cli.managed_uv import ensure_uv@@ -4828,6 +4943,12 @@ def _cmd_update_impl(args, gateway_mode: bool):# breaks on this machine, keep base deps and reinstall the remaining extras# individually so update does not silently strip working capabilities.#+ # Self-lock deferral (relocated preflight — #86735): if THIS process+ # holds a native extension the sync must rewrite, defer NOW — after+ # the code swap, so only the dependency install is pending and the+ # next fresh launch completes it via the marker.+ _m()._abort_dependency_sync_if_self_locked(_windows_gateway_resume)+ ## Drop the core-install breadcrumb BEFORE touching the venv. If the# install is killed mid-flight (Ctrl-C, terminal close, WSL OOM), the# marker survives and the next ``hermes`` launch finishes the installdiff --git a/tests/hermes_cli/test_update_self_lock.py b/tests/hermes_cli/test_update_self_lock.pyindex faafff86f96..3c477a67928 100644--- a/tests/hermes_cli/test_update_self_lock.py+++ b/tests/hermes_cli/test_update_self_lock.py@@ -1,36 +1,110 @@-"""Regression coverage for the updater self-lock preflight (#83569).+"""Regression coverage for the updater self-lock deferral (#83569, #86735).``_detect_venv_python_processes`` excludes the calling process and itsancestors by design — a CLI ``hermes update`` IS the venv python. Beforethis 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.+(e.g. ``cryptography.hazmat.bindings._rust``) died mid-sync with+``os error 5`` when ``uv`` tried to replace the mapped ``.pyd``, stranding+the venv half-updated (#83569).++The first version of the guard (#86687) fired as a PRE-FETCH preflight and+keyed on nothing but "is the module in sys.modules" — which was ALWAYS true+while ``bitwarden.py`` imported cryptography at module level, so every+Windows ``hermes update`` exited 2 before even fetching and the update+looped forever (#86735 / #86780 / #86781). The guard is now honest:++* it only reports a loaded module when the dependency sync would actually+ REWRITE that distribution (``_dependency_sync_would_rewrite`` — installed+ version vs the on-disk pyproject pins);+* it runs AFTER the code swap, immediately before the venv rewrite+ (``_abort_dependency_sync_if_self_locked``), so a deferral leaves the+ user on NEW code with only the dependency install pending."""from __future__ import annotations+import subprocessimport sys-from types import SimpleNamespace+import textwrap+from pathlib import Pathfrom unittest.mock import MagicMock, patchimport pytestimport hermes_cli.main as cli_main+import hermes_cli.update_cmd as update_cmd++ROOT = Path(__file__).resolve().parents[2]+++# ---------------------------------------------------------------------------+# _dependency_sync_would_rewrite+# ---------------------------------------------------------------------------+++class TestDependencySyncWouldRewrite:+ def _with_pyproject(self, tmp_path, body: str):+ (tmp_path / "pyproject.toml").write_text(body, encoding="utf-8")+ return patch.object(cli_main, "PROJECT_ROOT", tmp_path)++ def test_satisfied_pin_means_no_rewrite(self, tmp_path):+ with self._with_pyproject(+ tmp_path,+ '[project]\nname = "x"\ndependencies = ["cryptography==1.2.3"]\n',+ ), patch("importlib.metadata.version", return_value="1.2.3"):+ assert cli_main._dependency_sync_would_rewrite("cryptography") is False++ def test_stale_pin_means_rewrite(self, tmp_path):+ with self._with_pyproject(+ tmp_path,+ '[project]\nname = "x"\ndependencies = ["cryptography==2.0.0"]\n',+ ), patch("importlib.metadata.version", return_value="1.2.3"):+ assert cli_main._dependency_sync_would_rewrite("cryptography") is True++ def test_missing_distribution_means_rewrite(self, tmp_path):+ with self._with_pyproject(+ tmp_path,+ '[project]\nname = "x"\ndependencies = ["cryptography==2.0.0"]\n',+ ), patch(+ "importlib.metadata.version",+ side_effect=Exception("not installed"),+ ):+ assert cli_main._dependency_sync_would_rewrite("cryptography") is True++ def test_pin_in_optional_extra_is_honored(self, tmp_path):+ body = textwrap.dedent(+ """+ [project]+ name = "x"+ dependencies = []+ [project.optional-dependencies]+ all = ["cryptography>=2,<3"]+ """+ )+ with self._with_pyproject(tmp_path, body), patch(+ "importlib.metadata.version", return_value="2.5.0"+ ):+ assert cli_main._dependency_sync_would_rewrite("cryptography") is False+ with self._with_pyproject(tmp_path, body), patch(+ "importlib.metadata.version", return_value="1.0.0"+ ):+ assert cli_main._dependency_sync_would_rewrite("cryptography") is True++ def test_unpinned_distribution_is_unknown(self, tmp_path):+ with self._with_pyproject(+ tmp_path, '[project]\nname = "x"\ndependencies = ["requests"]\n'+ ), patch("importlib.metadata.version", return_value="1.0.0"):+ assert cli_main._dependency_sync_would_rewrite("pyyaml") is None++ def test_broken_pyproject_is_unknown_never_raises(self, tmp_path):+ with self._with_pyproject(tmp_path, "not [valid toml"), patch(+ "importlib.metadata.version", return_value="1.0.0"+ ):+ assert cli_main._dependency_sync_would_rewrite("cryptography") is None# ----------------------------------------------------------------------------# _detect_self_loaded_native_modules+# _detect_self_loaded_native_modules — version-gated detection# ---------------------------------------------------------------------------@@ -41,109 +115,201 @@ def test_self_lock_detection_is_noop_off_windows(_winp):@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)"- ]+def test_loaded_module_with_pending_version_change_is_flagged(_winp):+ with patch.dict(+ sys.modules, {"cryptography.hazmat.bindings._rust": MagicMock()}+ ), patch.object(cli_main, "_dependency_sync_would_rewrite", return_value=True):+ assert "cryptography (_rust.pyd)" in cli_main._detect_self_loaded_native_modules()@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() == []+def test_loaded_module_already_at_target_version_is_not_flagged(_winp):+ """#86735 core fix: loaded-but-not-changing must NOT trip the deferral.+ Installed cryptography already satisfies the on-disk pins → the sync+ will not touch ``_rust.pyd`` → no lock risk → the update must proceed.+ """+ with patch.dict(+ sys.modules, {"cryptography.hazmat.bindings._rust": MagicMock()}+ ), patch.object(cli_main, "_dependency_sync_would_rewrite", return_value=False):+ assert cli_main._detect_self_loaded_native_modules() == []-# ----------------------------------------------------------------------------# Preflight wiring inside _cmd_update_impl-# ---------------------------------------------------------------------------[email protected](cli_main, "_is_windows", return_value=True)+def test_unknown_rewrite_risk_fails_open(_winp):+ """Uncertain rewrite risk must NOT defer (None → proceed).-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)+ PyYAML is loaded by every CLI process; deferring on an unparseable+ pyproject would recreate the #86735 always-firing loop. The missed-+ deferral downside is the pre-existing mid-sync failure, which the+ marker recovery already handles.+ """+ with patch.dict(+ sys.modules, {"cryptography.hazmat.bindings._rust": MagicMock()}+ ), patch.object(cli_main, "_dependency_sync_would_rewrite", return_value=None):+ assert cli_main._detect_self_loaded_native_modules() == []-def _run_update_until_sync(args, *, self_locked: list[str]):- """Drive _cmd_update_impl to just past the self-lock preflight.[email protected](cli_main, "_is_windows", return_value=True)+def test_self_lock_detection_clean_when_rust_not_loaded(_winp):+ sys.modules.pop("cryptography.hazmat.bindings._rust", None)+ with patch.object(cli_main, "_dependency_sync_would_rewrite", return_value=True):+ assert (+ "cryptography (_rust.pyd)"+ not in cli_main._detect_self_loaded_native_modules()+ )- 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+# ---------------------------------------------------------------------------+# _abort_dependency_sync_if_self_locked — deferral wiring+# ---------------------------------------------------------------------------- class _RootSentinel:- def __truediv__(self, _other):- raise _PastPreflight- marker_writes = []+def test_abort_helper_noop_when_nothing_at_risk():+ with patch.object(+ cli_main, "_detect_self_loaded_native_modules", return_value=[]+ ), patch.object(cli_main, "_defer_update_for_self_lock") as defer:+ cli_main._abort_dependency_sync_if_self_locked()+ defer.assert_not_called()- 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++def test_abort_helper_defers_and_exits_2(capsys):+ marker_writes = []+ with patch.object(+ cli_main,+ "_detect_self_loaded_native_modules",+ return_value=["cryptography (_rust.pyd)"],), 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"+ ), pytest.raises(SystemExit) as exc:+ cli_main._abort_dependency_sync_if_self_locked()+ assert exc.value.code == 2# Deferral contract: marker dropped so the next fresh launch completes- # the install before anything imports the native extension.- assert markers == ["written"]+ # the dependency install (the code swap has already happened by now).+ assert marker_writes == ["written"]out = capsys.readouterr().outassert "cryptography (_rust.pyd)" in outassert "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_abort_helper_resumes_paused_gateways_before_exit():+ resume_calls = []+ sentinel = object()+ with patch.object(+ cli_main,+ "_detect_self_loaded_native_modules",+ return_value=["cryptography (_rust.pyd)"],+ ), patch.object(cli_main, "_write_update_incomplete_marker"), patch.object(+ cli_main,+ "_resume_windows_gateways_after_update",+ side_effect=lambda token: resume_calls.append(token),+ ), pytest.raises(SystemExit):+ cli_main._abort_dependency_sync_if_self_locked(sentinel)+ assert resume_calls == [sentinel]+++# ---------------------------------------------------------------------------+# Placement: the deferral must NOT fire before the fetch (#86735 / #86780)+# ---------------------------------------------------------------------------+++def test_pre_fetch_flow_has_no_self_lock_preflight():+ """#86780 regression: a loaded native module must not block the git fetch.+ The old preflight sat between the venv-holder sweep and the fetch, so a+ universally-loaded module (bitwarden's module-level cryptography import)+ deferred every update before any code was pulled — the Windows infinite+ update loop. The deferral now lives at the dependency-sync boundaries+ only; the stretch of _cmd_update_impl between the venv-holder sweep and+ the fetch must not consult the detector at all.+ """+ import inspect++ src = inspect.getsource(update_cmd._cmd_update_impl)+ fetch_idx = src.index("Fetching updates")+ pre_fetch = src[:fetch_idx]+ assert "_detect_self_loaded_native_modules()" not in pre_fetch+ assert "_m()._abort_dependency_sync_if_self_locked" not in pre_fetch+ # ... and it must still guard the dependency sync after the code swap.+ post_fetch = src[fetch_idx:]+ assert "_m()._abort_dependency_sync_if_self_locked" in post_fetch+++def test_zip_update_guards_dependency_sync():+ import inspect++ src = inspect.getsource(update_cmd._update_via_zip)+ swap_idx = src.index("Updating Python dependencies")+ assert "_abort_dependency_sync_if_self_locked" in src[:swap_idx]+++# ---------------------------------------------------------------------------+# Import hygiene: the update entrypoint must not load cryptography at all+# ---------------------------------------------------------------------------+++class TestUpdateEntrypointImportHygiene:+ """Subprocess-verified: the CLI/update path never eagerly loads crypto.++ Empirical sys.modules assertions in a clean interpreter — the technique+ that pinned #86735's root cause. If any future module-level import of+ cryptography (or another self-locking native module) creeps back into+ the startup path, these fail before a Windows user ever hits the loop.+ """-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 == []+ def _run(self, code: str) -> subprocess.CompletedProcess[str]:+ return subprocess.run(+ [sys.executable, "-c", code],+ capture_output=True,+ text=True,+ cwd=str(ROOT),+ timeout=120,+ )++ def test_import_main_does_not_load_self_locking_modules(self):+ result = self._run(+ textwrap.dedent(+ """+ import sys+ import hermes_cli.main+ from hermes_cli.update_cmd import _SELF_LOCKING_NATIVE_MODULES+ loaded = [+ p for p in _SELF_LOCKING_NATIVE_MODULES+ if p in sys.modules and not p.startswith("yaml")+ ]+ # PyYAML is a base dep every CLI process needs (config parsing);+ # it is version-gated instead of import-gated. Everything else+ # in the registry must stay lazy.+ assert not loaded, f"eagerly loaded self-locking modules: {loaded}"+ assert "cryptography.hazmat.bindings._rust" not in sys.modules+ print("OK")+ """+ )+ )+ assert result.returncode == 0, result.stdout + result.stderr+ assert "OK" in result.stdout++ def test_update_dispatch_does_not_load_cryptography(self):+ result = self._run(+ textwrap.dedent(+ """+ import sys+ from unittest.mock import patch+ sys.argv = ["hermes", "update", "--check"]+ import hermes_cli.main as m+ with patch("hermes_cli.main._cmd_update_check", lambda *a, **k: 0):+ try:+ m.main()+ except SystemExit:+ pass+ assert "cryptography.hazmat.bindings._rust" not in sys.modules, (+ "update dispatch eagerly loaded cryptography._rust"+ )+ print("OK")+ """+ )+ )+ assert result.returncode == 0, result.stdout + result.stderr+ assert "OK" in result.stdout