Skip to content

The agent that grows with you

fix(pm): wait out Windows scanner holds in the archive hoist and entry swaps

Brooklyn Nicholson2d66d6e2f896
diff --git a/pm/filesystem.py b/pm/filesystem.py
index f8469d6b5a2..37d3e04de5f 100644
--- a/pm/filesystem.py
+++ b/pm/filesystem.py
@@ -84,6 +84,24 @@ def durable_write_bytes(path: Path, data: bytes) -> None:
Path(temporary).unlink(missing_ok=True)
+#: A handle still open inside the tree. Windows reports antivirus and indexer scans of freshly
+#: written files this way (WinError 5 and 32 both surface as EACCES) and they clear in moments;
+#: a missing source or an occupied destination never does, so those raise at once.
+_HELD_ERRNOS = frozenset({errno.EACCES, errno.EPERM, errno.EBUSY})
+_HELD_RETRY_DELAYS = (0.1, 0.2, 0.4, 0.8, 1.6)
+
+
+def retry_held(operation):
+ """Run a rename-like mutation, riding out a transient Windows hold (~3s) before raising."""
+ for delay in (*_HELD_RETRY_DELAYS, None):
+ try:
+ return operation()
+ except OSError as error:
+ if delay is None or error.errno not in _HELD_ERRNOS:
+ raise
+ time.sleep(delay)
+
+
def remove_tree(path: Path) -> None:
"""``shutil.rmtree`` that clears a Windows read-only attribute and retries that one unlink.
diff --git a/pm/install.py b/pm/install.py
index f8281131da1..fe83afe86ad 100644
--- a/pm/install.py
+++ b/pm/install.py
@@ -15,7 +15,7 @@ from typing import Optional
from pm import paths
from pm.downloader import DownloadPaused, ProgressFn
-from pm.filesystem import remove_tree
+from pm.filesystem import remove_tree, retry_held
from pm.lock import Facts, Lockfile
from pm.package import InstallError, Package, Runner, StatePackage, compose_env
from pm.plugin_inputs import Candidates, Members, PluginInput, Selection, StagedUpdate
@@ -305,12 +305,12 @@ def _restore_previous_entry(store: Store, entry, previous) -> None:
displaced = store.entry(f".displaced-{uuid.uuid4().hex}")
had_entry = entry.exists() or entry.is_symlink()
if had_entry:
- entry.rename(displaced)
+ retry_held(lambda: entry.rename(displaced))
try:
- previous.rename(entry)
+ retry_held(lambda: previous.rename(entry))
except BaseException:
if had_entry:
- displaced.rename(entry)
+ retry_held(lambda: displaced.rename(entry))
raise
if had_entry:
_discard_entry(store, displaced.name)
@@ -320,7 +320,7 @@ def _restore_previous_entry(store: Store, entry, previous) -> None:
def _publish_entry(package, store, staged, entry, previous_entry, target):
"""Keep rollback live through the caller's native facts commit, if any."""
if entry.exists() or entry.is_symlink():
- entry.rename(previous_entry)
+ retry_held(lambda: entry.rename(previous_entry))
try:
store.publish(staged, entry.name)
reason = package.verify(entry, target)
diff --git a/pm/store.py b/pm/store.py
index 1c943126601..b6754651e60 100644
--- a/pm/store.py
+++ b/pm/store.py
@@ -14,7 +14,7 @@ from contextlib import contextmanager
from pathlib import Path
from typing import IO
-from pm.filesystem import is_junction
+from pm.filesystem import is_junction, retry_held
@@ -272,7 +272,8 @@ def _zip_symlink(member: str, target: str, dest: Path) -> None:
def flatten_single_dir(dest: Path) -> None:
"""Hoist a lone top-level dir's contents unless it IS the layout
- (bin/, cmd/, lib/...). Refuses on name collisions."""
+ (bin/, cmd/, lib/...). Refuses on name collisions. The tree was extracted
+ seconds ago, when a Windows scanner still holds it (#131884)."""
keep = {"bin", "cmd", "lib", "libexec", "share", "etc", "usr"}
entries = list(dest.iterdir())
if len(entries) != 1 or not entries[0].is_dir() or entries[0].name in keep:
@@ -282,8 +283,8 @@ def flatten_single_dir(dest: Path) -> None:
target = dest / item.name
if target.exists():
return
- item.rename(target)
- inner.rmdir()
+ retry_held(lambda: item.rename(target))
+ retry_held(inner.rmdir)
def merge_tree(src: Path, dst: Path) -> None:
@@ -298,7 +299,7 @@ def merge_tree(src: Path, dst: Path) -> None:
if target.exists():
raise FileExistsError(f"archives disagree about {rel}")
target.parent.mkdir(parents=True, exist_ok=True)
- item.replace(target)
+ retry_held(lambda: item.replace(target))
def tree_digest(root: Path) -> str:
diff --git a/tests/pm/test_archive_safety.py b/tests/pm/test_archive_safety.py
index 7619c3b9d31..94ce56cff1d 100644
--- a/tests/pm/test_archive_safety.py
+++ b/tests/pm/test_archive_safety.py
@@ -248,6 +248,53 @@ class TestCollisionsAndClobbering:
assert (dest / "bin" / "gh").is_file()
+class TestTransientHolds:
+ """A Windows scanner holds a just-extracted tree, so the hoist's rename fails ``[WinError 5]``
+ (EACCES) for a moment; ffmpeg and agent-browser installs died on ``package/bin`` (#131884)."""
+
+ @pytest.fixture(autouse=True)
+ def instant_backoff(self, monkeypatch):
+ from pm import filesystem
+
+ monkeypatch.setattr(filesystem, "_HELD_RETRY_DELAYS", (0,) * len(filesystem._HELD_RETRY_DELAYS))
+
+ def _held_rename(self, monkeypatch, error: OSError, failures: float):
+ calls = []
+ real = Path.rename
+
+ def rename(self, target):
+ if self.name == "bin":
+ calls.append(self.name)
+ if len(calls) <= failures:
+ raise error
+ return real(self, target)
+
+ monkeypatch.setattr(Path, "rename", rename)
+ return calls
+
+ def test_the_hoist_waits_out_a_scanner_hold(self, tmp_path, monkeypatch):
+ dest = tmp_path / "dest"
+ extract(_tar(tmp_path / "wrapped.tar.gz", {"pkg/bin/tool": b"x", "pkg/README.md": b"docs"}), dest)
+ calls = self._held_rename(monkeypatch, PermissionError(13, "Access is denied"), failures=2)
+
+ flatten_single_dir(dest)
+
+ assert len(calls) == 3
+ assert (dest / "bin" / "tool").is_file() and (dest / "README.md").is_file()
+
+ @pytest.mark.parametrize("error", [PermissionError(13, "Access is denied"), OSError(18, "cross-device")])
+ def test_a_refusal_waiting_cannot_fix_still_raises(self, tmp_path, monkeypatch, error):
+ dest = tmp_path / "dest"
+ extract(_tar(tmp_path / "wrapped.tar.gz", {"pkg/bin/tool": b"x"}), dest)
+ calls = self._held_rename(monkeypatch, error, failures=float("inf"))
+
+ with pytest.raises(type(error)):
+ flatten_single_dir(dest)
+ from pm import filesystem
+
+ assert len(calls) == (1 if error.errno == 18 else len(filesystem._HELD_RETRY_DELAYS) + 1)
+
+
class TestStoreIsolation:
def test_extract_replaces_only_its_own_entry_directory(self, tmp_path):
"""Each staged entry owns exactly its dest dir. Neighbouring