The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(pm): keep restored runtimes usable after locked displaced cleanup (#128955)
Gille98cceaef2b57
diff --git a/pm/cli.py b/pm/cli.pyindex d4f122f828d..11dc3c926a6 100644--- a/pm/cli.py+++ b/pm/cli.py@@ -11,7 +11,8 @@ import timefrom pathlib import Pathfrom pm import termux_libs-from pm.install import _facts, _lockfile, _store, ensure, stage_only+from pm.install import (_RESTORED_DISPLACEMENT_SUFFIX, _facts, _lockfile, _remove_entry,+ _store, ensure, stage_only)from pm.operations import lock_projectfrom pm.package import InstallErrorfrom pm.paths import repo_root@@ -490,6 +491,28 @@ def _gc_store(store, facts) -> tuple[int, int]:facts.reload()keep = facts.entries_in_use()collect_partials(partials_dir)+ # A restored entry is live before its displaced replacement is removed.+ # Only the sidecar written after that restore makes the orphan safe to GC.+ for marker in sorted(store.root.glob(f".displaced-*{_RESTORED_DISPLACEMENT_SUFFIX}")):+ if marker.is_symlink() or not marker.is_file():+ continue+ displaced_name = marker.name.removesuffix(_RESTORED_DISPLACEMENT_SUFFIX)+ displaced = store.entry(displaced_name)+ if displaced.is_symlink():+ continue+ existed = displaced.exists()+ try:+ _remove_entry(store, displaced_name)+ except OSError as exc:+ print(f"keeping {displaced_name}: {exc}")+ continue+ try:+ marker.unlink(missing_ok=True)+ except OSError as exc:+ print(f"keeping reclaim marker {marker.name}: {exc}")+ if existed:+ print(f"removing {displaced_name}")+ removed += 1for item in sorted(store.root.iterdir()):if not item.is_dir():continuediff --git a/pm/install.py b/pm/install.pyindex 3b6cfd8433e..8ab88c44a33 100644--- a/pm/install.py+++ b/pm/install.py@@ -241,6 +241,9 @@ def _remove_entry(store: Store, entry_name: str) -> None:time.sleep(0.2 * (attempt + 1))+_RESTORED_DISPLACEMENT_SUFFIX = ".restored"++def _remove_downloads(store: Store, artifacts: list[dict]) -> None:"""Release this package's archives after publication, under its store lock."""for artifact in artifacts:@@ -271,7 +274,18 @@ def _restore_previous_entry(store: Store, entry, previous) -> None:displaced.rename(entry)raiseif had_entry:- _remove_entry(store, displaced.name)+ try:+ _remove_entry(store, displaced.name)+ except OSError as exc:+ # The prior entry is live again. A Windows handle on the displaced+ # tree must not turn successful recovery into another failed install.+ # Mark only this post-restore orphan as safe for `hermes pm gc`.+ marker = store.entry(f"{displaced.name}{_RESTORED_DISPLACEMENT_SUFFIX}")+ try:+ marker.touch()+ except OSError:+ raise exc+ LOG.warning("Keeping locked restored displacement %s for pm gc: %s", displaced, exc)@contextmanagerdiff --git a/tests/pm/test_pm_core.py b/tests/pm/test_pm_core.pyindex ded107f709f..400711ca862 100644--- a/tests/pm/test_pm_core.py+++ b/tests/pm/test_pm_core.py@@ -5,6 +5,7 @@ stores."""from __future__ import annotations+import shutilimport threadingfrom pathlib import Path@@ -468,6 +469,46 @@ 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):+ import pm.install as install+ from pm.cli import cmd_gc++ _, runtime, *_ = pm_env+ install.ensure("faketool", base_env={})+ entry_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)+ (entry / "corrupt.txt").write_text("bad publish", encoding="utf-8")+ unmarked = store.entry(".displaced-" + "f" * 32)+ unmarked.mkdir()++ original_remove = install._remove_entry++ 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)+ 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()++ monkeypatch.setattr(install, "_remove_entry", original_remove)+ cmd_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 (entry / "bin/faketool").is_file()++def test_gc_removes_fetch_cache_archives(pm_env):"""The fetch-<sha> download-cache dirs are install-time only — gc mustdrop them so a staged payload (and the CI cache that stores it) doesn't