refactor(pm): one sdist seed rule for uv-cache/ and uv-cache.hpkg

The archive planner carried its own copy of the pointer-text check
(_parse_archive_pointer_bytes) and of the revision rule
(_collect_sdist_dir_buckets), and the copy had already drifted: the loose
walk judges each sdists-v* tree on its own, while the archive walk pooled
every tree, so a second sdists-v* tree with no wheel revision (another uv's
layout) fell back to a full merge from uv-cache/ but seeded selectively from
uv-cache.hpkg.

Both formats now share _pointer_text_bucket (the text rule, with the
format's own bucket-presence check) and _sdist_tree_buckets (one bucket per
wheel, and a wheel revision in every tree that holds files), applied per
sdists-v* tree. Directory walking and ZIP reads stay separate.

The selective-seed contracts in test_uv_cache_selective_seed.py now run
against both layouts, the hpkg one packed by the real
pack_uv_cache_archive. The two-tree case fails on the previous head for
hpkg only. New rows pin the presence, name and one-bucket-per-wheel
checks on their own: the stale-pointer test put its pointer beside a
valid one, so either check alone sent it to the full merge.
This commit is contained in:
BearHuddleston
2026-11-30 07:05:47 +00:00
committed by Bear Huddleston
parent c455207039
commit ee8cd63678
2 changed files with 155 additions and 98 deletions

View File

@@ -10,6 +10,8 @@ import subprocess
import sys
import tempfile
import uuid
from collections.abc import Callable, Iterable, Iterator
from functools import partial
from pathlib import Path
from typing import Literal, Optional
@@ -470,6 +472,54 @@ class _UnresolvedPointerError(Exception):
"""A pointer-shaped sdist entry whose ``archive-v0`` target the payload cache does not hold."""
def _pointer_text_bucket(name: str, size: int, read: Callable[[], bytes],
has_bucket: Callable[[str], bool]) -> str | None:
"""The ``archive-v0`` bucket a uv pointer file's text names, or ``None`` if it is not a pointer.
The one text rule for both payload formats: a loose ``uv-cache/`` file and a ``uv-cache.hpkg``
member. Raises ``_UnresolvedPointerError`` for a bucket *has_bucket* rejects.
"""
if Path(name).suffix.lower() in _SDIST_NON_POINTER_SUFFIXES or not 0 < size <= 256:
return None
try:
text = read().decode("utf-8-sig").strip()
except (OSError, UnicodeDecodeError):
return None
if not text.startswith("archive-v0/"):
return None
bucket = text[len("archive-v0/"):]
if not bucket or "/" in bucket or "\\" in bucket or bucket in (".", "..") or not has_bucket(bucket):
raise _UnresolvedPointerError(name)
return bucket
def _sdist_tree_buckets(revisions: Iterable[tuple[int, list[str | None]]]) -> set[str] | None:
"""The ``archive-v0`` buckets one ``sdists-v*`` tree's non-editable revisions reference.
Each revision is its wheel count and each entry's bucket (``None`` for a non-pointer). A
revision holding wheels must name one bucket per wheel, and a tree holding files must hold a
wheel revision. Returns ``None`` when the layout is unrecognized or a pointer cannot be
resolved, so the caller falls back to a full merge instead of risking a compiler-free source
build. Both payload formats judge each tree with this rule.
"""
buckets: set[str] = set()
saw_revision = saw_whl_revision = False
try:
for whl_count, pointers in revisions:
saw_revision = True
found = {bucket for bucket in pointers if bucket is not None}
if whl_count:
saw_whl_revision = True
if len(found) != whl_count:
return None
buckets |= found
except _UnresolvedPointerError:
return None
if saw_revision and not saw_whl_revision:
return None
return buckets
def _parse_archive_pointer(path: Path, payload_cache: Path, root: Path) -> str | None:
"""The validated ``archive-v0`` bucket name *path* references, or ``None`` if it is not a pointer.
@@ -484,61 +534,28 @@ def _parse_archive_pointer(path: Path, payload_cache: Path, root: Path) -> str |
if "archive-v0" in Path(os.readlink(path)).parts:
raise _UnresolvedPointerError(path)
return None
if not path.is_file() or path.suffix.lower() in _SDIST_NON_POINTER_SUFFIXES:
if not path.is_file():
return None
try:
size = path.stat().st_size
if size <= 0 or size > 256:
return None
text = path.read_text(encoding="utf-8-sig").strip()
except (OSError, UnicodeDecodeError):
except OSError:
return None
if not text.startswith("archive-v0/"):
return None
bucket = text[len("archive-v0/"):]
if not bucket or "/" in bucket or "\\" in bucket or bucket in (".", ".."):
raise _UnresolvedPointerError(path)
if not (payload_cache / "archive-v0" / bucket).is_dir():
raise _UnresolvedPointerError(path)
return bucket
return _pointer_text_bucket(path.name, size, path.read_bytes,
lambda bucket: (payload_cache / "archive-v0" / bucket).is_dir())
def _collect_sdist_dir_buckets(sdist_dir: Path, payload_cache: Path, root: Path) -> set[str] | None:
"""Collect ``archive-v0`` buckets referenced by non-editable builds under one ``sdists-v*`` dir.
Returns ``None`` if the cache layout is unrecognized or a pointer cannot be resolved, so the
caller falls back to a full merge instead of risking a compiler-free source build.
"""
buckets: set[str] = set()
saw_non_editable_files = False
saw_whl_revision = False
def _sdist_dir_revisions(sdist_dir: Path, payload_cache: Path,
root: Path) -> Iterator[tuple[int, list[str | None]]]:
"""Each non-editable revision directory under one loose ``sdists-v*`` dir, for ``_sdist_tree_buckets``."""
for child in sdist_dir.iterdir():
if child.name == "editable" or not child.is_dir():
continue
for dirpath, dirnames, filenames in os.walk(child):
current = Path(dirpath)
link_dirs = [name for name in dirnames if (current / name).is_symlink()]
candidates = [*filenames, *link_dirs]
if not candidates:
continue
saw_non_editable_files = True
whl_count = sum(1 for name in filenames if name.endswith(".whl"))
rev_buckets: set[str] = set()
for name in candidates:
try:
bucket = _parse_archive_pointer(current / name, payload_cache, root)
except _UnresolvedPointerError:
return None
if bucket is not None:
rev_buckets.add(bucket)
if whl_count:
saw_whl_revision = True
if len(rev_buckets) != whl_count:
return None
buckets.update(rev_buckets)
if saw_non_editable_files and not saw_whl_revision:
return None
return buckets
candidates = [*filenames, *(name for name in dirnames if (current / name).is_symlink())]
if candidates:
yield (sum(name.endswith(".whl") for name in filenames),
[_parse_archive_pointer(current / name, payload_cache, root) for name in candidates])
def _plan_sdist_seed(payload_cache: Path) -> tuple[list[str], list[Path]] | None:
@@ -557,7 +574,7 @@ def _plan_sdist_seed(payload_cache: Path) -> tuple[list[str], list[Path]] | None
if name in _SEED_MARKERS:
continue
if name.startswith("sdists-v") and entry.is_dir() and not entry.is_symlink():
found = _collect_sdist_dir_buckets(entry, payload_cache, root)
found = _sdist_tree_buckets(_sdist_dir_revisions(entry, payload_cache, root))
if found is None:
return None
buckets.update(found)
@@ -621,56 +638,34 @@ def _extract_seed_member(archive, info, dst: Path) -> Path:
return dst
def _parse_archive_pointer_bytes(archive, info, name: str, present_buckets: set[str]) -> str | None:
"""Validate an ``archive-v0/<bucket>`` pointer member inside ``uv-cache.hpkg``."""
if Path(name).suffix.lower() in _SDIST_NON_POINTER_SUFFIXES:
return None
if info.file_size <= 0 or info.file_size > 256:
return None
try:
text = archive.read(info).decode("utf-8-sig").strip()
except (OSError, UnicodeDecodeError):
return None
if not text.startswith("archive-v0/"):
return None
bucket = text[len("archive-v0/"):]
if not bucket or "/" in bucket or "\\" in bucket or bucket in (".", ".."):
raise _UnresolvedPointerError(info.filename)
if bucket not in present_buckets:
raise _UnresolvedPointerError(info.filename)
return bucket
def _archive_sdist_revisions(archive, revisions: dict[tuple[str, ...], list],
present_buckets: set[str]) -> Iterator[tuple[int, list[str | None]]]:
"""Each revision directory of one archived ``sdists-v*`` tree (``(name, ZipInfo)`` entries),
for ``_sdist_tree_buckets``."""
for entries in revisions.values():
yield (sum(name.endswith(".whl") for name, _ in entries),
[_pointer_text_bucket(name, info.file_size, partial(archive.read, info), present_buckets.__contains__)
for name, info in entries])
def _plan_sdist_archive_seed(archive, members: list[tuple[tuple[str, ...], object]]) -> tuple[list[tuple[tuple[str, ...], object]], list[tuple[tuple[str, ...], object]]] | None:
"""Plan selective ``scope="sdists"`` extraction directly from ``uv-cache.hpkg``."""
"""Plan selective ``scope="sdists"`` extraction directly from ``uv-cache.hpkg``.
The rules are ``_plan_sdist_seed``'s: each ``sdists-v*`` tree is judged on its own by
``_sdist_tree_buckets``, and every pointer by ``_pointer_text_bucket``.
"""
present_buckets = {parts[1] for parts, _ in members if len(parts) >= 3 and parts[0] == "archive-v0"}
sdist_dirs: dict[tuple[str, ...], list[tuple[tuple[str, ...], object]]] = {}
trees: dict[str, dict[tuple[str, ...], list[tuple[str, object]]]] = {}
for parts, info in members:
if len(parts) >= 3 and parts[0].startswith("sdists-v") and parts[1] != "editable":
sdist_dirs.setdefault(parts[:-1], []).append((parts, info))
trees.setdefault(parts[0], {}).setdefault(parts[:-1], []).append((parts[-1], info))
referenced_buckets: set[str] = set()
saw_non_editable_files = False
saw_whl_revision = False
for dir_parts in sorted(sdist_dirs):
entries = sdist_dirs[dir_parts]
saw_non_editable_files = True
whl_count = sum(1 for parts, _ in entries if parts[-1].endswith(".whl"))
rev_buckets: set[str] = set()
for parts, info in entries:
try:
bucket = _parse_archive_pointer_bytes(archive, info, parts[-1], present_buckets)
except _UnresolvedPointerError:
return None
if bucket is not None:
rev_buckets.add(bucket)
if whl_count:
saw_whl_revision = True
if len(rev_buckets) != whl_count:
return None
referenced_buckets.update(rev_buckets)
if saw_non_editable_files and not saw_whl_revision:
return None
for revisions in trees.values():
found = _sdist_tree_buckets(_archive_sdist_revisions(archive, revisions, present_buckets))
if found is None:
return None
referenced_buckets |= found
bucket_members: list[tuple[tuple[str, ...], object]] = []
other_members: list[tuple[tuple[str, ...], object]] = []

View File

@@ -12,6 +12,7 @@ from __future__ import annotations
import io
import os
import shutil
import subprocess
import sys
from pathlib import Path
@@ -94,6 +95,18 @@ def _make_payload_cache(tmp_path: Path, monkeypatch, *, symlink_sdist: bool = Fa
return uv_cache, machine
def _ship(uv_cache: Path, layout: str) -> None:
"""Ship the staged tree as the bundle would: loose on POSIX, packed into ``uv-cache.hpkg`` on Windows."""
if layout == "hpkg":
from scripts.bundles.native import pack_uv_cache_archive
pack_uv_cache_archive(uv_cache, uv_cache.parent / packages.UV_CACHE_ARCHIVE_NAME)
shutil.rmtree(uv_cache)
LAYOUTS = pytest.mark.parametrize("layout", ["dir", "hpkg"])
@pytest.mark.parametrize(
("target", "offline", "explicit_cache", "expected"),
[
@@ -112,8 +125,10 @@ def test_selective_seed_target_gate(target, offline, explicit_cache, expected):
) is expected
def test_sdist_scope_seeds_only_sdists_and_promotes_monotonically(tmp_path, monkeypatch):
_, machine = _make_payload_cache(tmp_path, monkeypatch)
@LAYOUTS
def test_sdist_scope_seeds_only_sdists_and_promotes_monotonically(tmp_path, monkeypatch, layout):
uv_cache, machine = _make_payload_cache(tmp_path, monkeypatch)
_ship(uv_cache, layout)
packages.uv_cache_dir(scope="sdists")
@@ -180,11 +195,13 @@ def test_sdist_scope_publishes_archives_before_sdist_pointers_and_retries(tmp_pa
assert (machine / ".seeded-sdists").is_file()
def test_sdist_scope_falls_back_to_full_merge_when_a_built_wheel_has_no_pointer(tmp_path, monkeypatch):
@LAYOUTS
def test_sdist_scope_falls_back_to_full_merge_when_a_built_wheel_has_no_pointer(tmp_path, monkeypatch, layout):
"""Without its pointer, nothing says which ``archive-v0`` bucket the built wheel unpacked to."""
uv_cache, machine = _make_payload_cache(tmp_path, monkeypatch)
pointer = uv_cache / "sdists-v10" / "pypi" / "pilk" / "0.2.4" / "VeTTI3yY6UPI1P1w" / "pilk-0.2.4-cp314-cp314-win_amd64"
pointer.unlink()
_ship(uv_cache, layout)
packages.uv_cache_dir(scope="sdists")
@@ -193,20 +210,28 @@ def test_sdist_scope_falls_back_to_full_merge_when_a_built_wheel_has_no_pointer(
assert (machine / "archive-v0" / "wheelBucket00001" / "httpx" / "__init__.py").is_file()
@pytest.mark.parametrize("stale", [
"archive-v0/missingBucket001",
"archive-v0/../escape",
pytest.param("symlink", marks=pytest.mark.platforms("posix")),
@pytest.mark.parametrize(("layout", "stale"), [
("dir", "archive-v0/missingBucket001"),
("hpkg", "archive-v0/missingBucket001"),
("dir", "archive-v0/../escape"),
("hpkg", "archive-v0/../escape"),
# A bucket the payload holds: one wheel still cannot name two buckets.
("dir", "archive-v0/wheelBucket00001"),
("hpkg", "archive-v0/wheelBucket00001"),
# An archive holds no links: the packer refuses them.
pytest.param("dir", "symlink", marks=pytest.mark.platforms("posix")),
])
def test_sdist_scope_falls_back_to_full_merge_on_a_stale_pointer_beside_a_built_wheel(tmp_path, monkeypatch, stale):
"""The revision's one ``.whl`` still pairs with its valid pointer, so only the pointer check
stands between the selective seed and publishing a pointer to a bucket the payload lacks."""
def test_sdist_scope_falls_back_to_full_merge_on_a_stale_pointer_beside_a_built_wheel(tmp_path, monkeypatch, layout,
stale):
"""A leftover pointer beside the revision's one valid ``.whl`` pointer: the layout is not one
bucket per wheel, so the selective seed must not guess which bucket the wheel unpacked to."""
uv_cache, machine = _make_payload_cache(tmp_path, monkeypatch)
leftover = uv_cache / "sdists-v10" / "pypi" / "pilk" / "0.2.4" / "VeTTI3yY6UPI1P1w" / "pilk-0.2.3-cp314-cp314-win_amd64"
if stale == "symlink":
os.symlink("../../../../../archive-v0/missingBucket001", leftover)
else:
leftover.write_text(stale, encoding="utf-8")
_ship(uv_cache, layout)
packages.uv_cache_dir(scope="sdists")
@@ -215,10 +240,47 @@ def test_sdist_scope_falls_back_to_full_merge_on_a_stale_pointer_beside_a_built_
assert (machine / "archive-v0" / "wheelBucket00001" / "httpx" / "__init__.py").is_file()
def test_sdist_scope_falls_back_to_full_merge_when_sdist_layout_has_no_wheel_revision(tmp_path, monkeypatch):
@pytest.mark.parametrize("bad", ["archive-v0/missingBucket001", "archive-v0/sdistBucket00001/pilk"])
@LAYOUTS
def test_sdist_scope_falls_back_to_full_merge_when_a_built_wheels_only_pointer_is_unresolved(tmp_path, monkeypatch,
layout, bad):
"""One wheel, one pointer, so the pairing holds: only the pointer's own check stops the seed
from publishing a pointer to a bucket the payload lacks (or to a path inside one)."""
uv_cache, machine = _make_payload_cache(tmp_path, monkeypatch)
pointer = uv_cache / "sdists-v10" / "pypi" / "pilk" / "0.2.4" / "VeTTI3yY6UPI1P1w" / "pilk-0.2.4-cp314-cp314-win_amd64"
pointer.write_text(bad, encoding="utf-8")
_ship(uv_cache, layout)
packages.uv_cache_dir(scope="sdists")
assert (machine / ".seeded").is_file()
assert not (machine / ".seeded-sdists").exists()
assert (machine / "archive-v0" / "wheelBucket00001" / "httpx" / "__init__.py").is_file()
@LAYOUTS
def test_sdist_scope_falls_back_to_full_merge_when_sdist_layout_has_no_wheel_revision(tmp_path, monkeypatch, layout):
uv_cache, machine = _make_payload_cache(tmp_path, monkeypatch)
whl = uv_cache / "sdists-v10" / "pypi" / "pilk" / "0.2.4" / "VeTTI3yY6UPI1P1w" / "pilk-0.2.4-cp314-cp314-win_amd64.whl"
whl.unlink()
_ship(uv_cache, layout)
packages.uv_cache_dir(scope="sdists")
assert (machine / ".seeded").is_file()
assert not (machine / ".seeded-sdists").exists()
assert (machine / "archive-v0" / "wheelBucket00001" / "httpx" / "__init__.py").is_file()
@LAYOUTS
def test_sdist_scope_judges_each_sdists_tree_on_its_own(tmp_path, monkeypatch, layout):
"""A second ``sdists-v*`` tree (another uv's layout) without a wheel revision is unrecognized,
even when ``sdists-v10`` beside it has one: both formats fall back to the full merge."""
uv_cache, machine = _make_payload_cache(tmp_path, monkeypatch)
older = uv_cache / "sdists-v9" / "pypi" / "pilk" / "0.2.3" / "rev0"
older.mkdir(parents=True)
(older / "metadata.msgpack").write_bytes(b"meta")
_ship(uv_cache, layout)
packages.uv_cache_dir(scope="sdists")