Skip to content

The agent that grows with you

perf(bundles): ship the full uv cache; offline per-install rebuilds resolve from shipped wheels

ethie4f3b8d713ea5
diff --git a/scripts/bundles/native.py b/scripts/bundles/native.py
index 1617217f6e3..55ca920b856 100644
--- a/scripts/bundles/native.py
+++ b/scripts/bundles/native.py
@@ -2,7 +2,6 @@
from __future__ import annotations
import os
-import re
import shutil
import subprocess
import sys
@@ -54,125 +53,29 @@ def _arch_guard(store_dir: Path) -> list[str]:
def stage_uv_cache(source: Path, destination: Path) -> None:
- """Keep offline wheel/index entries, without sdist build inputs.
+ """Ship everything a per-install venv rebuild resolves from offline.
- uv installs built wheels from extracted entries; their ZIPs and source
- trees (including Rust target/ outputs) are build-only. Scope exclusions
- to cache metadata boundaries so extracted package data stays intact.
+ sdist source trees (including Rust target/ outputs) are build-only bulk —
+ offline rebuilds install the built wheel entries, never recompile from
+ source — so they stay out. Built wheel ZIPs (including the copies uv keeps
+ beside sdist metadata.msgpack shards) ship: without them an offline
+ rebuild falls back to wanting the sdist download and fails closed.
"""
def ignore(directory: str, names: list[str]) -> set[str]:
path = Path(directory)
parts = path.relative_to(source).parts
if not parts or not parts[0].startswith("sdists-v"):
return set()
- omitted = set()
# Source trees live under a revision selected by a sibling pointer.
if "src" in names and (path / "src").is_dir() and any(
(path.parent / pointer).is_file() for pointer in ("revision.http", "revision.rev")
):
- omitted.add("src")
- # Build settings can put wheel entries in a shard below the revision.
- # The signer can reach extracted code, but not native code inside ZIPs.
- if "metadata.msgpack" in names:
- omitted.update(name for name in names if name.endswith(".whl") and (path / name).is_file())
- return omitted
+ return {"src"}
+ return set()
shutil.copytree(source, destination, ignore=ignore)
-def _cache_index_dirs(cache: Path, family: str) -> list[Path]:
- """Index roots under a cache family (wheels-v*/sdists-v*), whatever the
- index name: PyPI materializes as `pypi`, a custom --index-url as a hashed
- dir under `index`. Depth is fixed, the leaf dir name is not."""
- roots: list[Path] = []
- for family_dir in sorted(cache.glob(f"{family}-v*")):
- for index_dir in family_dir.iterdir():
- if index_dir.name in ("index",) or index_dir.name == "pypi":
- roots.extend(d for d in index_dir.iterdir() if d.is_dir())
- return roots
-
-
-def _lock_wheel_names(source_repo: Path) -> dict[str, set[str]]:
- """Map lock package name → wheel filenames uv downloads for it."""
- import tomllib
-
- lock = tomllib.loads((source_repo / "uv.lock").read_text(encoding="utf-8-sig"))
- packages: dict[str, set[str]] = {}
- for entry in lock.get("package", []):
- names = set()
- for wheel in entry.get("wheels") or []:
- url = wheel.get("url") if isinstance(wheel, dict) else wheel
- if url:
- names.add(url.rsplit("/", 1)[-1])
- packages[entry["name"]] = names
- return packages
-
-
-def prune_uv_cache_to_built(cache: Path, source_repo: Path) -> dict[str, list[str]]:
- """Slim a staged uv cache to the packages that had no downloadable wheel.
-
- A venv rebuild from the bundle may go online — PyPI re-serving released
- wheels is fine — but it must never invoke a compiler for the dependency
- graph's built-ins: packages whose wheels uv had to build on the build
- machine (no cp314/platform wheel on the index) would need a toolchain
- the user's machine may not have. Those packages' cache entries — sdist
- records, built wheel zips, and extracted archive buckets — are the
- infra-free guarantee; everything else is re-downloadable bytes.
-
- Returns the kept package names (for the build log).
- """
- lock_wheels = _lock_wheel_names(source_repo)
-
- built = {name for name, wheels in lock_wheels.items() if not wheels}
- sdist_dirs = _cache_index_dirs(cache, "sdists")
- wheels_dirs = _cache_index_dirs(cache, "wheels")
- # uv records every source distribution it fetched (and compiled).
- built |= {entry.name for directory in sdist_dirs for entry in directory.iterdir() if entry.is_dir()}
- for pkg_dir in (entry for directory in wheels_dirs for entry in directory.iterdir() if entry.is_dir()):
- # A cached wheel uv did not download from the index is one it
- # built itself (platform gap, e.g. no win cp314 wheel).
- if any(whl.name not in lock_wheels.get(pkg_dir.name, set())
- for whl in pkg_dir.rglob("*.whl")):
- built.add(pkg_dir.name)
- built.discard("hermes-agent") # installed from the payload's own tree
-
- keep_sdist = built & {e.name for directory in sdist_dirs for e in directory.iterdir()}
- keep_wheels = built & {e.name for directory in wheels_dirs for e in directory.iterdir()}
-
- # archive-v0 buckets are content-addressed: keep the ones holding any
- # built package (matched by its .dist-info directory).
- keep_buckets: set[str] = set()
- archive_root = cache / "archive-v0"
- if archive_root.is_dir():
- dist_info = re.compile(r"([a-zA-Z0-9_.]+?)-\d[^-]*\.dist-info")
- for bucket in archive_root.iterdir():
- if not bucket.is_dir():
- continue
- for dirpath, dirnames, _filenames in os.walk(bucket):
- if Path(dirpath).relative_to(bucket).parts.__len__() > 3:
- dirnames[:] = []
- continue
- for name in list(dirnames):
- match = dist_info.match(name)
- if match:
- if match.group(1).lower().replace("_", "-") in built:
- keep_buckets.add(bucket.name)
- dirnames.remove(name)
-
- for directory, keep in (
- *[(d, keep_sdist) for d in sdist_dirs],
- *[(d, keep_wheels) for d in wheels_dirs],
- ):
- for entry in directory.iterdir():
- if entry.name not in keep and entry.is_dir():
- shutil.rmtree(entry, ignore_errors=True)
- if archive_root.is_dir():
- for bucket in archive_root.iterdir():
- if bucket.name not in keep_buckets and bucket.is_dir():
- shutil.rmtree(bucket, ignore_errors=True)
- return {"sdists": sorted(keep_sdist), "wheels": sorted(keep_wheels), "buckets": sorted(keep_buckets)}
-
-
def stage_pm_runtime(root: Path, python: Path, repo: Path, *, offline: bool = False,
cache: Path | None = None) -> None:
"""Publish the same PM dependency graph as source installs, ready offline."""
@@ -327,11 +230,10 @@ def _prepare_native(*, out: Path, ref: str, source: Path, cache: Path,
write_features(features, out)
print(f"✓ enabled-features.json ({len(features)} extras recorded)")
- # Ship a slim uv cache: the venv sync on the build machine warms the
- # hermes-owned cache with every wheel this payload needs. A mutable-venv
- # rebuild from the bundle re-downloads released wheels online (seconds)
- # and reuses the shipped built-wheels for the packages that had none —
- # no compiler, no Xcode CLT, no Rust toolchain on the user machine.
+ # Ship the full uv cache (build-only sdist sources and wheel ZIPs are
+ # already excluded by stage_uv_cache). Any per-install venv rebuild —
+ # plugin extras, feature changes — resolves entirely from the shipped
+ # wheels with zero network access, on every profile of this install.
payload_cache = out / "uv-cache"
if payload_cache.exists():
shutil.rmtree(payload_cache, ignore_errors=True)
@@ -339,14 +241,7 @@ def _prepare_native(*, out: Path, ref: str, source: Path, cache: Path,
if src_cache.is_dir():
print(f" uv-cache: copying {src_cache} → payload...", flush=True)
stage_uv_cache(src_cache, payload_cache)
- # Ship only what a rebuild cannot re-acquire online: the wheels uv
- # built itself for packages with no downloadable wheel. Rebuilds go
- # online for released wheels (seconds) but must never need a
- # compiler; the full 2GB cache buys offline rebuilds the bundle
- # contract does not promise.
- kept = prune_uv_cache_to_built(payload_cache, repo_dir)
- print(f"✓ uv-cache (slim — built-only: {len(kept['sdists'])} sdist records, "
- f"{len(kept['wheels'])} built wheels, {len(kept['buckets'])} archive buckets)", flush=True)
+ print("✓ uv-cache (full — offline rebuilds resolve from shipped wheels)", flush=True)
else:
raise InstallError("uv-cache", "runtime dependency cache is missing")
diff --git a/tests/scripts/test_bundle_native.py b/tests/scripts/test_bundle_native.py
index c6536787fb6..d2d5dda6903 100644
--- a/tests/scripts/test_bundle_native.py
+++ b/tests/scripts/test_bundle_native.py
@@ -317,10 +317,10 @@ def test_staged_cache_skips_build_inputs_before_copying(tmp_path, monkeypatch, p
wheels = revision / shard
waste = {
revision / "src/target/release/build.exe": b"build output",
- wheels / "cache_proof-1.0-py3-none-any.whl": b"redundant ZIP",
}
kept = {
wheels / "metadata.msgpack": b"wheel metadata",
+ wheels / "cache_proof-1.0-py3-none-any.whl": b"built wheel ZIP ships for offline rebuilds",
revision.parent / pointer: b"revision pointer",
wheels / "cache_proof-1.0-py3-none-any/src/template.whl": b"package data",
Path("archive-v0/entry/cache_proof/src/__init__.py"): b"archive data",
@@ -345,18 +345,59 @@ def test_staged_cache_skips_build_inputs_before_copying(tmp_path, monkeypatch, p
assert all((cache / relative).read_bytes() == data for relative, data in {**waste, **kept}.items())
-def test_staged_cache_slim_ships_built_only_and_rebuilds_online_without_compiling(tmp_path):
+SELF_BUILD_BACKEND = '''import os, zipfile
+
+
+def build_wheel(wheel_directory, config_settings=None, metadata_directory=None):
+ name = "cache_proof-1.0.0-py3-none-any.whl"
+ path = os.path.join(wheel_directory, name)
+ with zipfile.ZipFile(path, "w") as zf:
+ zf.writestr("cache_proof/__init__.py", "VALUE = 'installed from cached wheel'\\n")
+ info = "cache_proof-1.0.0.dist-info/"
+ zf.writestr(info + "METADATA", "Metadata-Version: 2.1\\nName: cache-proof\\nVersion: 1.0.0\\n")
+ zf.writestr(
+ info + "WHEEL",
+ "Wheel-Version: 1.0\\nGenerator: selfbuild\\nRoot-Is-Purelib: true\\nTag: py3-none-any\\n",
+ )
+ zf.writestr(info + "RECORD", "")
+ return name
+
+
+def build_sdist(sdist_directory, config_settings=None):
+ raise NotImplementedError
+
+
+def get_requires_for_build_wheel(config_settings=None):
+ return []
+
+
+def get_requires_for_build_sdist(config_settings=None):
+ return []
+
+
+def prepare_metadata_for_build_wheel(metadata_directory, config_settings=None):
+ path = os.path.join(metadata_directory, "cache_proof-1.0.0.dist-info")
+ os.mkdir(path)
+ with open(os.path.join(path, "METADATA"), "w") as handle:
+ handle.write("Metadata-Version: 2.1\\nName: cache-proof\\nVersion: 1.0.0\\n")
+ return "cache_proof-1.0.0.dist-info"
+'''
+
+
+def test_staged_cache_ships_full_wheel_set_and_rebuilds_offline(tmp_path):
from tests.pm._fixtures import _wheel
uv = shutil.which("uv")
assert uv, "native bundle test requires uv"
package = tmp_path / "package"
package.mkdir()
+ # Self-contained PEP 517 backend (stdlib only, requires=[]): the offline
+ # rebuild below must not depend on build tools absent from the fixture.
(package / "pyproject.toml").write_text(
- '[project]\nname="cache-proof"\nversion="1.0.0"\n'
- '[build-system]\nrequires=["setuptools"]\nbuild-backend="setuptools.build_meta"\n',
+ '[build-system]\nrequires=[]\nbuild-backend="selfbuild"\nbackend-path=["."]\n',
encoding="utf-8",
)
+ (package / "selfbuild.py").write_text(SELF_BUILD_BACKEND, encoding="utf-8")
(package / "cache_proof.py").write_text("VALUE = 'installed from cached wheel'\n", encoding="utf-8")
dist = tmp_path / "dist"
dist.mkdir()
@@ -385,14 +426,15 @@ def test_staged_cache_slim_ships_built_only_and_rebuilds_online_without_compilin
thread.start()
index_url = f"http://127.0.0.1:{server.server_port}/simple"
try:
- subprocess.run(
+ warm = subprocess.run(
[uv, "pip", "install", "--python", sys.executable, "--target", str(tmp_path / "first"),
- "--no-build-isolation", "--no-deps", "--index-url", index_url,
+ "--no-deps", "--index-url", index_url,
"cache-proof==1.0.0", "wheel-proof==1.0"],
- env=env, cwd=tmp_path, capture_output=True, text=True, check=True, timeout=60,
+ env=env, cwd=tmp_path, capture_output=True, text=True, timeout=60,
)
+ assert warm.returncode == 0, warm.stderr + warm.stdout
locked = subprocess.run(
- [uv, "lock", "--python", sys.executable, "--index-url", index_url, "--no-build-isolation"],
+ [uv, "lock", "--python", sys.executable, "--index-url", index_url],
env=env, cwd=project, capture_output=True, text=True, timeout=60,
)
assert locked.returncode == 0, locked.stderr
@@ -408,26 +450,19 @@ def test_staged_cache_slim_ships_built_only_and_rebuilds_online_without_compilin
assert sources, "the actual uv build must leave its source tree in the cache"
shipped = tmp_path / "payload/uv-cache"
native.stage_uv_cache(cache, shipped)
- kept = native.prune_uv_cache_to_built(shipped, project)
- assert not list(shipped.rglob("*.whl")) or kept["wheels"], "built wheels survive the slim"
assert all(not (shipped / path.relative_to(cache)).exists() for path in sources)
assert all(path.exists() for path in [*built_zips, *sources]), "the build machine's cache must not change"
- # The slim ships only what was built: cache-proof (sdist-only) survives,
- # wheel-proof (a downloadable wheel) is dropped as re-downloadable.
- assert "cache-proof" in kept["sdists"]
- assert "wheel-proof" not in kept["sdists"] and "wheel-proof" not in kept["wheels"]
- assert not any(shipped.rglob("wheel_proof*")), "downloadable wheels leave the shipped cache"
-
- # A fresh mutable venv rebuilds ONLINE from the slim cache: the
- # sdist-only package installs from the shipped built content — no
- # compiler, no source tree — while the downloadable package comes
- # back from the index (--frozen installs the lock's baked URLs, so
- # the rebuild must reach the same origin the lock recorded).
+ # The full cache ships every wheel the build resolved, downloadable
+ # or built: a per-install venv rebuild must not depend on network
+ # reachability for any package the payload already shipped.
+ assert any(shipped.rglob("wheel_proof*")), "downloadable wheels ship in the full cache"
+
+ # A fresh mutable venv rebuilds OFFLINE from the shipped cache alone.
shutil.rmtree(cache, ignore_errors=True)
shutil.rmtree(tmp_path / "first", ignore_errors=True)
shutil.rmtree(project / ".venv", ignore_errors=True)
result = subprocess.run(
- [uv, "sync", "--python", sys.executable, "--frozen", "--index-url", index_url],
+ [uv, "sync", "--python", sys.executable, "--frozen", "--offline"],
env={**env, "UV_CACHE_DIR": str(shipped)}, cwd=project,
capture_output=True, text=True, timeout=60,
)