Skip to content

Retain hashes of filtered wheels for isolated builds - #23337

Draft
charliermarsh wants to merge 1 commit into
mainfrom
charlie/preserve-build-hashes
Draft

charliermarsh wants to merge 1 commit into
mainfrom
charlie/preserve-build-hashes

Conversation

@charliermarsh

@charliermarsh charliermarsh commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

Summary

On macOS, uv sync --frozen can reject a wheel from PyPI immediately after uv lock. Consider a project that needs cffi at runtime on Android and at build time on every platform.

[project]
name = "example"
version = "0.1.0"
requires-python = "==3.12.*"
dependencies = ["cffi==2.0.0; sys_platform == 'android'"]

[build-system]
requires = ["setuptools", "cffi==2.0.0"]
build-backend = "setuptools.build_meta"
touch example.py
uv lock
uv sync --frozen --no-build-package cffi
# Hash mismatch for `cffi==2.0.0`

The runtime marker filters out the macOS wheel, leaving only the source distribution in the cffi entry. The isolated build needs the macOS wheel because we disabled building cffi from source. uv checks the wheel against the source distribution’s hash and rejects it. On an index that hashes only some files, filtering can also discard the last hash for a version. A later build can then install a replacement wheel without checking it against the lockfile. Both cases already occur with platform markers and can also arise with interpreter filtering in #23310.

This draft saves the selected index’s digests for otherwise eligible wheels excluded by the runtime marker in an optional build-hashes list. Frozen builds and metadata builds during uv lock --check can verify those wheels. During an unlocked re-resolution such as uv lock --refresh, metadata builds use the current explicit build constraints. They can therefore run a wheel that the resulting frozen build would reject. When re-locking a version from the same index, we keep additional digests only for eligible files whose hashes were already in the lock. Tightening --exclude-newer drops later files. If the release would lose its last trusted digest, or a filtered digest disappears while a new digest appears, uv asks for an explicit --upgrade-package. Since the list omits filenames, simultaneously adding and removing unrelated files can also require an upgrade. When multiple indexes supply the same locked name and version, the build verifier accepts an additional digest only if all those sources recorded it.

On an index that hashes only the Linux wheel, a macOS-only lock now retains the Linux digest for builds. A subsequent macOS build rejects the hashless wheel because its contents don’t match any locked digest. We also check for conflicts with explicit build constraints before writing the lockfile. Runtime installs and exports use the runtime artifacts’ hashes. If filtering removes a requirement’s last runtime hash, uv export emits --require-hashes to prevent pip from installing an unverified replacement. The directive applies to the whole file. For example, a FreeBSD-only dependency can trigger it and cause pip on macOS to reject an unrelated dependency that lacks a hash. uv export --no-hashes opts out.

Across the 22 ecosystem fixtures, 9 lockfiles grow, adding 30,833 bytes in total (+0.27%). The cost is higher for projects that deliberately filter out many wheels. For the three-platform NumPy project in #23270, this change alone adds 37 hashes and takes the lockfile from 12,050 to 14,992 bytes (+24.4%). #23310 alone drops four PyPy wheels and produces a 10,761-byte lockfile. With both changes, the lockfile contains 30 wheels and 41 additional hashes (14,019 bytes, +16.3% over main). An unrestricted NumPy lock adds zero bytes.

Comment thread crates/uv-lock/src/lock/mod.rs Resolved
Comment thread crates/uv-lock/src/lock/mod.rs Resolved
Comment thread crates/uv-lock/src/lock/mod.rs Resolved
Comment thread crates/uv-lock-operations/src/lock.rs Resolved
Comment on lines +2572 to +2575
if !wheel_marker.is_true() {
package.build_hashes =
package.additional_build_hashes(dist, index_locations, &requires_python);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Collect build hashes where registry wheels are filtered

Package::from_annotated_dist already has the index, Python requirement, and wheel marker, but returns a package with empty build hashes. Its caller must then revisit the original distribution, repeat the registry/index selection from Wheel::from_annotated_dist, and infer which files were omitted. That leaves two places to update when wheel eligibility changes. Have the wheel-selection pass return the runtime wheels and additional digests together, and initialize both fields in the package constructor.

Comment thread crates/uv-lock-operations/src/lock.rs Resolved
Comment on lines +326 to +328
if !package.build_hashes.is_empty() {
writer.key_multiline_array("build-hashes", &package.build_hashes, |writer, hash| {
writer.value(hash.to_string())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Record the new package field in the lockfile revision

The writer emits build-hashes while still declaring revision 5. That makes an older lock that never collected filtered digests indistinguishable from a newly generated lock that found none. docs/concepts/resolution.md specifically lists adding a distribution field as a use for revision. Bump and document the writer revision while continuing to read revision 5; this need not force existing locks to re-resolve.

@charliermarsh
charliermarsh force-pushed the charlie/preserve-build-hashes branch 2 times, most recently from 0de3cfc to 09eb239 Compare November 21, 2026 02:01
Comment thread crates/uv-lock/src/lock/mod.rs Resolved
Comment on lines 694 to +696
let resolution_build_hasher = match mode {
LockMode::Locked(..) => locked_hasher.with_constraint_hashes(&build_hasher)?,
LockMode::Write(_) | LockMode::DryRun(_) | LockMode::Frozen(_) => build_hasher,
LockMode::Locked(..) => build_artifacts.with_constraint_hashes(&build_hasher)?,
LockMode::Write(_) | LockMode::DryRun(_) | LockMode::Frozen(_) => build_hasher.clone(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Enforce retained build hashes during non-upgrade resolution

uv lock --refresh forces a fresh resolution without upgrading packages. If an sdist needs an isolated build to obtain metadata, this branch gives that build only the explicit constraints. It can use a wheel that uv sync --frozen would reject, then write the original build digest back to the lock. The constraints-only branch existed at the merge base; the new inconsistency is that the same command retains a build digest on disk without enforcing it during resolution. Combine the current constraints with the locked build policy for packages not selected for upgrade.

Comment thread crates/uv-lock/src/lock/mod.rs Resolved
Comment thread crates/uv-lock/src/lock/mod.rs Resolved
Comment on lines +74 to +75
{
writeln!(f, "--require-hashes")?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Do not change the whole export's hash policy for an inactive requirement

--require-hashes applies to the whole file, not to the marker on the affected package. In an offline pip dry-run on Linux, a file with a macOS-only demo pin and an unrelated hashless ok pin installed ok without the directive; with it, pip skipped demo but rejected ok. The merge base already exported a bare pin when no runtime hashes remained. The isolated-build fix can land without changing exports; handle that existing limitation separately, or report the unrepresentable package at export time instead of changing unrelated requirements.

Comment thread crates/uv-tool-commands/src/common.rs Outdated
Vec::new(),
index_locations,
false,
None,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Avoid collecting build hashes for tool locks that never consult them

None here means “collect fresh digests,” not “skip build hashes.” A universal tool lock with a platform-marked dependency therefore writes build-hashes, but both ToolLock::validate and the tool installation path through sync_environment construct their build policies from explicit constraints alone. Tools already used only constraints at the merge base; this PR adds serialized digests with no consumer. Either use the lock's build strategy on reuse or leave collection out of tool locks until that support lands.

Comment thread crates/uv-lock-operations/src/lock.rs Resolved
Comment on lines +838 to 839
let lock = existing_lock.expect("validated an existing lock");
Ok((LockResult::Unchanged(lock), None))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Keep the owned lock paired with its validation outcome

Matching Satisfies(lock) already identifies the lock, but the caller must recover ownership from a second Option with expect. The fallback likewise needs a valid boolean to decide whether to report that same lock as previous. Have validation return a status and mismatch reason, and pair that outcome with the owned lock at the call site. Then the success arm can return the lock directly, while the error arm can still retain its hashes for re-resolution.

Comment thread crates/uv/tests/lock/lock.rs Resolved
@charliermarsh
charliermarsh force-pushed the charlie/preserve-build-hashes branch from 09eb239 to 49de926 Compare November 21, 2026 02:17
Comment on lines +3102 to +3104
package
.build_hashes
.retain(|digest| trusted.contains(digest));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Prevent a refresh from widening the build allowlist through runtime hashes

Consider an unchanged release with a hashless runtime wheel and one filtered wheel with digest B. If the index starts advertising digest R for the runtime wheel, uv lock --refresh sees B in both sets, so neither rejection condition fires. This retain only filters build_hashes; the next frozen build accepts R through artifact_hashes(), although the previous build policy accepted only B. The marker and filenames need not change. The merge base also refreshed runtime hashes, but it had no build-only allowlist to widen in this case. When a release was verified solely by build hashes, require an explicit package upgrade before admitting a runtime digest outside that set.

Comment on lines +678 to +680
let locked_build_hasher = build_artifacts
.clone()
.with_constraint_hashes(&build_hasher)?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Let an explicit upgrade recover from a host-specific constraint conflict

A lock written on Linux can contain a Windows-only build constraint that was inactive during the pre-write check. If its digest conflicts with the release’s only build-hashes entry, uv lock --upgrade on Windows fails here even after the constraint is removed from pyproject.toml: this intersects the old lock’s constraints before ValidatedLock::validate can take its no-metadata upgrade path. The eager intersection exists on the merge base, but a release with no runtime hashes contributed no conflicting digest there. Defer this validation-only intersection until validation actually needs metadata; keep applying the current constraints during fresh resolution.

Comment on lines +1026 to +1028
if let Some(previous) = existing_lock.as_ref() {
lock.retain_trusted_build_hashes(previous, hash_upgrade)?;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Make previous-lock reconciliation part of relock construction

Lock::from_resolution returns a serializable lock containing live index digests. On a relock, that value is not ready to write until the caller remembers this second, fallible mutation. Both the previous lock and the upgrade selection are available before construction, and the intervening pruning only changes manifest settings. Make fresh construction versus relocking explicit at the constructor boundary and reconcile the digests before returning the relocked Lock. That keeps fresh tool locks possible without making trust preservation a call-order requirement.

group_requires_python: self.group_requires_python,
sdist: self.sdist,
wheels: self.wheels,
build_hashes: self.build_hashes,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Reject build hashes on non-registry lock entries

The writer collects these digests only for registry packages, but the reader accepts them on any source. For example, an editable package with build-hashes passes lock parsing, is ignored by common_build_hashes, and can nevertheless make uv export emit --require-hashes alongside -e .. The same field thus changes the export while providing no build verification. Reject a nonempty set on non-registry sources during lock construction, alongside the existing source/hash consistency checks.

Comment on lines +2243 to +2247
lock()
.args(["--exclude-newer", "2023-01-01"])
.assert()
.success();
assert!(!context.read("uv.lock").contains(&replacement));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Isolate the upload-cutoff test from the wheel replacement

The cutoff assertion checks that replacement disappeared, but the preceding marker-widening scenario already published changed in its place. The digest being checked is therefore absent from the index independently of the cutoff. Give the cutoff its own named scenario: keep the index unchanged after locking, tighten only --exclude-newer, and snapshot the lockfile diff showing that the still-advertised later wheel loses its digest.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant