Skip to content

The agent that grows with you

fix(pm): scan whole dist-info files for torn writes

Ben Barclay3819a978936c
diff --git a/pm/uv_cache_health.py b/pm/uv_cache_health.py
index d90b761d2d8..7a728bef7b8 100644
--- a/pm/uv_cache_health.py
+++ b/pm/uv_cache_health.py
@@ -79,20 +79,24 @@ _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.
+ 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.
"""
try:
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
except FileNotFoundError:
return True
except OSError:
return False
- if not head or b"\0" in head:
- return True
- return header is not None and not header.search(head)
+ return False
def _archive_root(cache: Path) -> Path | None:
diff --git a/tests/pm/test_uv_cache_corruption.py b/tests/pm/test_uv_cache_corruption.py
index fbd7cb4688e..5b5ab8cf3dc 100644
--- a/tests/pm/test_uv_cache_corruption.py
+++ b/tests/pm/test_uv_cache_corruption.py
@@ -227,10 +227,13 @@ def test_valid_entries_uv_accepts_are_never_flagged(tmp_path, files):
assert corrupt_cached_packages(tmp_path) == set()
[email protected]("damage", ["WHEEL", "METADATA", "RECORD", "missing-RECORD", "WHEEL-without-version"])
[email protected]("damage", ["WHEEL", "METADATA", "RECORD", "missing-RECORD", "WHEEL-without-version",
+ "RECORD-tail"])
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":
+ if damage == "RECORD-tail": # the first pages reached the disk, a later one did not
+ files["RECORD"] = b"a/b.py,,\n" * 20000 + b"\0" * 4096
+ elif damage == "missing-RECORD":
del files["RECORD"]
elif damage == "WHEEL-without-version":
files["WHEEL"] = b"Root-Is-Purelib: true\n"