Repository navigation
Add workspace groups - #1832
Add workspace groups#1832zaniebot wants to merge 90 commits into
Conversation
Merging this PR will not alter performance
|
2c85b59 to
f16583e
Compare
f16583e to
b58e528
Compare
fa6c29c to
c102755
Compare
eda7311 to
c980e89
Compare
| let groups = workspace.workspace_groups_with_sources(&settings.sources)?; | ||
| if !groups.is_empty() { | ||
| return Box::pin(do_lock_workspace_groups( |
There was a problem hiding this comment.
[P2] Invalidate grouped locks when the last group is removed
When the workspace no longer declares groups, this falls through to ordinary lock validation without invalidating an existing grouped lock. For a non-project workspace with one group containing all members, unchanged Python bounds, and no dependencies, the existing validation checks still pass: neither ValidatedLock::validate nor Lock::satisfies compares workspace-group definitions. Consequently, uv lock --check accepts the removed group and uv lock retains format version 2 and its default selection. Explicitly invalidate the grouped graph on this transition and regenerate an ordinary lock, retaining usable version preferences.
| if local { | ||
| let marker = active.and(requirement.marker).and(source.marker()); | ||
| if !marker.is_false() { | ||
| pending.push((requirement.name.clone(), marker)); |
There was a problem hiding this comment.
[P2] Apply dependency exclusions before computing group reachability
This traversal follows raw production requirements without applying exclude-dependencies. For example, a group rooted at an app requiring Python >=3.13 is rejected if it depends on a local member requiring <3.13, even when that dependency is explicitly excluded. The excluded member still reaches the Python intersection before the resolver can apply DependencyModifiers. Compute reachability from effective requirements using the same exclusion and override policy as resolution, so removed edges cannot restrict the group's Python domain.
| for dependency in member.project().dependencies.iter().flatten() { | ||
| let requirement = | ||
| Requirement::<VerbatimParsedUrl>::from_str(dependency).map_err(|error| { |
There was a problem hiding this comment.
[P2] Use the existing lenient requirement parser
Adding a workspace group now changes which dependency declarations are accepted. The normal metadata paths (RequiresDist::from_pyproject_toml and ResolutionMetadata) use LenientRequirement, which accepts declarations such as leaf>=1.9.*; this prepass uses the strict parser and rejects them before resolution. It parses every production dependency, including remote dependencies and dependencies whose sources are disabled. Reuse LenientRequirement here so group discovery follows the established parsing policy.
| error @ (LockError::UnsupportedLockVersion(..) | ||
| | LockError::UnparsableLockVersion(..) | ||
| | LockError::LockSerialization(_) | ||
| | LockError::WorkspaceGroupResolution(..) | ||
| | LockError::MissingWorkspaceGroupResolution |
There was a problem hiding this comment.
[P2] Preserve error classification through group context
An unsatisfiable individual group is wrapped in WorkspaceGroupResolution, which this arm classifies as UvError::Unexpected. The same underlying NoSolution normally goes through LockError::Resolve and becomes a user failure. Merely declaring a group therefore changes the exit status from 1 to 2; the new workspace_groups_internal_conflict snapshot encodes that change. Delegate classification to the wrapped error while retaining the group context.
| exit_code: 2 (failure) | ||
| ----- stderr ----- | ||
| error: The lockfile at `uv.lock` uses an unsupported schema version (v2, but only v1 is supported). Downgrade to a compatible uv version, or remove the `uv.lock` prior to running `uv lock` or `uv sync`. | ||
| error: The lockfile at `uv.lock` uses an unsupported schema version (v3, but versions up to v2 are supported). Downgrade to a compatible uv version, or remove the `uv.lock` prior to running `uv lock` or `uv sync`. |
There was a problem hiding this comment.
[P2] Update the command-layer schema-version diagnostics
This expected message does not match the error path used by uv lock --frozen. LockParseError is converted into uv_lock_operations::LockError::UnsupportedLockVersion, whose display text still says but only v{0} is supported; UnparsableLockVersion has the same mismatch with the second updated snapshot. Updating the lower-level parse error does not update these wrappers. Change both command-layer messages to describe support for versions 1 and 2 and match these expectations.
| let mut candidates = Vec::new(); | ||
| let mut covered = BTreeSet::new(); | ||
| for group in lock.workspace_groups() { | ||
| let Some(candidate) = lock.select_workspace_group(&group.definition.name)? else { | ||
| continue; | ||
| }; |
There was a problem hiding this comment.
[P3] Give workspace-context selection one shared owner
The coverage, candidate projection, and ambiguity algorithm here duplicates uv-project-commands/src/lock.rs::select_workspace_group_lock, along with three selection error variants. Both implement the same policy, but project-edit commands reach this copy while sync/run/export reach the command-layer copy. Future fixes to overlap or coverage rules must therefore be maintained twice. Move the shared selection operation into uv-lock, returning structured selection errors that callers can translate into command diagnostics.
c980e89 to
63034b9
Compare
| for group in &lock.workspace_groups { | ||
| writer.array_of_tables(&["workspace-group"])?; |
There was a problem hiding this comment.
[P3] Teach the canonical reader about workspace-group tables
Every grouped lock emitted here is rejected by from_canonical_toml: DocumentMapAccess::section_key has no [[workspace-group]] case. Normal commands still work through the general TOML fallback, but grouped workspaces lose the canonical read path. The new round-trip test masks this because it calls from_toml. Extend the reader’s table and sequence handling, and check serialized grouped output directly with from_canonical_toml, following canonical_round_trip_uses_fast_path.
| selected_lock: Option<Lock>, | ||
| target_members: BTreeSet<PackageName>, | ||
| needs_lock_resolution: bool, |
There was a problem hiding this comment.
[P3] Distinguish pending command selections from finalized scopes
For a member reached only through an extra or dependency group, this selection still contains the broader group domain until refine_from_lock runs. However, scoped_workspace already exposes it as an ordinary Workspace, and workspace_for_project_groups returns that workspace alongside the pending selection. Sync, run, check, and the edit commands must each remember the flag-check → resolve → refine ordering before creating an environment. Represent pending and finalized selections explicitly, requiring refinement before exposing the environment scope. Keep an explicit provisional scope for interpreter probes and --no-sync. This makes the ordering requirement visible in the API instead of distributing it across command implementations.
| if let Some(workspace_group_requires_python) = | ||
| workspace.workspace_group_requires_python(sources)? | ||
| { | ||
| let Some(requires_python_intersection) = RequiresPython::intersection( | ||
| std::iter::once(workspace_group_requires_python.specifiers()).chain( |
There was a problem hiding this comment.
[P2] Preserve platform-dependent Python bounds during discovery
This uses the group's Python projection without its remaining environment conditions. For example, let app support >=3.12 and depend on a local member requiring >=3.13 only on Linux. The group correctly records sys_platform != 'linux' or python_full_version >= '3.13', but its projected Python requirement still permits 3.12. On Linux, discovery therefore reuses an existing 3.12 environment, and synchronization subsequently fails with LockedPlatformIncompatibility, even when 3.13 is available. Carry the selected environment through interpreter discovery and derive Python bounds for the target platform; apply the same rule to frozen discovery.
| project_workspace_selection( | ||
| project, | ||
| &package, | ||
| all_packages, | ||
| &discover_workspace_groups( |
There was a problem hiding this comment.
[P2] Apply selected workspace roots to check targets
In a non-project workspace with default group main = [app] and another member outside that group, this selects main for interpreter discovery and installation. However, check_targets was already populated from every workspace member, and that unchanged list reaches ty::run. Consequently, uv check analyzes the other applications against an environment missing their dependencies and potentially using an incompatible Python version. Resolve the member selection before constructing the check targets, and use the same selected roots for analysis and environment preparation.
| if project_python.has_environment_constraints() { | ||
| let requests = match project_python | ||
| .clone() | ||
| .for_environment(python.interpreter().markers()) | ||
| { |
There was a problem hiding this comment.
[P3] Share platform-aware interpreter search in the discovery layer
This duplicates the probe → platform refinement → installed-interval preference → download/retry sequence in ProjectPythonRequest::find_or_download. Changes to global version-file handling or interval fallback must now be maintained in both the discovery layer and this command. The warning-only compatibility behavior of venv is deliberate, but the interpreter search itself is shared policy. Extract that search into uv-python-discovery, returning the selected request and installation, and layer strict validation or warning-only handling on the result.
| } else if let MetadataSource::Manifest(LockTarget::Workspace(workspace)) = &source { | ||
| Some(workspace.with_provisional_workspace_groups( | ||
| &workspace.workspace_groups_with_dependency_metadata( | ||
| &settings.sources, | ||
| &settings.dependency_metadata, | ||
| )?, |
There was a problem hiding this comment.
[P2] Skip manifest group discovery for frozen metadata
This frozen branch recomputes group domains from the current manifests before reading uv.lock, even without --sync. After creating a valid grouped lock, changing a member's Python bounds to conflict with its group makes workspace metadata --frozen fail instead of exporting the locked graph. read_frozen deliberately accepts the locked group definitions, and synchronization already obtains its requirement from the selected lock. Skip this manifest discovery in frozen mode and derive any required environment scope from the lock.
| let selected_target = if let Some(target) = selected_target { | ||
| target | ||
| } else { | ||
| install_target | ||
| .select_workspace_context() | ||
| .context("Failed to collect module owners")? |
There was a problem hiding this comment.
[P2] Preserve metadata export when installation contexts are ambiguous
For incompatible groups without a default, metadata export succeeds without an environment but fails once .venv exists: this branch tries to combine every workspace root into one installable context. The resulting error recommends --workspace-group, which this command does not accept. Full-graph export should not require a jointly installable workspace merely to collect optional module owners. When synchronization is disabled and context selection is ambiguous, retain the graph and environment metadata and omit module ownership information.
| member_sources | ||
| .and_then(|sources| sources.inner().get(&requirement.name)) | ||
| .map(|sources| (sources, member_root)) | ||
| .or_else(|| { | ||
| self.sources() | ||
| .get(&requirement.name) | ||
| .map(|sources| (sources, self.install_path().as_path())) |
There was a problem hiding this comment.
[P3] Share the source-selection policy with requirement lowering
This prepass independently implements project-versus-workspace source precedence, extra filtering, and marker complements already implemented by LoweredRequirement::from_requirement. These decisions must agree: one determines the group's Python domain while the other determines its resolved dependencies. Future source-policy changes therefore require coordinated edits in two layers. Extract the pure source-selection and marker-partitioning policy into a shared workspace helper, retaining asynchronous source lowering and reachability traversal in their respective callers.
| if let Ok(wire) = toml::from_str::<LockWire>(input) | ||
| && let Err(error) = Self::try_from(wire) | ||
| && let LockErrorKind::MissingWorkspaceMemberIdentity(_) = &*error.kind | ||
| { | ||
| return Err(LockParseError::MissingWorkspaceMemberIdentity(error)); |
There was a problem hiding this comment.
[P3] Retain typed lock validation errors without reparsing
A canonical legacy lock missing member identities is deserialized and validated by the fast reader, again by the TOML fallback, and again here solely to recover the typed error erased by Serde. This repeats full graph construction and makes recoverability depend on an error-specific reparse branch. Deserialize the fallback into LockWire and call Lock::try_from explicitly, retaining its domain error in LockParseError while preserving unsupported-version diagnostics.
| } else if let TreeSource::Manifest(LockTarget::Workspace(workspace)) = source { | ||
| Some(workspace.with_provisional_workspace_groups( | ||
| &workspace.workspace_groups_with_dependency_metadata( | ||
| &settings.sources, | ||
| &settings.dependency_metadata, | ||
| )?, |
There was a problem hiding this comment.
[P2] Skip group discovery for frozen universal trees
This prepass runs before the --frozen && --universal interpreter bypass. After locking a valid group, changing a member's Python bounds to conflict with that group's bounds makes uv tree --frozen --universal fail with DisjointWorkspaceGroupPython, although the locked graph remains valid. read_frozen deliberately accepts the locked group definitions, and existing frozen-tree tests establish that stale graphs remain readable. Skip this discovery when no interpreter is needed; derive any necessary frozen scope from the lock.
| Ok(FinalizedCommandWorkspaceSelection { | ||
| scope: self.scope, | ||
| selected_lock: None, | ||
| }) |
There was a problem hiding this comment.
[P3] Reuse the projection produced when finalizing a selection
For pending member selections, finalize constructs a projected lock to derive the Python domain, then discards it here. After environment creation, sync calls select_workspace_group_result on the same resolved graph and repeats that projection. This duplicates package cloning, reachability traversal, sorting, and index construction. Retain the projection in the existing selected_lock field and let callers consume it through take_selected_lock, as the frozen-selection path already does.
| .map_or(MarkerTree::FALSE, |&index| { | ||
| package_environment(lock.package(index), &lock.requires_python) | ||
| }) | ||
| .and(environment); |
There was a problem hiding this comment.
[P2] Remove conflict selectors from member platform domains
When a selected local member exists only in a conflicting-extra fork—for example, one extra selects workspace leaf while another selects a different leaf source—package_environment retains encoded extra selectors. These propagate into the projected lock's supported_environments. However, sync_from_lock evaluates those environments with no extras activated, so a positive selector causes LockedPlatformIncompatibility on every platform despite the valid member selection. Derive the Python/platform domain using the environment-only projection (without_extras()), keeping conflict activation separate in graph selection.
| self.workspace_groups = groups; | ||
| for group in &self.workspace_groups { | ||
| let selected = self.select_workspace_group(&group.definition.name)?; | ||
| for name in &group.definition.members { |
There was a problem hiding this comment.
[P3] Validate group identity invariants when deserializing locks
LockWire reaches this constructor without the duplicate-name and multiple-default checks performed during workspace discovery. A lockfile containing two main groups with the same roots but different Python domains passes this validation: select_workspace_group uses .find(), so both iterations validate the first definition. Frozen commands then silently select the first definition; multiple defaults similarly become order-dependent. Reject duplicate group names and multiple defaults at this construction boundary so lockfile consumers receive the same unambiguous group identities guaranteed by manifest discovery.
| uv_snapshot!(context.filters(), context.export().args(["--offline", "--frozen", "--no-sources", "--no-header", "--no-hashes"]), @" | ||
| exit_code: 2 (failure) | ||
| ----- stderr ----- | ||
| error: the argument '--frozen' cannot be used with '--no-sources' |
There was a problem hiding this comment.
[P3] Exercise the grouped lock in the no-sources export test
The --frozen/--no-sources combination hits an existing clap conflict before workspace discovery or lock projection. This snapshot therefore passes independently of workspace-group support and never checks the lock just produced by uv lock --no-sources. Remove --no-sources from the frozen export—the lock already records that resolution—and snapshot the successful common-leaf export, following the adjacent export tests.
| let selected = requirement | ||
| .requires_python | ||
| .to_exact_marker_tree() | ||
| .and(requirement.environments.restrict(platform)); |
There was a problem hiding this comment.
[P2] Evaluate substring markers during platform refinement
restrict(platform) cannot evaluate in/not in or reversed substring comparisons: the marker engine represents these as independent In/Contains variables, separate from the equality nodes constructed above. For example, an app supporting Python >=3.12 can depend on a local member requiring >=3.13 under sys_platform in 'linux darwin'. On Linux, this refinement leaves the substring condition unresolved, and Python projection still permits 3.12. Discovery can therefore reuse a 3.12 environment, after which synchronization rejects it with LockedPlatformIncompatibility, even when 3.13 is available. Partially evaluate all platform-string node kinds against the concrete MarkerEnvironment before projecting Python ranges.
Depends on #2593.
Large workspaces can contain sets of applications that cannot share every dependency version or Python range. Add
tool.uv.workspace.groupsto name those resolution roots, restrict their Python support, and optionally select a default. Locking attempts a shared resolution and automatically splits incompatible contexts while retaining common package records and stable locked preferences.uv sync,uv run, anduv exportcan select a context with--workspace-group, including from a frozen lockfile. Ordinary package targeting combines compatible contexts and reports ambiguous choices. Grouped workspaces use lockfile format version 2 so older readers cannot combine incompatible variants; ungrouped workspaces continue to use version 1.