Skip to content

The agent that grows with you

fix(pm): close the file descriptor when a dist-info file is a directory

Ben Barclay9eaec9ba5d76
diff --git a/pm/uv_cache_health.py b/pm/uv_cache_health.py
index 441a80a3bc6..2ab50ecfea7 100644
--- a/pm/uv_cache_health.py
+++ b/pm/uv_cache_health.py
@@ -131,10 +131,14 @@ def _damaged_at(directory: int, name: str, header: re.Pattern | None) -> bool:
except OSError:
return False
try:
- with os.fdopen(fd, "rb") as stream:
+ # closefd=False: fdopen itself can fail (a directory in the file's place),
+ # and the descriptor must be closed either way.
+ with os.fdopen(fd, "rb", closefd=False) as stream:
return _stream_damaged(stream, header)
except OSError:
return False
+ finally:
+ os.close(fd)
def _dist_name(info: str) -> str | None:
diff --git a/tests/pm/test_uv_cache_corruption.py b/tests/pm/test_uv_cache_corruption.py
index ca1d7185107..f38805b7980 100644
--- a/tests/pm/test_uv_cache_corruption.py
+++ b/tests/pm/test_uv_cache_corruption.py
@@ -328,3 +328,18 @@ def test_a_failed_purge_keeps_the_original_install_error(project, tmp_path, monk
second.sync(source, timeout=120)
assert "cache is read-only" in str(caught.value)
assert "The wheel is invalid" in str(caught.value)
+
+
[email protected]("odd", ["WHEEL", "METADATA", "RECORD"])
+def test_sweep_closes_every_descriptor_when_a_file_is_a_directory(tmp_path, odd):
+ from pm.uv_cache_health import remove_corrupt_entries
+
+ files = {"WHEEL": b"Wheel-Version: 1.0\n", "METADATA": b"Name: alpha-dep\n", "RECORD": b"a,,\n"}
+ del files[odd]
+ info = next(_bucket(tmp_path, files=files).glob("*.dist-info"))
+ (info / odd).mkdir()
+ before = len(os.listdir("/proc/self/fd"))
+ for _ in range(20):
+ remove_corrupt_entries(tmp_path, {"alpha-dep"})
+ assert len(os.listdir("/proc/self/fd")) == before