The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(pm): sweep leftover corrupt cache entries only under uv's lock
Ben Barclay00eab5ba8214
diff --git a/pm/environment.py b/pm/environment.pyindex d6d1edb4f16..d62e071b74d 100644--- a/pm/environment.py+++ b/pm/environment.py@@ -479,7 +479,13 @@ class PythonEnvironment:if self.output is not None:self.output.write(f"The cached copy of {', '.join(names)} is corrupt; ""removing it from the uv cache and retrying the install.\n")- self.purge_cached_packages(names)+ try:+ self.purge_cached_packages(names)+ except InstallError as exc:+ # Keep the install failure that started this; the clean error alone hides it.+ original = f"{result.stderr or ''}\n{result.stdout or ''}".strip()[-600:]+ raise InstallError(exc.package, f"{exc.cause}; uv {stage} had failed with: {original}",+ exc.remedy) from excpurged.update(names)result = attempt()if not result.returncode or not purged:diff --git a/pm/uv_cache_health.py b/pm/uv_cache_health.pyindex e10fa10526f..d90b761d2d8 100644--- a/pm/uv_cache_health.py+++ b/pm/uv_cache_health.py@@ -7,15 +7,21 @@ survive while the files read back as NUL bytes. uv then reuses that entry onevery later sync and fails at install time with "The wheel is invalid", andretrying cannot help. These helpers recognise that failure and name thepackages to purge. Deletion always goes through ``uv cache clean`` (the caller),-which takes uv's cache lock, so a concurrent sync never loses files mid-read.+which takes uv's cache lock, so a concurrent sync never loses files mid-read;+the leftover-archive sweep takes that same lock itself.Stdlib only: the bootstrap runner imports pm.environment on an older systempython."""from __future__ import annotations+import osfrom pathlib import Pathimport re+import shutil+import sys++from pm.filesystem import is_junction, lock_fd# uv's install step names the wheel it was linking from the cache:# error: Failed to install: lxml-6.1.3-cp314-...whl (lxml==6.1.3)@@ -64,34 +70,62 @@ def failed_cached_packages(output: str) -> set[str]:return names-def _readable(path: Path, marker: bytes, limit: int = 65536) -> bool:+_HEAD = 65536+# How long a sweep waits for uv's cache lock before leaving the leftovers for later.+_LOCK_WAIT_SECONDS = 10.0+_WHEEL_VERSION = re.compile(rb"(?im)^wheel-version[ \t]*:")+++def _damaged(path: Path, header: re.Pattern | None = None) -> bool:+ """True only on positive evidence of a torn write: missing, empty or NUL bytes.++ A file that cannot be read for another reason (permissions) proves+ nothing and counts as healthy: a false positive would delete an entry uv+ can still use.+ """try:with path.open("rb") as stream:- head = stream.read(limit)+ head = stream.read(_HEAD)+ except FileNotFoundError:+ return Trueexcept OSError:return False- return marker in head and b"\0" not in head+ if not head or b"\0" in head:+ return True+ return header is not None and not header.search(head)+++def _archive_root(cache: Path) -> Path | None:+ """``cache/archive-v0`` when it is a real directory inside the cache, else None."""+ archive = cache / "archive-v0"+ if archive.is_symlink() or is_junction(archive) or not archive.is_dir():+ return None+ return archive-def corrupt_cache_entries(cache: Path) -> dict[str, list[Path]]:- """Unpacked cache entries uv cannot install from, by package.+def corrupt_cache_entries(cache: Path) -> dict[str, list[str]]:+ """Unpacked cache entries uv cannot install from, as package -> archive entry names.- Checks the three files uv reads first (WHEEL, METADATA, RECORD); an- interrupted write leaves them empty or NUL-filled. Entries without a- .dist-info (unknown layouts) and symlinked entries are skipped, never- guessed at. Read-only.+ Checks the three files uv reads first. An interrupted write leaves them+ missing, empty or NUL-filled, and a torn WHEEL loses its Wheel-Version+ line. Nothing else counts: unknown layouts, symlinked or junctioned+ entries and a symlinked ``archive-v0`` are skipped, never guessed at.+ Read-only."""- archive = cache / "archive-v0"- found: dict[str, list[Path]] = {}+ found: dict[str, list[str]] = {}+ archive = _archive_root(cache)+ if archive is None:+ return foundtry:buckets = list(archive.iterdir())except OSError:return foundfor bucket in buckets:try:- if bucket.is_symlink() or not bucket.is_dir():+ if bucket.is_symlink() or is_junction(bucket) or not bucket.is_dir():continue- infos = [entry for entry in bucket.iterdir() if entry.name.endswith(".dist-info")]+ infos = [entry for entry in bucket.iterdir()+ if entry.name.endswith(".dist-info") and not entry.is_symlink() and entry.is_dir()]except OSError:continuefor info in infos:@@ -99,10 +133,9 @@ def corrupt_cache_entries(cache: Path) -> dict[str, list[Path]]:name = match and _valid(match.group("name"))if not name:continue- if not (_readable(info / "WHEEL", b"Wheel-Version:")- and _readable(info / "METADATA", b"Name:")- and _readable(info / "RECORD", b",")):- found.setdefault(name, []).append(bucket)+ if (_damaged(info / "WHEEL", _WHEEL_VERSION) or _damaged(info / "METADATA")+ or _damaged(info / "RECORD")):+ found.setdefault(name, []).append(bucket.name)return found@@ -111,21 +144,49 @@ def corrupt_cached_packages(cache: Path) -> set[str]:return set(corrupt_cache_entries(cache))-def remove_corrupt_entries(cache: Path, names: set[str]) -> None:+def remove_corrupt_entries(cache: Path, names: set[str]) -> bool:"""Delete the corrupt archive entries of *names* that ``uv cache clean`` left behind.Where uv links a wheel to its archive by symlink (Linux), clean drops the- link and leaves the archive, which nothing uses again. ``uv cache prune``- is not an option: PM seeds this cache from a bundle copy whose links are- real directories, and prune treats their archives as unreachable, so the- next install fails. An archive entry is never rewritten once uv renames it- into place, so deleting one that fails validation cannot take a good copy- from a concurrent install. rmtree refuses a symlinked root and does not- follow links inside it.+ link and leaves the archive, which nothing uses again but ``hermes pm+ doctor`` would keep reporting. ``uv cache prune`` is not an option: PM+ seeds this cache from a bundle copy whose links are real directories, and+ prune treats their archives as unreachable, so the next install fails.++ The sweep holds uv's own cache lock, so no uv process runs while it+ deletes, and it only takes entries the validation above proves torn.+ Deletion is anchored to a descriptor of the real ``archive-v0`` where the+ platform allows it, so a symlink swapped in above it cannot redirect the+ delete. Returns False when the lock stayed busy (the leftovers are+ harmless and the next sweep or ``hermes pm doctor --repair`` takes them)."""- import shutil-- for name, buckets in corrupt_cache_entries(cache).items():- if name in names:- for bucket in buckets:- shutil.rmtree(bucket, ignore_errors=True)+ archive = _archive_root(cache)+ if archive is None or not names:+ return True+ try:+ lock = os.open(cache / ".lock", os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0), 0o666)+ except OSError:+ return False+ try:+ if not lock_fd(lock, wait=True, timeout=_LOCK_WAIT_SECONDS):+ return False+ doomed = [bucket for name, buckets in corrupt_cache_entries(cache).items()+ if name in names for bucket in buckets]+ if not doomed:+ return True+ # rmtree's dir_fd is 3.11+; the bootstrap runner may be older.+ if sys.version_info >= (3, 11) and shutil.rmtree.avoids_symlink_attacks and hasattr(os, "O_DIRECTORY"):+ directory = os.open(archive, os.O_RDONLY | os.O_DIRECTORY | getattr(os, "O_NOFOLLOW", 0))+ try:+ for bucket in doomed:+ shutil.rmtree(bucket, dir_fd=directory, ignore_errors=True)+ finally:+ os.close(directory)+ else:+ for bucket in doomed:+ path = archive / bucket+ if not (path.is_symlink() or is_junction(path)):+ shutil.rmtree(path, ignore_errors=True)+ return True+ finally:+ os.close(lock)diff --git a/tests/pm/test_uv_cache_corruption.py b/tests/pm/test_uv_cache_corruption.pyindex 0e1430c7c42..fbd7cb4688e 100644--- a/tests/pm/test_uv_cache_corruption.py+++ b/tests/pm/test_uv_cache_corruption.py@@ -14,6 +14,7 @@ import jsonimport osfrom pathlib import Pathimport shutil+import subprocessimport sysimport pytest@@ -204,3 +205,98 @@ def test_doctor_reports_then_repairs_corrupt_cache_entries(project, tmp_path, moassert "removed corrupt entries for alpha-dep" in capsys.readouterr().outassert corrupt_cached_packages(cache) == set()assert cli._doctor_uv_cache(repair=False) == 0+++def _bucket(cache: Path, name: str = "alpha_dep", files=None) -> Path:+ """An archive entry by hand: ``files`` maps dist-info file name -> bytes."""+ info = cache / "archive-v0" / "bucket" / f"{name}-1.0.dist-info"+ info.mkdir(parents=True)+ for file, body in (files or {"WHEEL": b"\0" * 20, "METADATA": b"Name: x\n", "RECORD": b"a,,\n"}).items():+ (info / file).write_bytes(body)+ return info.parent++[email protected]("files", [+ {"WHEEL": b"wheel-version: 1.0\n", "METADATA": b"metadata-version: 2.1\nname: alpha-dep\n", "RECORD": b"a,,\n"},+ {"WHEEL": b"Wheel-Version: 1.0\n", "METADATA": b"Metadata-Version: 2.1\n" + b"X: y\n" * 20000 + b"Name: a\n",+ "RECORD": b"a,,\n"},+])+def test_valid_entries_uv_accepts_are_never_flagged(tmp_path, files):+ """Header names are case-insensitive and METADATA may be long; only torn writes count."""+ _bucket(tmp_path, files=files)+ assert corrupt_cached_packages(tmp_path) == set()++[email protected]("damage", ["WHEEL", "METADATA", "RECORD", "missing-RECORD", "WHEEL-without-version"])+def test_torn_writes_are_flagged(tmp_path, damage):+ files = {"WHEEL": b"Wheel-Version: 1.0\n", "METADATA": b"Name: alpha-dep\n", "RECORD": b"a,,\n"}+ if damage == "missing-RECORD":+ del files["RECORD"]+ elif damage == "WHEEL-without-version":+ files["WHEEL"] = b"Root-Is-Purelib: true\n"+ else:+ files[damage] = b"\0" * 152+ _bucket(tmp_path, files=files)+ assert corrupt_cached_packages(tmp_path) == {"alpha-dep"}++[email protected]("linux", "macos")[email protected]("link", ["archive", "bucket", "dist-info"])+def test_sweep_never_deletes_through_a_symlink(tmp_path, link):+ from pm.uv_cache_health import remove_corrupt_entries++ cache = tmp_path / "cache"+ outside = tmp_path / "outside"+ victim = _bucket(outside) # a corrupt-looking tree outside the cache+ (victim / "user-data").write_text("must survive", encoding="utf-8")+ archive = cache / "archive-v0"+ if link == "archive":+ cache.mkdir()+ archive.symlink_to(outside / "archive-v0", target_is_directory=True)+ elif link == "bucket":+ archive.mkdir(parents=True)+ (archive / "bucket").symlink_to(victim, target_is_directory=True)+ else:+ (archive / "bucket").mkdir(parents=True)+ info = next(victim.glob("*.dist-info"))+ (archive / "bucket" / info.name).symlink_to(info, target_is_directory=True)++ assert corrupt_cached_packages(cache) == set()+ assert remove_corrupt_entries(cache, {"alpha-dep"})+ assert (victim / "user-data").is_file() and next(victim.glob("*.dist-info")).is_dir()++[email protected]("linux", "macos")+def test_sweep_waits_for_uv_and_leaves_entries_while_uv_holds_the_cache(tmp_path, monkeypatch):+ """uv holds a shared flock on <cache>/.lock while it runs; the sweep must not delete under it."""+ import fcntl++ import pm.uv_cache_health as health++ monkeypatch.setattr(health, "_LOCK_WAIT_SECONDS", 0.2)+ bucket = _bucket(tmp_path)+ with open(tmp_path / ".lock", "w", encoding="utf-8") as held:+ fcntl.flock(held.fileno(), fcntl.LOCK_SH)+ assert health.remove_corrupt_entries(tmp_path, {"alpha-dep"}) is False+ assert bucket.is_dir()+ assert health.remove_corrupt_entries(tmp_path, {"alpha-dep"}) is True+ assert not bucket.exists()+++def test_a_failed_purge_keeps_the_original_install_error(project, tmp_path, monkeypatch):+ source, uv, env, _ = project+ _nul_fill(_cached(tmp_path / "cache", "alpha_dep") / "WHEEL")+ real = PythonEnvironment._run++ def refuse_clean(self, args, *, cwd, timeout):+ if args[:2] == ["cache", "clean"]:+ return subprocess.CompletedProcess(args, 2, "", "error: cache is read-only")+ return real(self, args, cwd=cwd, timeout=timeout)++ monkeypatch.setattr(PythonEnvironment, "_run", refuse_clean)+ second = _environment(uv, tmp_path, "second", env)+ second.create()+ with pytest.raises(InstallError) as caught:+ second.sync(source, timeout=120)+ assert "cache is read-only" in str(caught.value)+ assert "The wheel is invalid" in str(caught.value)