Skip to content

Add locked tool installs from source projects - #405

Draft
zaniebot wants to merge 14 commits into
mainfrom
zb/locked-tool-uv-dev
Draft

zaniebot wants to merge 14 commits into
mainfrom
zb/locked-tool-uv-dev

Conversation

@zaniebot

@zaniebot zaniebot commented Jul 24, 2026 •

Copy link
Copy Markdown
Collaborator

Installing a tool from a source project currently ignores the project’s uv.lock, allowing its dependencies to resolve independently of the project. Add uv tool install --locked to validate and reuse source-project lockfiles through the existing universal tool-lock machinery, including workspace members, Git checkouts, extras, and correctly relocated local sources.

Part of astral-sh#5815.

@astral-automations-bot
astral-automations-bot Bot force-pushed the zb/locked-tool-uv-dev branch 2 times, most recently from b06be0e to 0ee015b Compare August 14, 2026 11:48
@zaniebot zaniebot added priority:3 Normal: useful features, documentation, usability, or routine efficiency improvements. size:4 Complex: architectural or security-sensitive work requiring broad or cross-repository context. enhancement New feature or request preview Experimental behavior risk:3 Credible risk of meaningful incorrect behavior or regression; bounded or recoverable. labels Sep 9, 2026
@codspeed

codspeed Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

⚠️ 8 benchmarks spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 69 untouched benchmarks
⏩ 35 skipped benchmarks1


Comparing zb/locked-tool-uv-dev (268b640) with main (64e2ac8)

Open in CodSpeed

Footnotes

  1. 35 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@zaniebot zaniebot added priority:2 Important: bounded correctness, release reliability, committed work, or proven performance gains. and removed priority:3 Normal: useful features, documentation, usability, or routine efficiency improvements. labels Sep 23, 2026
@astral-automations-bot
astral-automations-bot Bot force-pushed the zb/locked-tool-uv-dev branch 2 times, most recently from b9b6101 to 4fc4539 Compare October 6, 2026 01:11
Comment thread crates/uv-settings/src/lib.rs Outdated
Comment on lines +87 to +96
pub fn for_project(&self, project_root: &Path) -> Result<ResolverInstallerOptions, Error> {
let project = FilesystemOptions::find(project_root)?
.map(FilesystemOptions::into_options)
.map(|options| ResolverInstallerOptions::from(options.top_level))
.unwrap_or_default();
Ok(self
.cli_environment
.clone()
.combine(project)
.combine(self.filesystem.clone()))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[P2] Preserve configuration discovery and explicit-file precedence

for_project unconditionally discovers configuration and places it ahead of filesystem, but that layer can contain an explicit --config-file, not just user/system settings. Consequently, tool install --locked --no-config still reads project configuration, and project settings override an explicitly selected configuration file. A lock created with uv lock --config-file custom.toml can therefore fail validation when installed with the same configuration. Carry the discovery policy and explicit-file distinction into this wrapper, and bypass project configuration discovery when either requires it.

Comment on lines +546 to +550
let source_tool_lock = source_project_lock
.map(|(project, lock)| {
ToolLock::from_project_lock(
&tool_dir,
&project,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[P2] Carry resolved project build requirements into installation

The workspace is discarded here while the imported settings still contain unlowered extra-build-dependencies. Lock validation resolves those dependencies with LoweredExtraBuildDependencies::from_workspace, but the subsequent planner and sync_environment use from_non_lowered. For a project mapping an extra build dependency to a local wheel or explicit index through tool.uv.sources, installation consequently resolves a registry requirement instead, potentially failing offline or selecting the wrong distribution. Resolve these requirements while the workspace is available and pass the resulting ExtraBuildRequires through planning and installation.

Comment on lines +5993 to +5996
assert_snapshot!(context.read("tools/foo/uv.lock"), @r#"
version = 1
revision = 3
requires-python = ">=3.12"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[P2] Refresh the new snapshots for the current lockfile revision

This snapshot and the one in tool_install_locked_workspace_member expect revision 3, but both fixtures generate their lockfiles with the current binary. Lock::from_resolution writes REVISION = 5, and into_absolute_paths retains that revision, so these assertions cannot match the generated tool locks. Run the two focused tests and update their snapshots to the current output.

Comment on lines +5969 to +5973
context
.lock()
.current_dir(project.path())
.assert()
.success();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[P3] Test reuse of a version that fresh resolution would replace

The fixture locks iniconfig<2 with the same settings used during installation, so fresh resolution also selects the asserted 1.1.1. The version assertion therefore does not establish the feature's central guarantee that installation honors the source lock's selection. Generate this lock with an older compatible version, for example using --upgrade-package iniconfig==1.0.0, then assert that the locked install retains it despite a newer compatible version being available.

Comment on lines +349 to +353
let target = InstallTarget::Project {
workspace: project.workspace(),
name: &requirement.name,
lock: &lock,
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[P2] Validate the source project's name before accepting its lock

For uv tool install 'foo @ file:///path/to/bar' --locked, if project bar depends on an executable-bearing foo or shares a workspace with it, this path can install that other package. resolve_names passes named requirements through unchanged, lock validation checks the workspace, and the later projection selects foo by name without checking its requested source. The receipt then incorrectly records bar as its source. Require project.project_name() to match requirement.name before accepting the lock, rejecting non-project targets too.

Comment thread crates/uv-tool-commands/src/install.rs Outdated
Comment on lines +394 to +398
Err(ToolLockError::Lock(err @ LockError::LockMismatch(..))) => {
writeln!(printer.stderr(), "{}", err.to_string().bold())?;
return Ok(ExitStatus::Failure);
}
Err(err) => return Err(err.into()),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[P3] Reuse the shared lock-error reporting path

This duplicates behavior already owned by From<LockError> for UvError. Manually printing LockMismatch drops its actionable uv lock hint, while returning other lock errors directly bypasses their classification: a missing lockfile exits 2 here instead of the expected-failure status 1 used by uv lock and uv sync. Handle ToolLockError::Lock(err) through UvError::from(err) so classification, formatting, and hints stay consistent without command-specific maintenance.

@zaniebot
zaniebot deployed to automations October 9, 2026 02:57 — with GitHub Actions Active
@zaniebot
zaniebot deployed to automations October 10, 2026 00:37 — with GitHub Actions Active
Comment thread crates/uv-tool-commands/src/install.rs Outdated
Comment on lines +212 to +216
let (options, settings) = if let Some((project, _, _)) = source_project.as_ref() {
let options = tool_options.for_project(project.workspace().install_path())?;
let mut project_settings = ResolverInstallerSettings::from(options.clone());
project_settings.resolver.torch_backend = settings.resolver.torch_backend;
(options, project_settings)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[P2] Retain Git provenance for imported index paths

For a Git project with find-links = ["./wheels"], for_project resolves that path inside the checkout, and the resulting options are persisted unchanged in the receipt. After installation with --locked --no-cache, that directory disappears. A subsequent upgrade restores the deleted path and calls FlatIndex::load before fetching the source, so it fails even when the repository remains available. Retain Git-relative provenance for imported index/find-links paths and rematerialize them before upgrade resolution.

Comment thread crates/uv-settings/src/lib.rs Outdated
Comment on lines +103 to +107
pub fn for_project(&self, project_root: &Path) -> Result<ResolverInstallerOptions, Error> {
let project = if self.discover_project {
FilesystemOptions::find(project_root)?
.map(FilesystemOptions::into_options)
.map(|options| ResolverInstallerOptions::from(options.top_level))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[P2] Bound Git configuration discovery to the checkout

FilesystemOptions::find searches all ancestors and skips pyprojects without [tool.uv]. For a Git source without uv configuration, a cache located beneath an unrelated uv.toml therefore imports that file as project configuration. For example, an ancestor's resolution = "lowest" can make a valid source lock fail validation. Workspace discovery already receives a Git boundary, but settings discovery loses it here. Carry the checkout boundary into this lookup while retaining ordinary ancestor discovery for local sources.

Comment thread crates/uv-tool-commands/src/common.rs Outdated
Comment on lines +730 to +734
let environments = self.lock.supported_environments();
if !environments.is_empty()
&& !environments
.iter()
.any(|environment| environment.evaluate(&markers, &[]))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[P3] Share lock-environment compatibility checks

The new Python-range and supported-environment checks duplicate those in sync_from_lock, including diagnostic formatting. Both paths enforce the same lock/environment compatibility rules, so future changes now require coordinated edits across project and tool workflows. Extract shared compatibility helpers in uv-environment-operations and use them from both paths, keeping validation at the point where the interpreter and markers are available.

@zaniebot
zaniebot deployed to automations October 10, 2026 01:06 — with GitHub Actions Active
@zaniebot
zaniebot deployed to automations October 10, 2026 01:10 — with GitHub Actions Active
Comment on lines +88 to +89
replace_index_urls(&mut options.indexes, &replacements);
Ok(restored)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[P2] Rebase index bindings in stored requirements too

For a Git project with an extra build dependency mapped through tool.uv.sources to a repository-local index, lowering stores the checkout URL in RequirementSource::Registry.index. This restoration updates only tool options; upgrade_tool subsequently restores the saved build requirement unchanged. After installation with --locked --no-cache, upgrading with --reinstall --no-cache therefore queries the deleted index, despite successfully fetching its replacement. Apply the replacement map to stored requirements’ index bindings before resolution and receipt persistence.

Comment thread crates/uv-tool/src/tool.rs Outdated
Comment on lines +160 to +168
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolIndexSource {
index: IndexUrl,
source: RequirementSource,
}

impl ToolIndexSource {
pub fn new(index: IndexUrl, source: RequirementSource) -> Self {
Self { index, source }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[P3] Enforce Git-directory provenance at construction

ToolIndexSource::new and derived deserialization accept every RequirementSource variant, while restore_index_sources requires GitDirectory and rejects other variants during upgrade. This invariant is already knowable at construction, and the source cannot subsequently be mutated. Use a Git-directory-specific representation, or validate both construction and deserialization, so callers cannot create receipts that only fail when consumed later.

@zaniebot
zaniebot deployed to automations October 10, 2026 01:27 — with GitHub Actions Active
@zaniebot
zaniebot deployed to automations October 10, 2026 01:35 — with GitHub Actions Active
Comment thread crates/uv-tool-commands/src/install.rs Outdated
Comment on lines +646 to +649
receipt_constraints.extend(
lock.constraints(project_root)
.requirements()
.cloned()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[P2] Persist declared constraints instead of the pruned lock manifest

With resolution-inputs enabled, Lock::prune_constraints intentionally removes version bounds satisfied by the locked packages, as covered by lock_resolution_inputs_version_constraints. A project constraint such as dep<2 can therefore be absent here even though it selected dep==1.0.0. The locked install succeeds, but its receipt loses the constraint, allowing a subsequent uv tool upgrade to install version 2. Lock validation does not restore omitted declarations, and ToolOptions does not retain them. Capture the workspace’s declared, lowered constraints for the receipt instead of treating the lossy lock manifest as the upgrade policy.

Comment on lines +479 to +483
"extra-build-requires",
value(serde::Serialize::serialize(
&self.extra_build_requires,
toml_edit::ser::ValueSerializer::new(),
)?),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[P2] Preserve index formats in persisted build requirements

When a source project maps an extra build dependency to a named format = "flat" index, this serialization loses the format: RequirementSourceWire stores only the index URL and reconstructs it as IndexFormat::Simple. upgrade_tool restores these requirements unchanged, and the registry client uses their explicit index metadata rather than the format retained in ToolOptions. Consequently, a successful locked install can fail on uv tool upgrade foo --reinstall --no-cache, querying a Simple API package path instead of the flat index. Preserve the format across serialization or restore it from the saved index options before resolving stored requirements.

This branch was successfully deployed

1 active (outdated) deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request preview Experimental behavior priority:2 Important: bounded correctness, release reliability, committed work, or proven performance gains. risk:3 Credible risk of meaningful incorrect behavior or regression; bounded or recoverable. size:4 Complex: architectural or security-sensitive work requiring broad or cross-repository context.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants