Skip to content

The agent that grows with you

fix(win): never rewrite the in-use managed Node tree (#80926)

David Metcalfee4d0e4c3d8fc
diff --git a/hermes_cli/npm_engine.py b/hermes_cli/npm_engine.py
index c33572894e7..b26afe6a7e3 100644
--- a/hermes_cli/npm_engine.py
+++ b/hermes_cli/npm_engine.py
@@ -37,6 +37,7 @@ from pathlib import Path
from hermes_constants import (
bootstrap_hermes_managed_node,
get_hermes_home,
+ managed_node_tree_in_use,
with_hermes_node_path,
)
@@ -184,6 +185,20 @@ def upgrade_managed_npm(
f"→ Upgrading Hermes-managed npm to satisfy {npm_range}…",
flush=True,
)
+ # The managed npm lives inside the very tree the desktop app's Node
+ # processes execute from; an in-place upgrade while it is in use fails
+ # with PermissionError: [WinError 5] on npm.cmd (#80926). Defer instead
+ # of forcing the write — the upgrade re-triggers on the next resolution
+ # (e.g. the next update once the app is closed).
+ if managed_node_tree_in_use():
+ if not quiet:
+ print(
+ " ⚠ deferred: the Hermes-managed Node.js tree is in use by a "
+ "running app; the npm upgrade will apply on a later update "
+ "once the app is closed.",
+ file=sys.stderr,
+ )
+ return False
try:
# A temp cwd keeps the checkout's .npmrc (engine-strict, min-release-age)
# from applying to the upgrade itself.
diff --git a/hermes_constants.py b/hermes_constants.py
index a9a56edefe9..4250a1dac19 100644
--- a/hermes_constants.py
+++ b/hermes_constants.py
@@ -388,11 +388,116 @@ def hermes_managed_node_tree_present(home: Path | None = None) -> bool:
return False
-def _heal_managed_node_windows() -> bool:
- """Redownload the portable Node zip into ``%HERMES_HOME%\\node`` on Windows."""
+def _path_under_any(path: str, roots: list[str]) -> bool:
+ """Return True when *path* sits inside one of *roots* (same drive).
+
+ Windows paths are case-insensitive and psutil / env vars can disagree on
+ drive-letter casing, so compare through ``normcase`` (a no-op on POSIX).
+ Each root is evaluated individually so disjoint roots both work.
+ """
+ path_norm = os.path.normcase(os.path.normpath(path))
+ for root in roots:
+ root_norm = os.path.normcase(os.path.normpath(root))
+ try:
+ if os.path.commonpath([path_norm, root_norm]) == root_norm:
+ return True
+ except ValueError:
+ # Different drives on Windows — commonpath raises.
+ continue
+ return False
+
+
+def managed_node_tree_in_use(home: Path | None = None) -> bool:
+ """Return True when any running process executes from the managed Node tree.
+
+ Windows locks executables and loaded scripts against deletion or
+ overwrite while a process runs them, so the updater must not rewrite
+ ``%HERMES_HOME%\\node`` while the desktop app's Node processes hold it —
+ ``PermissionError: [WinError 5]`` on ``npm.cmd`` is the classic symptom
+ (#80926). Always ``False`` on POSIX, which has no equivalent lock
+ semantics.
+
+ The scan is a fast pre-check that avoids pointless re-downloads in
+ long-lived processes; the rename-based swap in
+ :func:`_heal_managed_node_windows` is the authoritative in-use guard.
+ """
+ if sys.platform != "win32":
+ return False
+ try:
+ import psutil
+ except Exception:
+ return False
+ dirs: list[str] = []
+ for directory in iter_hermes_node_dirs(home):
+ try:
+ dirs.append(str(Path(directory).resolve()))
+ except OSError:
+ continue
+ if not dirs:
+ return False
+ try:
+ procs = psutil.process_iter(["exe", "cmdline"])
+ except Exception:
+ return False
+ for proc in procs:
+ try:
+ info = proc.info
+ except Exception:
+ continue
+ exe = info.get("exe")
+ if exe:
+ try:
+ exe_path = str(Path(exe).resolve())
+ except (OSError, ValueError):
+ exe_path = str(exe)
+ if _path_under_any(exe_path, dirs):
+ return True
+ for arg in info.get("cmdline") or []:
+ if _path_under_any(arg, dirs):
+ return True
+ return False
+
+
+_managed_node_in_use_notice_printed = False
+
+
+def _print_managed_node_in_use_notice() -> None:
+ """Print the managed-Node deferral notice once per process."""
+ global _managed_node_in_use_notice_printed
+ if _managed_node_in_use_notice_printed:
+ return
+ _managed_node_in_use_notice_printed = True
+ print(
+ "→ Hermes-managed Node.js is in use by a running app; deferring its "
+ "upgrade until the app is closed (re-run `hermes update` afterwards).",
+ flush=True,
+ )
+
+
+def _heal_managed_node_windows(home: Path | None = None) -> bool | None:
+ """Redownload the portable Node zip into ``%HERMES_HOME%\\node`` on Windows.
+
+ Returns ``True`` on success, ``False`` on a genuine failure (offline,
+ download error, bad archive), and ``None`` when the tree is in use and the
+ heal is deferred — callers must not record the once-per-process attempt
+ for ``None`` so a later call can retry once the tree is free.
+
+ The replacement is staging-first: the new tree is fully downloaded and
+ extracted to a sibling ``node.new-*`` directory, then the live tree is
+ renamed aside (``node.old-*``) and the staged tree renamed into place.
+ The live tree is never deleted before its replacement is ready, so an
+ interrupted heal cannot gut the running installation. Windows allows
+ renaming a tree whose executables are running (images are mapped with
+ ``FILE_SHARE_DELETE`` — the same mechanism as the hermes.exe quarantine);
+ when the OS refuses the rename, that refusal *is* the in-use signal and
+ the heal defers instead of forcing the write and crashing with
+ ``PermissionError: [WinError 5]`` on ``npm.cmd`` (#80926).
+ """
import re
import tempfile
+ import time
import urllib.request
+ import uuid
import zipfile
arch = (os.environ.get("PROCESSOR_ARCHITEW6432") or os.environ.get("PROCESSOR_ARCHITECTURE", "")).lower()
@@ -405,7 +510,35 @@ def _heal_managed_node_windows() -> bool:
else:
return False
- home = get_hermes_home()
+ home = home or get_hermes_home()
+ target = home / "node"
+
+ # Cheap pre-check: skip the download and staging work when the tree is
+ # already visibly in use. The rename-based swap below is the
+ # authoritative guard — this scan only avoids pointless re-downloads for
+ # long-lived processes whose npm resolution retries.
+ if managed_node_tree_in_use(home):
+ _print_managed_node_in_use_notice()
+ return None
+
+ # Best-effort sweep of staging/backup litter from interrupted runs; a
+ # locked file simply stays for the next attempt. Only dirs older than
+ # 10 minutes are removed so a concurrent heal's in-flight swap (whose
+ # staged/backup dirs are seconds old) is never disturbed.
+ cutoff = time.time() - 600
+ for stale in home.glob("node.old-*"):
+ try:
+ if stale.stat().st_mtime < cutoff:
+ shutil.rmtree(stale, ignore_errors=True)
+ except OSError:
+ continue
+ for stale in home.glob("node.new-*"):
+ try:
+ if stale.stat().st_mtime < cutoff:
+ shutil.rmtree(stale, ignore_errors=True)
+ except OSError:
+ continue
+
index_url = f"https://nodejs.org/dist/latest-v{_HERMES_NODE_TARGET_MAJOR}.x/"
try:
with urllib.request.urlopen(index_url, timeout=60) as response:
@@ -428,6 +561,9 @@ def _heal_managed_node_windows() -> bool:
except OSError:
return False
+ token = uuid.uuid4().hex[:8]
+ staged = home / f"node.new-{token}"
+ backup = home / f"node.old-{token}"
try:
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_path = Path(tmp_dir)
@@ -440,13 +576,51 @@ def _heal_managed_node_windows() -> bool:
extracted = next(extract_dir.glob("node-v*"), None)
if extracted is None or not extracted.is_dir():
return False
- target = home / "node"
- if target.exists():
- shutil.rmtree(target)
- shutil.move(str(extracted), str(target))
+ # Move the fully-extracted tree to a sibling staging dir so the
+ # swap below is a same-volume rename.
+ shutil.move(str(extracted), str(staged))
except OSError:
return False
+ if target.exists():
+ try:
+ os.replace(str(target), str(backup))
+ except OSError:
+ # The OS refuses to move the live tree — a running process holds
+ # it. Defer; the old tree is untouched and the next resolution
+ # (e.g. the next update after the app is closed) retries.
+ _print_managed_node_in_use_notice()
+ shutil.rmtree(staged, ignore_errors=True)
+ return None
+ # A rename preserves the directory's mtime, so a backup renamed from
+ # a long-lived tree would instantly look older than the litter-sweep
+ # cutoff to a concurrent heal. Touch it (best-effort — a failure
+ # must not abort the swap, which already succeeded) so the in-flight
+ # backup is never swept mid-swap.
+ try:
+ os.utime(backup, None)
+ except OSError:
+ pass
+ try:
+ os.replace(str(staged), str(target))
+ except OSError:
+ # Roll the live tree back and report the failure.
+ try:
+ os.replace(str(backup), str(target))
+ except OSError:
+ pass
+ shutil.rmtree(staged, ignore_errors=True)
+ return False
+ # The old tree is no longer canonical; locked files may keep it on
+ # disk until the next heal attempt, which is safe.
+ shutil.rmtree(backup, ignore_errors=True)
+ else:
+ try:
+ os.replace(str(staged), str(target))
+ except OSError:
+ shutil.rmtree(staged, ignore_errors=True)
+ return False
+
return node_tool_runnable(str(target / "node.exe"))
@@ -530,16 +704,26 @@ def heal_hermes_managed_node() -> bool:
Runs at most once per process. POSIX installs shell out to
``heal_managed_node`` in ``scripts/lib/node-bootstrap.sh``; Windows
downloads the portable zip directly (same source as ``install.ps1``).
+ A Windows deferral (the tree is in use by a running app) does NOT record
+ the attempt, so a later call — or the next process — can heal once the
+ tree is free (#80926).
"""
global _managed_node_heal_attempted
if _managed_node_heal_attempted:
return False
if not hermes_managed_node_tree_present():
return False
- _managed_node_heal_attempted = True
if sys.platform == "win32":
- return _heal_managed_node_windows()
+ result = _heal_managed_node_windows()
+ if result is None:
+ # In-use deferral: leave the attempt flag clear so a later call
+ # in this process can heal after the app releases the tree.
+ return False
+ _managed_node_heal_attempted = True
+ return bool(result)
+
+ _managed_node_heal_attempted = True
if not _NODE_BOOTSTRAP_SCRIPT.is_file():
return False
diff --git a/scripts/install.ps1 b/scripts/install.ps1
index a59f454a365..f9e481cd32c 100644
--- a/scripts/install.ps1
+++ b/scripts/install.ps1
@@ -904,6 +904,15 @@ function Update-ManagedNpm {
} catch { }
}
+ # In-app updates run while the desktop app's Node processes are alive.
+ # The managed npm lives inside the very tree they execute from, so an
+ # in-place upgrade would hit WinError 5 (Access denied) on npm.cmd
+ # (#80926). Defer; the next update with the app closed retries.
+ if (Test-ManagedNodeInUse $NodeDir) {
+ Write-Warn "Hermes-managed Node.js is in use by a running app; skipping the bundled npm upgrade (applies on a later update with the app closed)."
+ return $false
+ }
+
Write-Info "Upgrading bundled npm to satisfy $range ..."
$tmpCwd = Join-Path $env:TEMP ("hermes-npm-upgrade-" + [Guid]::NewGuid().ToString("N"))
@@ -942,6 +951,17 @@ function Update-ManagedNpm {
return $true
}
+function Test-ManagedNodeInUse {
+ param([string]$NodeDir)
+ # Windows locks files that running processes execute from. During an
+ # in-app update the desktop app's Node processes may hold the managed
+ # tree open, and rewriting it then fails with WinError 5 (Access denied)
+ # on npm.cmd (#80926). Cheap pre-check used to skip destructive steps;
+ # the rename/move itself remains the authoritative guard.
+ return @(Get-Process -ErrorAction SilentlyContinue |
+ Where-Object { $_.Path -like "$NodeDir\*" }).Count -gt 0
+}
+
# Re-discover uv without re-installing it. Cross-process stage drivers
# (the desktop GUI's onboarding wizard, CI step-runners) invoke each stage
# in a fresh powershell process, so $script:UvCmd set by Install-Uv in a
@@ -1542,8 +1562,55 @@ function Test-Node {
$extractedDir = Get-ChildItem $tmpDir -Directory | Select-Object -First 1
if ($extractedDir) {
- if (Test-Path "$HermesHome\node") { Remove-Item -Recurse -Force "$HermesHome\node" }
- Move-Item $extractedDir.FullName "$HermesHome\node"
+ # Rename-swap instead of delete-then-move: the live tree is
+ # never removed before its replacement is fully extracted.
+ # Windows permits renaming a tree with running executables,
+ # but if a process holds it without FILE_SHARE_DELETE the
+ # rename fails with WinError 5 -- that refusal means the tree
+ # is in use, so defer instead of forcing the write (#80926).
+ # Best-effort sweep of staging/backup litter from interrupted
+ # runs; locked files simply stay for the next attempt. Only
+ # dirs older than 10 minutes are removed so a concurrent
+ # heal's in-flight swap is never disturbed.
+ Get-ChildItem "$HermesHome" -Directory -Filter "node.old-*" -ErrorAction SilentlyContinue |
+ Where-Object { $_.LastWriteTime -lt (Get-Date).AddMinutes(-10) } |
+ Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
+ Get-ChildItem "$HermesHome" -Directory -Filter "node.new-*" -ErrorAction SilentlyContinue |
+ Where-Object { $_.LastWriteTime -lt (Get-Date).AddMinutes(-10) } |
+ Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
+ $stamp = [Guid]::NewGuid().ToString("N")
+ if (Test-Path "$HermesHome\node") {
+ try {
+ Rename-Item "$HermesHome\node" "$HermesHome\node.old-$stamp" -ErrorAction Stop
+ } catch {
+ Write-Warn "Hermes-managed Node.js is in use by a running app; deferring its upgrade. Close the app and re-run the update."
+ Remove-Item -Recurse -Force $tmpDir -ErrorAction SilentlyContinue
+ Remove-Item -Force $tmpZip -ErrorAction SilentlyContinue
+ return $false
+ }
+ # A rename preserves LastWriteTime, so a backup renamed
+ # from a long-lived tree would instantly look older than
+ # the litter-sweep cutoff to a concurrent heal. Touch it
+ # (best-effort) so the in-flight backup is never swept.
+ try {
+ (Get-Item "$HermesHome\node.old-$stamp").LastWriteTime = Get-Date
+ } catch { }
+ }
+ try {
+ Move-Item $extractedDir.FullName "$HermesHome\node" -ErrorAction Stop
+ } catch {
+ # Restore the live tree before bailing. A cross-volume
+ # Move-Item may have left a partial target, so clear it
+ # first (best-effort) before renaming the old tree back.
+ if (Test-Path "$HermesHome\node.old-$stamp") {
+ Remove-Item -Recurse -Force "$HermesHome\node" -ErrorAction SilentlyContinue
+ Rename-Item "$HermesHome\node.old-$stamp" "$HermesHome\node" -ErrorAction SilentlyContinue
+ }
+ Remove-Item -Recurse -Force $tmpDir -ErrorAction SilentlyContinue
+ Remove-Item -Force $tmpZip -ErrorAction SilentlyContinue
+ return $false
+ }
+ Remove-Item -Recurse -Force "$HermesHome\node.old-$stamp" -ErrorAction SilentlyContinue
# Session PATH so the rest of this run sees node/npm.
$env:Path = "$HermesHome\node;$env:Path"
diff --git a/tests/hermes_cli/test_npm_engine.py b/tests/hermes_cli/test_npm_engine.py
index a574c35e5f3..56e6e7e4264 100644
--- a/tests/hermes_cli/test_npm_engine.py
+++ b/tests/hermes_cli/test_npm_engine.py
@@ -11,6 +11,7 @@ from pathlib import Path
import pytest
+import hermes_cli.npm_engine as npm_engine
from hermes_cli.npm_engine import (
actual_npm_version,
is_ebadengine,
@@ -125,6 +126,56 @@ class TestManagedDetection:
assert managed_npm_prefix("") is None
+class TestInUseDeferral:
+ """The managed tree cannot be written while a running app executes from
+ it (WinError 5 on npm.cmd, #80926) — the npm upgrade defers instead."""
+
+ @pytest.fixture
+ def managed_npm(self, tmp_path, monkeypatch):
+ home = tmp_path / ".hermes"
+ bin_dir = home / "node" / "bin"
+ bin_dir.mkdir(parents=True)
+ npm = bin_dir / "npm"
+ npm.write_text("#!/bin/sh\n", encoding="utf-8")
+ npm.chmod(0o755)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ return npm
+
+ def test_in_use_managed_tree_defers_upgrade_without_running_npm(
+ self, managed_npm, monkeypatch
+ ):
+ monkeypatch.setattr(npm_engine, "managed_node_tree_in_use", lambda: True)
+
+ def forbidden_run(cmd, **kwargs):
+ raise AssertionError(f"npm must not run while the tree is in use: {cmd}")
+
+ monkeypatch.setattr(subprocess, "run", forbidden_run)
+
+ result = npm_engine.upgrade_managed_npm(
+ str(managed_npm),
+ ">=11.0.0",
+ prefix=managed_npm.parent,
+ quiet=True,
+ )
+ assert result is False
+
+ def test_in_use_deferral_blocks_repair_retry(self, managed_npm, monkeypatch):
+ """End-to-end: an in-use tree means no npm subprocess runs and no
+ retry is offered — the original EBADENGINE failure stands with the
+ deferral notice."""
+ monkeypatch.setattr(npm_engine, "managed_node_tree_in_use", lambda: True)
+
+ def forbidden_run(cmd, **kwargs):
+ raise AssertionError(f"npm must not run while the tree is in use: {cmd}")
+
+ monkeypatch.setattr(subprocess, "run", forbidden_run)
+
+ assert (
+ maybe_repair_npm_engine(str(managed_npm), EBADENGINE_OUTPUT, quiet=True)
+ is None
+ )
+
+
class TestRepairDecision:
"""`maybe_repair_npm_engine` returns the npm to retry with (truthy) only
when a repair actually happened, because its return value is what gates
diff --git a/tests/test_hermes_constants.py b/tests/test_hermes_constants.py
index 30ef95cc1f1..158b5b40414 100644
--- a/tests/test_hermes_constants.py
+++ b/tests/test_hermes_constants.py
@@ -666,3 +666,378 @@ class TestWslPathTranslation:
assert hermes_constants.translate_cwd_for_wsl_backend(r"\\wsl.localhost\Ubuntu\home\alex") == "/home/alex"
# Already-POSIX paths pass through untouched.
assert hermes_constants.translate_cwd_for_wsl_backend("/home/alex") == "/home/alex"
+
+
+class TestManagedNodeTreeInUse:
+ """managed_node_tree_in_use() detects processes executing from the tree."""
+
+ def _install_fake_psutil(self, monkeypatch, procs):
+ import sys
+ from types import SimpleNamespace
+
+ monkeypatch.setattr(hermes_constants.sys, "platform", "win32")
+ fake = SimpleNamespace(
+ process_iter=lambda fields: [
+ SimpleNamespace(info=info) for info in procs
+ ]
+ )
+ monkeypatch.setitem(sys.modules, "psutil", fake)
+
+ def test_always_false_off_windows(self, tmp_path, monkeypatch):
+ monkeypatch.setattr(hermes_constants.sys, "platform", "darwin")
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ assert hermes_constants.managed_node_tree_in_use() is False
+
+ def test_exe_under_node_dir_counts(self, tmp_path, monkeypatch):
+ home = tmp_path / "hermes"
+ (home / "node").mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ self._install_fake_psutil(
+ monkeypatch,
+ [{"exe": str(home / "node" / "node.exe"), "cmdline": None}],
+ )
+ assert hermes_constants.managed_node_tree_in_use() is True
+
+ def test_cmdline_arg_under_node_dir_counts(self, tmp_path, monkeypatch):
+ home = tmp_path / "hermes"
+ (home / "node").mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ self._install_fake_psutil(
+ monkeypatch,
+ [
+ {
+ "exe": r"C:\Windows\System32\cmd.exe",
+ "cmdline": [r"C:\Windows\System32\cmd.exe", "/d", "/s", "/c", str(home / "node" / "npm.cmd")],
+ }
+ ],
+ )
+ assert hermes_constants.managed_node_tree_in_use() is True
+
+ def test_unrelated_process_does_not_count(self, tmp_path, monkeypatch):
+ home = tmp_path / "hermes"
+ (home / "node").mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ self._install_fake_psutil(
+ monkeypatch,
+ [{"exe": r"C:\Program Files\nodejs\node.exe", "cmdline": None}],
+ )
+ assert hermes_constants.managed_node_tree_in_use() is False
+
+ def test_missing_psutil_is_false(self, tmp_path, monkeypatch):
+ import sys
+
+ monkeypatch.setattr(hermes_constants.sys, "platform", "win32")
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ # None in sys.modules makes `import psutil` raise ImportError.
+ monkeypatch.setitem(sys.modules, "psutil", None)
+ assert hermes_constants.managed_node_tree_in_use() is False
+
+
+class _FakeUrlResponse:
+ def __init__(self, payload: bytes):
+ self._payload = payload
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ return False
+
+ def read(self):
+ return self._payload
+
+
+def _make_node_zip(major: int) -> tuple[str, bytes]:
+ import io
+ import zipfile
+
+ name = f"node-v{major}.5.1-win-x64.zip"
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as archive:
+ root = f"node-v{major}.5.1-win-x64"
+ archive.writestr(f"{root}/node.exe", b"fake-node")
+ archive.writestr(f"{root}/npm.cmd", "@echo off\r\n")
+ return name, buf.getvalue()
+
+
+class TestWindowsHealStageSwap:
+ """_heal_managed_node_windows() must never destroy the live tree before
+ its replacement is fully staged, and must defer (return None) when the
+ tree is in use instead of forcing the write (#80926)."""
+
+ def _stub_env(
+ self, monkeypatch, home, zip_name, zip_bytes, *, in_use=False
+ ):
+ import urllib.request
+
+ monkeypatch.setattr(hermes_constants.sys, "platform", "win32")
+ monkeypatch.setenv("PROCESSOR_ARCHITECTURE", "AMD64")
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setenv(
+ "HERMES_NODE_TARGET_MAJOR",
+ str(hermes_constants._HERMES_NODE_TARGET_MAJOR),
+ )
+ monkeypatch.setattr(hermes_constants, "_managed_node_heal_attempted", False)
+ monkeypatch.setattr(
+ hermes_constants, "_managed_node_in_use_notice_printed", False
+ )
+ monkeypatch.setattr(
+ hermes_constants,
+ "managed_node_tree_in_use",
+ lambda _home=None: in_use,
+ )
+ monkeypatch.setattr(
+ hermes_constants, "node_tool_runnable", lambda path: True
+ )
+
+ index_html = f'<a href="./{zip_name}">{zip_name}</a>'.encode()
+
+ def fake_urlopen(url, timeout=0):
+ if str(url).endswith(".zip"):
+ return _FakeUrlResponse(zip_bytes)
+ return _FakeUrlResponse(index_html)
+
+ monkeypatch.setattr(urllib.request, "urlopen", fake_urlopen)
+
+ def test_in_use_defers_without_touching_tree(self, tmp_path, monkeypatch):
+ import urllib.request
+
+ home = tmp_path / "hermes"
+ old = home / "node"
+ old.mkdir(parents=True)
+ (old / "node.exe").write_text("old", encoding="utf-8")
+ (old / "npm.cmd").write_text("@echo off", encoding="utf-8")
+ zip_name, zip_bytes = _make_node_zip(hermes_constants._HERMES_NODE_TARGET_MAJOR)
+ self._stub_env(monkeypatch, home, zip_name, zip_bytes, in_use=True)
+
+ def forbidden_urlopen(url, timeout=0):
+ raise AssertionError(f"no download may start while the tree is in use: {url}")
+
+ monkeypatch.setattr(urllib.request, "urlopen", forbidden_urlopen)
+
+ result = hermes_constants._heal_managed_node_windows()
+
+ assert result is None
+ # The live tree is untouched, and no staging litter remains.
+ assert (old / "node.exe").read_text(encoding="utf-8") == "old"
+ assert list(home.glob("node.new-*")) == []
+ assert list(home.glob("node.old-*")) == []
+
+ def test_swap_replaces_tree_and_cleans_up(self, tmp_path, monkeypatch):
+ home = tmp_path / "hermes"
+ old = home / "node"
+ old.mkdir(parents=True)
+ (old / "node.exe").write_text("old", encoding="utf-8")
+ (old / "old-marker").write_text("stale", encoding="utf-8")
+ zip_name, zip_bytes = _make_node_zip(hermes_constants._HERMES_NODE_TARGET_MAJOR)
+ self._stub_env(monkeypatch, home, zip_name, zip_bytes, in_use=False)
+
+ result = hermes_constants._heal_managed_node_windows()
+
+ assert result is True
+ assert (home / "node" / "node.exe").exists()
+ assert not (home / "node" / "old-marker").exists()
+ assert list(home.glob("node.new-*")) == []
+ assert list(home.glob("node.old-*")) == []
+
+ def test_creates_tree_when_absent(self, tmp_path, monkeypatch):
+ home = tmp_path / "hermes"
+ home.mkdir()
+ zip_name, zip_bytes = _make_node_zip(hermes_constants._HERMES_NODE_TARGET_MAJOR)
+ self._stub_env(monkeypatch, home, zip_name, zip_bytes, in_use=False)
+
+ result = hermes_constants._heal_managed_node_windows()
+
+ assert result is True
+ assert (home / "node" / "node.exe").exists()
+ assert list(home.glob("node.new-*")) == []
+
+ def test_rename_refusal_defers_and_preserves_tree(self, tmp_path, monkeypatch):
+ import os as _os
+
+ home = tmp_path / "hermes"
+ old = home / "node"
+ old.mkdir(parents=True)
+ (old / "node.exe").write_text("old", encoding="utf-8")
+ zip_name, zip_bytes = _make_node_zip(hermes_constants._HERMES_NODE_TARGET_MAJOR)
+ self._stub_env(monkeypatch, home, zip_name, zip_bytes, in_use=False)
+
+ real_replace = _os.replace
+ state = {"calls": 0}
+
+ def flaky_replace(src, dst):
+ state["calls"] += 1
+ if state["calls"] == 1:
+ raise PermissionError(13, "Access is denied", str(src))
+ return real_replace(src, dst)
+
+ monkeypatch.setattr(_os, "replace", flaky_replace)
+
+ result = hermes_constants._heal_managed_node_windows()
+
+ assert result is None
+ # The OS refused the swap — the live tree must survive intact.
+ assert (old / "node.exe").read_text(encoding="utf-8") == "old"
+ assert list(home.glob("node.new-*")) == []
+ assert list(home.glob("node.old-*")) == []
+
+
+ def test_touch_failure_does_not_abort_swap(self, tmp_path, monkeypatch):
+ """The post-rename mtime touch is best-effort: a touch failure must
+ not abort a swap that already succeeded."""
+ import os as _os
+
+ home = tmp_path / "hermes"
+ old = home / "node"
+ old.mkdir(parents=True)
+ (old / "node.exe").write_text("old", encoding="utf-8")
+ zip_name, zip_bytes = _make_node_zip(hermes_constants._HERMES_NODE_TARGET_MAJOR)
+ self._stub_env(monkeypatch, home, zip_name, zip_bytes, in_use=False)
+
+ calls = {"n": 0}
+
+ def failing_utime(path, times=None):
+ calls["n"] += 1
+ raise PermissionError(13, "Access is denied", str(path))
+
+ monkeypatch.setattr(_os, "utime", failing_utime)
+ result = hermes_constants._heal_managed_node_windows()
+
+ assert result is True
+ assert calls["n"] >= 1
+ # The new tree is in place despite the touch failure.
+ assert (home / "node" / "node.exe").exists()
+ assert list(home.glob("node.new-*")) == []
+ # The old tree was swapped aside and then removed.
+ assert list(home.glob("node.old-*")) == []
+
+ def test_second_rename_failure_rolls_back(self, tmp_path, monkeypatch):
+ """The staged->live rename failing must restore the live tree and
+ remove the staged copy, reporting a genuine failure (not a deferral)."""
+ import os as _os
+
+ home = tmp_path / "hermes"
+ old = home / "node"
+ old.mkdir(parents=True)
+ (old / "node.exe").write_text("old", encoding="utf-8")
+ zip_name, zip_bytes = _make_node_zip(hermes_constants._HERMES_NODE_TARGET_MAJOR)
+ self._stub_env(monkeypatch, home, zip_name, zip_bytes, in_use=False)
+
+ real_replace = _os.replace
+ state = {"calls": 0}
+
+ def flaky_replace(src, dst):
+ state["calls"] += 1
+ if state["calls"] == 2:
+ raise PermissionError(13, "Access is denied", str(src))
+ return real_replace(src, dst)
+
+ monkeypatch.setattr(_os, "replace", flaky_replace)
+
+ result = hermes_constants._heal_managed_node_windows()
+
+ assert result is False
+ # The live tree was rolled back into place; the staged copy is gone.
+ assert (old / "node.exe").read_text(encoding="utf-8") == "old"
+ assert list(home.glob("node.new-*")) == []
+ assert list(home.glob("node.old-*")) == []
+
+ def test_stale_staging_litter_is_swept(self, tmp_path, monkeypatch):
+ import os as _os
+ import time as _time
+
+ home = tmp_path / "hermes"
+ (home / "node").mkdir(parents=True)
+ (home / "node" / "node.exe").write_text("old", encoding="utf-8")
+ stale_backup = home / "node.old-deadbeef"
+ stale_backup.mkdir()
+ (stale_backup / "node.exe").write_text("stale", encoding="utf-8")
+ stale_staged = home / "node.new-deadbeef"
+ stale_staged.mkdir()
+ (stale_staged / "node.exe").write_text("stale", encoding="utf-8")
+ # The sweep only removes litter older than 10 minutes, so backdate.
+ old_ts = _time.time() - 3600
+ _os.utime(stale_backup, (old_ts, old_ts))
+ _os.utime(stale_staged, (old_ts, old_ts))
+ zip_name, zip_bytes = _make_node_zip(hermes_constants._HERMES_NODE_TARGET_MAJOR)
+ self._stub_env(monkeypatch, home, zip_name, zip_bytes, in_use=False)
+
+ result = hermes_constants._heal_managed_node_windows()
+
+ assert result is True
+ assert not stale_backup.exists()
+ assert not stale_staged.exists()
+ assert (home / "node" / "node.exe").exists()
+
+ def test_fresh_staging_dirs_are_not_swept(self, tmp_path, monkeypatch):
+ """A concurrent heal's in-flight backup must survive the sweep even
+ when it was renamed from a long-lived tree (rename preserves mtime —
+ the production code touches it after the rename, and the sweep must
+ respect that)."""
+ import os as _os
+ import time as _time
+
+ home = tmp_path / "hermes"
+ (home / "node").mkdir(parents=True)
+ (home / "node" / "node.exe").write_text("old", encoding="utf-8")
+ # Simulate a long-lived tree being renamed aside mid-swap: backdate
+ # it, rename, then touch exactly like the production swap does.
+ old_ts = _time.time() - 3600
+ _os.utime(home / "node", (old_ts, old_ts))
+ fresh_backup = home / "node.old-deadbeef"
+ _os.replace(str(home / "node"), str(fresh_backup))
+ _os.utime(fresh_backup, None)
+ zip_name, zip_bytes = _make_node_zip(hermes_constants._HERMES_NODE_TARGET_MAJOR)
+ self._stub_env(monkeypatch, home, zip_name, zip_bytes, in_use=False)
+
+ result = hermes_constants._heal_managed_node_windows()
+
+ assert result is True
+ assert fresh_backup.exists()
+
+
+class TestHealAttemptFlagSemantics:
+ """An in-use deferral must not record the once-per-process heal attempt,
+ so a later call can retry once the tree is free (#80926)."""
+
+ def test_deferral_keeps_flag_clear_and_retries(self, tmp_path, monkeypatch):
+ home = tmp_path / "hermes"
+ (home / "node").mkdir(parents=True)
+ (home / "node" / "node.exe").write_text("x", encoding="utf-8")
+ monkeypatch.setattr(hermes_constants.sys, "platform", "win32")
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setattr(hermes_constants, "_managed_node_heal_attempted", False)
+ calls = {"n": 0}
+
+ def fake_heal():
+ calls["n"] += 1
+ return None
+
+ monkeypatch.setattr(hermes_constants, "_heal_managed_node_windows", fake_heal)
+
+ assert heal_hermes_managed_node() is False
+ assert hermes_constants._managed_node_heal_attempted is False
+ # The flag stayed clear, so the next call retries the heal.
+ assert heal_hermes_managed_node() is False
+ assert calls["n"] == 2
+
+ def test_real_failure_records_attempt(self, tmp_path, monkeypatch):
+ home = tmp_path / "hermes"
+ (home / "node").mkdir(parents=True)
+ (home / "node" / "node.exe").write_text("x", encoding="utf-8")
+ monkeypatch.setattr(hermes_constants.sys, "platform", "win32")
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setattr(hermes_constants, "_managed_node_heal_attempted", False)
+ calls = {"n": 0}
+
+ def fake_heal():
+ calls["n"] += 1
+ return False
+
+ monkeypatch.setattr(hermes_constants, "_heal_managed_node_windows", fake_heal)
+
+ assert heal_hermes_managed_node() is False
+ assert hermes_constants._managed_node_heal_attempted is True
+ # The flag is set, so the once-per-process budget is spent.
+ assert heal_hermes_managed_node() is False
+ assert calls["n"] == 1