Skip to content

Add workspace groups - #1832

Draft
zaniebot wants to merge 90 commits into
zaniebot/project-extra-conflict-prerequisitefrom
zb/workspace-groups-sketch-20260916
Draft

zaniebot wants to merge 90 commits into
zaniebot/project-extra-conflict-prerequisitefrom
zb/workspace-groups-sketch-20260916

Conversation

@zaniebot

@zaniebot zaniebot commented Sep 16, 2026 •

Copy link
Copy Markdown
Collaborator

Depends on #2593.

Large workspaces can contain sets of applications that cannot share every dependency version or Python range. Add tool.uv.workspace.groups to 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, and uv export can 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.

@astral-automations-bot astral-automations-bot Bot added the documentation Improvements or additions to documentation label Sep 16, 2026
@zaniebot zaniebot added the project:workspace-conflicts Workspace resolution roots, groups, and conflict handling label Sep 16, 2026
@zaniebot zaniebot changed the title Sketch workspace groups Add workspace groups Sep 16, 2026
@codspeed

codspeed Bot commented Sep 16, 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

✅ 54 untouched benchmarks
⏩ 35 skipped benchmarks1


Comparing zb/workspace-groups-sketch-20260916 (49b16e0) with zaniebot/project-extra-conflict-prerequisite (1c7bcd3)

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. ↩

@astral-automations-bot
astral-automations-bot Bot force-pushed the zb/workspace-groups-sketch-20260916 branch from 2c85b59 to f16583e Compare September 18, 2026 17:27
@zaniebot zaniebot added risk:3 Credible risk of meaningful incorrect behavior or regression; bounded or recoverable. priority:3 Normal: useful features, documentation, usability, or routine efficiency improvements. size:5 Project-sized: too much semantic scope for a normal review; needs decomposition or design review. labels Sep 23, 2026
@astral-automations-bot
astral-automations-bot Bot force-pushed the zb/workspace-groups-sketch-20260916 branch from f16583e to b58e528 Compare September 25, 2026 16:26
@astral-automations-bot
astral-automations-bot Bot force-pushed the zb/workspace-groups-sketch-20260916 branch 4 times, most recently from fa6c29c to c102755 Compare October 3, 2026 00:25
@astral-automations-bot
astral-automations-bot Bot force-pushed the zb/workspace-groups-sketch-20260916 branch 4 times, most recently from eda7311 to c980e89 Compare October 7, 2026 21:49
Comment thread crates/uv-lock-operations/src/lock.rs Outdated
Comment on lines +515 to +517
let groups = workspace.workspace_groups_with_sources(&settings.sources)?;
if !groups.is_empty() {
return Box::pin(do_lock_workspace_groups(

ghost Oct 7, 2026

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] 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.

Comment on lines +214 to +217
if local {
let marker = active.and(requirement.marker).and(source.marker());
if !marker.is_false() {
pending.push((requirement.name.clone(), marker));

ghost Oct 7, 2026

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] 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.

Comment on lines +174 to +176
for dependency in member.project().dependencies.iter().flatten() {
let requirement =
Requirement::<VerbatimParsedUrl>::from_str(dependency).map_err(|error| {

ghost Oct 7, 2026

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] 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.

Comment on lines 197 to +201
error @ (LockError::UnsupportedLockVersion(..)
| LockError::UnparsableLockVersion(..)
| LockError::LockSerialization(_)
| LockError::WorkspaceGroupResolution(..)
| LockError::MissingWorkspaceGroupResolution

ghost Oct 7, 2026

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 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`.

ghost Oct 7, 2026

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] 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.

Comment on lines +424 to +429
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;
};

ghost Oct 7, 2026

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] 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.

@astral-automations-bot
astral-automations-bot Bot force-pushed the zb/workspace-groups-sketch-20260916 branch from c980e89 to 63034b9 Compare October 8, 2026 02:15
@zaniebot
zaniebot deployed to automations October 10, 2026 05:39 — with GitHub Actions Active
Comment on lines +111 to +112
for group in &lock.workspace_groups {
writer.array_of_tables(&["workspace-group"])?;

ghost Oct 10, 2026

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] 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.

@zaniebot
zaniebot deployed to automations October 10, 2026 06:12 — with GitHub Actions Active
@zaniebot
zaniebot deployed to automations October 10, 2026 06:17 — with GitHub Actions Active
Comment thread crates/uv-project-commands/src/lock.rs Outdated
Comment on lines +163 to +165
selected_lock: Option<Lock>,
target_members: BTreeSet<PackageName>,
needs_lock_resolution: bool,

ghost Oct 10, 2026

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] 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.

@zaniebot
zaniebot deployed to automations October 10, 2026 06:29 — with GitHub Actions Active
Comment on lines +267 to +271
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(

ghost Oct 10, 2026

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 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.

Comment on lines +354 to +358
project_workspace_selection(
project,
&package,
all_packages,
&discover_workspace_groups(

ghost Oct 10, 2026

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] 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.

Comment thread crates/uv/src/commands/venv.rs Outdated
Comment on lines +193 to +197
if project_python.has_environment_constraints() {
let requests = match project_python
.clone()
.for_environment(python.interpreter().markers())
{

ghost Oct 10, 2026

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 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.

Comment on lines +130 to +135
} 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,
)?,

ghost Oct 10, 2026

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] 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.

Comment on lines +352 to +357
let selected_target = if let Some(target) = selected_target {
target
} else {
install_target
.select_workspace_context()
.context("Failed to collect module owners")?

ghost Oct 10, 2026

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 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.

Comment on lines +540 to +546
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()))

ghost Oct 10, 2026

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 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.

Comment thread crates/uv-lock/src/lock/mod.rs Outdated
Comment on lines +3898 to +3902
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));

ghost Oct 10, 2026

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] 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.

Comment thread crates/uv-project-commands/src/tree.rs Outdated
Comment on lines +160 to +165
} 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,
)?,

ghost Oct 10, 2026

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] 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.

Comment on lines +259 to +262
Ok(FinalizedCommandWorkspaceSelection {
scope: self.scope,
selected_lock: None,
})

ghost Oct 10, 2026

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 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.

Comment on lines +434 to +437
.map_or(MarkerTree::FALSE, |&index| {
package_environment(lock.package(index), &lock.requires_python)
})
.and(environment);

ghost Oct 10, 2026

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] 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.

Comment on lines +151 to +154
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 {

ghost Oct 10, 2026

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] 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.

Comment on lines +1726 to +1729
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'

ghost Oct 10, 2026

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] 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.

Comment on lines +261 to +264
let selected = requirement
.requires_python
.to_exact_marker_tree()
.and(requirement.environments.restrict(platform));

ghost Oct 10, 2026

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] 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.

This branch was successfully deployed

1 active deployment
automations — 49b16e09 Deployed Oct 10, 2026 by zaniebot via review-code-quality / code quality review #9552
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation priority:3 Normal: useful features, documentation, usability, or routine efficiency improvements. project:workspace-conflicts Workspace resolution roots, groups, and conflict handling risk:3 Credible risk of meaningful incorrect behavior or regression; bounded or recoverable. size:5 Project-sized: too much semantic scope for a normal review; needs decomposition or design review.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants