The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(pm): pin held-tree cleanup with two invariants and a live Windows hold
teknium10dacc67e5a7b
diff --git a/tests/pm/test_held_entry_windows_live.py b/tests/pm/test_held_entry_windows_live.pynew file mode 100644index 00000000000..f58576f324a--- /dev/null+++ b/tests/pm/test_held_entry_windows_live.py@@ -0,0 +1,52 @@+"""Live Windows hold on a replaced PM entry (#124807).++A running Hermes process keeps the replaced interpreter's DLLs mapped, so+deleting the old entry fails with WinError 5 long after the new one is+published. This maps a real DLL from inside the live entry, reinstalls over+it, and requires the install to succeed and the tree to be reclaimed once+the image is unmapped. No modelled hold: the failure comes from the OS.+"""++from __future__ import annotations++import ctypes+import shutil+import sys+from pathlib import Path++import pytest++from pm.lock import Facts+from tests.pm.test_pm_core import pm_env as pm_env # noqa: F401 — fixture+from tests.pm._fixtures import served as served # noqa: F401 — fixture++[email protected]("windows")+def test_mapped_dll_in_replaced_entry_does_not_fail_reinstall(pm_env): # noqa: F811+ from pm.cli import cmd_gc+ from pm.install import ensure++ _, runtime, *_ = pm_env+ ensure("faketool", base_env={})+ entry = runtime / Facts(runtime / "facts.json").get("faketool")["entry"]+ dlls = Path(sys.base_prefix) / "DLLs"+ source = next(iter(sorted(dlls.glob("libcrypto-3*.dll")) or sorted(dlls.glob("*.dll"))))+ held = entry / "DLLs" / "held.dll"+ held.parent.mkdir()+ shutil.copy2(source, held)+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ kernel32.LoadLibraryW.restype = ctypes.c_void_p+ kernel32.FreeLibrary.argtypes = [ctypes.c_void_p]+ handle = kernel32.LoadLibraryW(str(held))+ assert handle, ctypes.get_last_error()+ try:+ (entry / "bin/faketool").unlink()+ runner = ensure("faketool", base_env={})+ assert entry.name in runner.env["PATH"]+ assert (entry / "bin/faketool").read_bytes() == b"#!x"+ assert not (runtime / f".previous-{entry.name}").exists()+ assert [p.name for p in runtime.glob(".reclaim-*/DLLs/held.dll")]+ finally:+ kernel32.FreeLibrary(handle)+ cmd_gc(None)+ assert not list(runtime.glob(".reclaim-*"))diff --git a/tests/pm/test_pm_core.py b/tests/pm/test_pm_core.pyindex 400711ca862..965bd0c3081 100644--- a/tests/pm/test_pm_core.py+++ b/tests/pm/test_pm_core.py@@ -236,11 +236,11 @@ def test_activation_trusts_a_recorded_entry_a_deliberate_install_repairs(pm_env,monkeypatch.setattr(ensure, "_entry_verified", verify)assert _install_names(["faketool"], verify=False) == 0assert checked == []- assert binary.read_text(encoding="utf-8") == "corrupt"+ assert binary.read_text(encoding="utf-8-sig") == "corrupt"assert _install_names(["faketool"]) == 0assert "faketool" in checked- assert binary.read_text(encoding="utf-8") == "good"+ assert binary.read_text(encoding="utf-8-sig") == "good"def test_warm_install_verifies_shared_dependencies_once_under_lock(pm_env, monkeypatch):@@ -281,7 +281,7 @@ def test_warm_install_verifies_shared_dependencies_once_under_lock(pm_env, monkewith Store(runtime).install_lock():binary.write_text("corrupt", encoding="utf-8")assert _install_names(["toptool"]) == 0- assert binary.read_text(encoding="utf-8") == "deptool"+ assert binary.read_text(encoding="utf-8-sig") == "deptool"def test_standalone_warm_ensure_does_not_wait_for_unrelated_writer(pm_env):@@ -327,7 +327,7 @@ def test_install_forgets_verification_when_state_operation_releases_lock(pm_env,monkeypatch.setattr(ensure, "sync_venv", sync)assert _install_names(["deptool", "venv", "toptool"]) == 0- assert binary.read_text(encoding="utf-8") == "deptool"+ assert binary.read_text(encoding="utf-8-sig") == "deptool"def test_version_bump_selects_the_new_tool(pm_env):@@ -469,7 +469,52 @@ def test_gc_keeps_used_removes_orphans(pm_env):assert any(p.name.startswith("faketool-1.0") for p in runtime.iterdir())-def test_locked_displacement_does_not_fail_restore_and_gc_only_reclaims_marked_one(pm_env, monkeypatch):+def _hold(monkeypatch, *prefixes):+ """Model a Windows hold (a running process mapping the old interpreter's+ DLLs): removal under these names fails past every retry; rename still works."""+ import pm.install as install++ real_remove = install._remove_entry+ held = {"on": True}++ def remove(store, name, **kw):+ if held["on"] and name.startswith(prefixes):+ raise PermissionError(13, "Access is denied")+ return real_remove(store, name, **kw)++ monkeypatch.setattr(install, "_remove_entry", remove)+ return held+++def test_held_replaced_entry_does_not_fail_reinstall_and_is_reclaimed(pm_env, monkeypatch):+ """#124807: the replaced entry is garbage once the new one is published and+ committed, so a hold on it must not fail the install, must not block the+ next publish of the same entry, and is reclaimed once released."""+ from pm.cli import cmd_gc+ from pm.install import ensure++ _, runtime, *_ = pm_env+ ensure("faketool", base_env={})+ entry_name = Facts(runtime / "facts.json").get("faketool")["entry"]+ held = _hold(monkeypatch, ".previous-", ".reclaim-")+ for _ in range(2):+ (runtime / entry_name / "bin/faketool").unlink()+ runner = ensure("faketool", base_env={})+ assert entry_name in runner.env["PATH"]+ assert (runtime / entry_name / "bin/faketool").read_bytes() == b"#!x"+ assert not (runtime / f".previous-{entry_name}").exists()+ assert len(list(runtime.glob(".reclaim-*"))) == 2++ held["on"] = False+ cmd_gc(None)+ assert not list(runtime.glob(".reclaim-*"))+ assert (runtime / entry_name / "bin/faketool").is_file()+++def test_held_displacement_does_not_fail_restore_and_gc_spares_interrupted_one(pm_env, monkeypatch):+ """A restore that succeeded leaves the displaced tree as garbage; a held one+ must not fail the install. An interrupted restore's displacement is never+ set aside, so gc keeps it."""import pm.install as installfrom pm.cli import cmd_gc@@ -478,34 +523,21 @@ def test_locked_displacement_does_not_fail_restore_and_gc_only_reclaims_marked_oentry_name = Facts(runtime / "facts.json").get("faketool")["entry"]store = Store(runtime)entry = store.entry(entry_name)- previous = store.entry(f".previous-{entry_name}")- shutil.copytree(entry, previous)+ shutil.copytree(entry, store.entry(f".previous-{entry_name}"))(entry / "corrupt.txt").write_text("bad publish", encoding="utf-8")- unmarked = store.entry(".displaced-" + "f" * 32)- unmarked.mkdir()-- original_remove = install._remove_entry+ interrupted = store.entry(".displaced-" + "f" * 32)+ interrupted.mkdir()- def locked_remove(store, name):- if name.startswith(".displaced-"):- raise PermissionError(13, "DLL still mapped")- return original_remove(store, name)-- monkeypatch.setattr(install, "_remove_entry", locked_remove)+ held = _hold(monkeypatch, ".displaced-", ".reclaim-")install.ensure("faketool", explicit=True, base_env={})-assert not (entry / "corrupt.txt").exists()- assert not previous.exists()- markers = list(runtime.glob(".displaced-*.restored"))- assert len(markers) == 1- displaced = store.entry(markers[0].name.removesuffix(".restored"))- assert displaced.is_dir()+ assert not store.entry(f".previous-{entry_name}").exists()+ assert len(list(runtime.glob(".reclaim-*"))) == 1- monkeypatch.setattr(install, "_remove_entry", original_remove)+ held["on"] = Falsecmd_gc(None)- assert not displaced.exists()- assert not markers[0].exists()- assert unmarked.is_dir(), "GC must preserve a displacement from an interrupted restore"+ assert not list(runtime.glob(".reclaim-*"))+ assert interrupted.is_dir()assert (entry / "bin/faketool").is_file()@@ -623,7 +655,7 @@ def test_machine_matches_binary_pe_headers(tmp_path):arm = tmp_path / "arm.exe"arm.write_bytes(pe(0xAA64))script = tmp_path / "tool"- script.write_text("#!/bin/sh\n")+ script.write_text("#!/bin/sh\n", encoding="utf-8")assert machine_matches_binary(amd, "win32-x64") is Trueassert machine_matches_binary(amd, "win32-arm64") is False@@ -733,7 +765,7 @@ def test_verify_missing_binary_reports_path_and_listing(tmp_path):entry actually contains — the diagnosis that exposes a bad pin."""entry = tmp_path / "entry"(entry / "bin").mkdir(parents=True)- (entry / "doc").write_text("x")+ (entry / "doc").write_text("x", encoding="utf-8")reason = FakeTool().verify(entry, current_target())assert "bin/faketool" in reasonassert "missing" in reasondiff --git a/tests/pm/test_previous_entry_discard.py b/tests/pm/test_previous_entry_discard.pydeleted file mode 100644index 4ab936c3d11..00000000000--- a/tests/pm/test_previous_entry_discard.py+++ /dev/null@@ -1,22 +0,0 @@-"""Locked stale previous entries must not fail the install that replaced them."""-from __future__ import annotations--from types import SimpleNamespace-from unittest.mock import patch--from pm.install import _discard_previous_entry---def test_discard_previous_entry_swallows_locked_file():- store = SimpleNamespace()- previous = SimpleNamespace(name=".previous-python-test")- with patch("pm.install._remove_entry", side_effect=PermissionError(5, "Access is denied")):- _discard_previous_entry(store, previous)---def test_discard_previous_entry_removes_when_unlocked():- store = SimpleNamespace()- previous = SimpleNamespace(name=".previous-python-test")- with patch("pm.install._remove_entry") as remove:- _discard_previous_entry(store, previous)- remove.assert_called_once_with(store, ".previous-python-test")