Skip to content

The agent that grows with you

fix(pm): anchor the leftover cache sweep to one directory descriptor

Ben Barclayfbf232828af7
diff --git a/pm/uv_cache_health.py b/pm/uv_cache_health.py
index 7a728bef7b8..441a80a3bc6 100644
--- a/pm/uv_cache_health.py
+++ b/pm/uv_cache_health.py
@@ -74,29 +74,72 @@ _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]*:")
+_FILES = (("WHEEL", _WHEEL_VERSION), ("METADATA", None), ("RECORD", None))
+_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0)
+_DIRECTORY = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | _NOFOLLOW
+# The sweep works only through directory descriptors (rmtree's dir_fd is 3.11+;
+# the bootstrap runner may be older). Elsewhere it is skipped: the leftovers are
+# harmless, and on Windows uv's pointer files let `uv cache clean` take them anyway.
+_FD_SWEEP = (os.name == "posix" and sys.version_info >= (3, 11) and shutil.rmtree.avoids_symlink_attacks
+ and os.open in os.supports_dir_fd and os.scandir in os.supports_fd)
-def _damaged(path: Path, header: re.Pattern | None = None) -> bool:
- """True only on positive evidence of a torn write: missing, empty or NUL bytes.
+def _stream_damaged(stream, header: re.Pattern | None) -> bool:
+ """Positive evidence of a torn write: empty, NUL bytes anywhere, or *header* never seen.
The whole file is scanned in bounded chunks: a torn write can keep the
- first pages and lose later ones. 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.
+ first pages and lose later ones.
+ """
+ seen = header is None
+ carry = b""
+ empty = True
+ while chunk := stream.read(_HEAD):
+ empty = False
+ if b"\0" in chunk:
+ return True
+ if not seen:
+ window = carry + chunk
+ seen = bool(header.search(window))
+ carry = window[-64:]
+ return empty or not seen
+
+
+def _damaged(path: Path, header: re.Pattern | None = None) -> bool:
+ """True only on positive evidence of a torn write (see _stream_damaged).
+
+ A missing file is damage. A linked file, or one 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:
+ if path.is_symlink():
+ return False
with path.open("rb") as stream:
- head = stream.read(_HEAD)
- if not head or b"\0" in head or (header is not None and not header.search(head)):
- return True
- while chunk := stream.read(_HEAD):
- if b"\0" in chunk:
- return True
+ return _stream_damaged(stream, header)
except FileNotFoundError:
return True
except OSError:
return False
- return False
+
+
+def _damaged_at(directory: int, name: str, header: re.Pattern | None) -> bool:
+ """_damaged for *name* inside an open directory descriptor; links are not followed."""
+ try:
+ fd = os.open(name, os.O_RDONLY | _NOFOLLOW, dir_fd=directory)
+ except FileNotFoundError:
+ return True
+ except OSError:
+ return False
+ try:
+ with os.fdopen(fd, "rb") as stream:
+ return _stream_damaged(stream, header)
+ except OSError:
+ return False
+
+
+def _dist_name(info: str) -> str | None:
+ match = _DIST_INFO.fullmatch(info)
+ return _valid(match.group("name")) if match else None
def _archive_root(cache: Path) -> Path | None:
@@ -112,8 +155,8 @@ def corrupt_cache_entries(cache: Path) -> dict[str, list[str]]:
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.
+ line. Nothing else counts: unknown layouts, linked or junctioned entries,
+ linked files and a linked ``archive-v0`` are skipped, never guessed at.
Read-only.
"""
found: dict[str, list[str]] = {}
@@ -133,12 +176,8 @@ def corrupt_cache_entries(cache: Path) -> dict[str, list[str]]:
except OSError:
continue
for info in infos:
- match = _DIST_INFO.fullmatch(info.name)
- name = match and _valid(match.group("name"))
- if not name:
- continue
- if (_damaged(info / "WHEEL", _WHEEL_VERSION) or _damaged(info / "METADATA")
- or _damaged(info / "RECORD")):
+ name = _dist_name(info.name)
+ if name and any(_damaged(info / file, header) for file, header in _FILES):
found.setdefault(name, []).append(bucket.name)
return found
@@ -148,49 +187,86 @@ def corrupt_cached_packages(cache: Path) -> set[str]:
return set(corrupt_cache_entries(cache))
+def _damaged_packages_at(bucket: int) -> set[str]:
+ """corrupt_cache_entries for one bucket, read only through descriptors."""
+ with os.scandir(bucket) as entries:
+ infos = [entry.name for entry in entries
+ if entry.name.endswith(".dist-info") and entry.is_dir(follow_symlinks=False)]
+ found = set()
+ for info in infos:
+ name = _dist_name(info)
+ if not name:
+ continue
+ try:
+ info_fd = os.open(info, _DIRECTORY, dir_fd=bucket)
+ except OSError:
+ continue
+ try:
+ if any(_damaged_at(info_fd, file, header) for file, header in _FILES):
+ found.add(name)
+ finally:
+ os.close(info_fd)
+ return found
+
+
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 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).
+ Where uv links a wheel to its archive by symlink (Linux, macOS), clean
+ drops the 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 cache directory is opened once, and ``archive-v0``, the lock, every
+ entry and every file are then reached only relative to that descriptor
+ without following links, so renaming or replacing a path above or inside
+ the cache mid-sweep cannot point a delete anywhere else. The sweep holds
+ uv's own cache lock, so no uv process runs while it deletes, and it only
+ takes entries whose files prove a torn write. Returns False when the
+ sweep did not run (lock busy for _LOCK_WAIT_SECONDS, no descriptor
+ support); the leftovers are harmless, and a later sweep or ``hermes pm
+ doctor --repair`` takes them.
"""
- archive = _archive_root(cache)
- if archive is None or not names:
+ if not names:
return True
+ if not _FD_SWEEP:
+ return False
try:
- lock = os.open(cache / ".lock", os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0), 0o666)
+ cache_fd = os.open(cache, os.O_RDONLY | os.O_DIRECTORY)
+ except FileNotFoundError:
+ return True
except OSError:
return False
+ archive = lock = None
try:
+ try:
+ archive = os.open("archive-v0", _DIRECTORY, dir_fd=cache_fd)
+ except FileNotFoundError:
+ return True
+ lock = os.open(".lock", os.O_RDWR | os.O_CREAT | _NOFOLLOW, 0o666, dir_fd=cache_fd)
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))
+ with os.scandir(archive) as entries:
+ buckets = [entry.name for entry in entries if entry.is_dir(follow_symlinks=False)]
+ for bucket in buckets:
+ try:
+ bucket_fd = os.open(bucket, _DIRECTORY, dir_fd=archive)
+ except OSError:
+ continue
try:
- for bucket in doomed:
- shutil.rmtree(bucket, dir_fd=directory, ignore_errors=True)
+ doomed = bool(_damaged_packages_at(bucket_fd) & names)
+ except OSError:
+ doomed = False
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)
+ os.close(bucket_fd)
+ if doomed:
+ shutil.rmtree(bucket, dir_fd=archive, ignore_errors=True)
return True
+ except OSError:
+ return False
finally:
- os.close(lock)
+ for fd in (lock, archive, cache_fd):
+ if fd is not None:
+ os.close(fd)
diff --git a/tests/pm/test_uv_cache_corruption.py b/tests/pm/test_uv_cache_corruption.py
index 5b5ab8cf3dc..ca1d7185107 100644
--- a/tests/pm/test_uv_cache_corruption.py
+++ b/tests/pm/test_uv_cache_corruption.py
@@ -220,6 +220,7 @@ def _bucket(cache: Path, name: str = "alpha_dep", files=None) -> Path:
{"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"},
+ {"WHEEL": b"X: y\n" * 20000 + b"Wheel-Version: 1.0\n", "METADATA": 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."""
@@ -265,10 +266,34 @@ def test_sweep_never_deletes_through_a_symlink(tmp_path, link):
(archive / "bucket" / info.name).symlink_to(info, target_is_directory=True)
assert corrupt_cached_packages(cache) == set()
- assert remove_corrupt_entries(cache, {"alpha-dep"})
+ 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_stays_in_the_cache_it_opened_when_the_path_is_swapped(tmp_path, monkeypatch):
+ """Replacing the cache path with a link mid-sweep must not redirect the delete."""
+ import pm.uv_cache_health as health
+
+ cache = tmp_path / "cache"
+ torn = _bucket(cache)
+ outside = tmp_path / "outside"
+ victim = _bucket(outside)
+ (victim / "user-data").write_text("must survive", encoding="utf-8")
+ moved = tmp_path / "cache-original"
+ real_lock = health.lock_fd
+
+ def swap_then_lock(fd, **kwargs):
+ cache.rename(moved)
+ cache.symlink_to(outside, target_is_directory=True)
+ return real_lock(fd, **kwargs)
+
+ monkeypatch.setattr(health, "lock_fd", swap_then_lock)
+ assert health.remove_corrupt_entries(cache, {"alpha-dep"}) is True
+ assert (victim / "user-data").is_file()
+ assert not (moved / "archive-v0" / torn.name).exists()
+
+
@pytest.mark.platforms("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."""