Skip to content

refactor: move more to compute engine. - #5938

Merged
baszalmstra merged 45 commits into
prefix-dev:feature/lockfile-v7from
baszalmstra:instantiate-tool-env
Apr 30, 2026
Merged

baszalmstra merged 45 commits into
prefix-dev:feature/lockfile-v7from
baszalmstra:instantiate-tool-env

Conversation

@baszalmstra

@baszalmstra baszalmstra commented Apr 21, 2026 •

Copy link
Copy Markdown
Contributor

Description

Moved to the compute engine:

  • Checking out git and url sources (b8917f6)
  • Discovering backends from sources (e68f255)
  • Instantiating tool environments (50dd3d7)
  • Build backend metadata (68c2f43)
  • Dev source metadata (4a9288f)

You can run any command with PIXI_COMPUTE_DEP_GRAPH:

PIXI_COMPUTE_DEP_GRAPH=deps.dot pixi lock

to dump the dependency graph from the compute engine at the end of the program.

How Has This Been Tested?

CI should pass

AI Disclosure

  • This PR contains AI-generated content.
    • I have tested any AI-generated content in my PR.
    • I take responsibility for any AI-generated content in my PR.

Tools: Claude Code Opus 4.7

Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added sufficient tests to cover my changes.

@baszalmstra
baszalmstra requested a review from hunger April 21, 2026 11:36
@baszalmstra
baszalmstra marked this pull request as draft April 22, 2026 15:07
@baszalmstra
baszalmstra marked this pull request as draft April 22, 2026 15:07
@baszalmstra
baszalmstra force-pushed the instantiate-tool-env branch 4 times, most recently from e1c249e to 68f4b78 Compare April 24, 2026 12:34
Retires the legacy dispatcher-task based source-build/source-metadata/
solve-pixi pipeline and replaces it with compute-engine Keys that
share computation across environments via content-addressed dedup.

## Compute engine primitives
- add SpawnHook so task-locals propagate across engine-spawned compute
  tasks (tracing spans, reporter contexts).
- add ComputeEngine::with_ctx bridge from engine handle to ctx
  extension traits.
- reshape async ctx combinators to AsyncFnOnce/AsyncFn.
- expose ParallelBuilder and simplify cycle-detection.

## New Keys on top of the engine
- InstantiateBackendKey, DiscoveredBackendKey
- BuildBackendMetadataKey, DevSourceMetadataKey
- SolveCondaKey, ResolveSourcePackageKey, SolvePixiEnvironmentKey
- SourceBuildKey + SourceBuildSpecV2 + SourceBuildResult
  plus on-disk ArtifactCache + WorkspaceCache with cross-process
  fd locks, variant-aware cache keys, bucket-tagged build/host deps,
  sidecar round-trip of every RepoDataRecord field.

## ctx extension traits
- ctx.install_pixi_environment (install_pixi::ext)
- ctx.backend_source_build (backend_source_build::ext)
- ctx.solve_conda (solve_binary)
Each handles reporter lifecycle, semaphore acquisition, and
reporter-context scoping.

## Migrated callers
- install_pixi source-build recursion routes through SourceBuildKey.
- pixi build / pixi publish CLI commands use SourceBuildKey directly.
- CommandDispatcher::install_pixi_environment routes through
  engine.with_ctx + ctx.install_pixi_environment.

## Retired legacy code
- Deleted legacy solve_pixi / source_metadata / source_record / source_build
  dispatcher-task bodies.
- Deleted BackendSourceBuild dispatcher-task plumbing.
- Deleted InstallPixiEnvironmentSpec::install, SourceBuildSpec,
  BuildCache, SourceBuildCacheStatusSpec, CommandDispatcherProcessor
  background thread, Reportable trait, PixiEnvironmentSpec,
  SolveCondaEnvironmentSpec::solve + CommandDispatcher::solve_conda_environment,
  SourceBuildError::CreateHostEnvironmentDirectory, SourceRecordReuseKey,
  SourceRecordDeduplicationKey, SourceCycleKey, cache_source_record::WriteResult,
  CommandDispatcherChannel::Weak variant, _PixiRecordUsedByKey /
  _PixiRunExports workaround aliases, SourceBuildSpec::build unused vars.

## Satisfiability stopgap
- Emit PlatformUnsat::SourceRecordRequiresRebuild for any mutable or
  partial source record. This forces a re-lock rather than
  reconstructing build/host environments. TODO comment in
  satisfiability/mod.rs explains the proper fix: verify the backend's
  declared host/build specs against the locked host/build package
  sets without reconstructing those environments.
- Satisfiability test harness accepts SourceRecordRequiresRebuild as
  a pass in the good-case suite since local-path source packages
  always hit the pessimistic path.

## Tests
- 76 unit tests, 34 integration tests.
- Cross-env dedup tests for SourceBuildKey, InstantiateBackendKey,
  SolvePixiEnvironmentKey (including the EphemeralEnv name-exclusion
  invariant).
- Cache-key derivation tests (bucket separation, variant, platform,
  backend identifier).
- Sidecar round-trip coverage for every RepoDataRecord field.
- Cycle tests use a fixed Platform::Linux64 and simple_test redacts
  the host platform so snapshots are stable across OSes.

## Known stopgap-blocked tests (ignored)
- test_source_package_lock_file_up_to_date,
  test_build_config_change_invalidates_cache,
  test_source_record_roundtrips_through_lock_file: expect a second
  lock invocation to no-op; the stopgap forces every source record
  to re-lock.
- test_targeted_pin_overrides_include_nested_source_dependencies,
  test_duplicate_installed_source_hints_are_order_independent,
  test_top_level_and_nested_source_hints_for_same_package_are_normalized:
  hint-normalization follow-ups.

## Lint / cleanup
- cargo fmt + clippy -D warnings clean across the workspace.
- Removed unused deps (coalesced_map, tokio-util, pixi_build_discovery,
  pixi_spec) from member Cargo.tomls; moved slotmap to dev-dependencies;
  dropped redundant cargo-shear ignore.
- Fixed rustdoc intra-doc links that referenced deleted or private items.
- Fixed typos (unparseable -> unparsable).

## Follow-up work (not in this change)
- Replace the pessimistic SourceRecordRequiresRebuild with a proper
  host/build spec verification against locked package sets.
- Normalize installed-hints before the solve (three ignored tests).
- Investigate stack overflows in add_sdist_functionality and
  pyproject_dynamic_version_source_dependency on Windows.
@baszalmstra
baszalmstra force-pushed the instantiate-tool-env branch from 68f4b78 to 23deb9e Compare April 24, 2026 13:46
CommandDispatcher::install_pixi_environment goes through
engine.with_ctx + ctx.install_pixi_environment. Both run inline in
the caller's task (with_ctx does not spawn; the ext trait is a
method on ComputeCtx, not a Key). When the caller is already deep
in another async pipeline (for example the PyPI resolve path
invoking conda prefix setup for build isolation), the additional
inline state machine can exhaust the thread stack.

Boxing the whole with_ctx future moves the state machine to the
heap in one allocation, preserving task-local propagation that a
tokio::spawn would drop.

Also un-ignores pyproject_dynamic_version_source_dependency and
add_sdist_functionality, which were ignored as follow-up work in
the previous commit but are fixed by this change.
Integrates prefix-dev#5958 on top of source-build-compute-engine. Adds:

- LockFileResolver: single-pass topological walk of lock-file packages
  that produces UnresolvedPixiRecord with build_packages/host_packages
  populated from predecessors. Built once per update/satisfiability run
  and shared across platforms.
- Hash/Eq/PartialEq on PixiRecord, UnresolvedPixiRecord, SourceRecord<D>
  (HashMap<String,SourceLocationSpec> -> BTreeMap for Hash).
- SourceRecordRequiresRebuild pessimistic stopgap for mutable/partial
  records in satisfiability (matches upstream). TODO to replace with
  backend-spec-vs-locked-packages check lives with the code.
- resolve_dev_dependencies takes a single WorkspaceEnvRef instead of
  channels/build_env/variants; adapted both call sites (satisfiability
  and update's spawn_extract_environment_task).
- Test fixtures for nested source-build deps and round-tripped build/host
  packages.

Adapts to the Key-based dispatcher API on this branch: uses
SolvePixiEnvironmentKey + EnvironmentRef/EnvironmentSpec in place of the
retired command_dispatcher.solve_pixi_environment; uses
engine().with_ctx(...).pin_and_checkout for source pinning.
Introduces InstalledSourceHints, a deduplicated and depth-unified view
of source-record install hints built once at the top of a pixi solve
and threaded through every nested recursion layer.

Before: SolvePixiEnvironmentKey's walk built a fresh HashMap<PackageName,
(Vec, Vec)> from its local installed slice, losing duplicates by
overwrite and disagreeing across depths (top-level hint for foo != the
nested foo hint that bar's host_packages carried). That produced
ResolveSourcePackageKey calls with divergent installed_build/host_packages
inputs for logically-equal source packages, so the engine cached them
as distinct entries and returned inconsistent results depending on which
branch of the recursion hit them first.

Now:
- New type InstalledSourceHints keys hints on (PackageName,
  SourceLocationSpec) from a recursive walk of the installed tree, with
  canonical tie-break on duplicates.
- SolvePixiEnvironmentSpec carries installed_source_hints:
  PtrArc<InstalledSourceHints>; the full hint map flows through nested
  SPEKs verbatim via Arc clone.
- ResolveSourcePackageSpec drops installed_build_packages /
  installed_host_packages; RSP's compute looks up its own (package,
  source_location) in the hints.
- SolvePixiEnvironmentSpec.installed is now Arc<[UnresolvedPixiRecord]>
  (cheap clone, shared across hops).
- New helper type PtrArc<T>: an Arc<T> wrapper with pointer-identity
  Hash/Eq for use in Key specs where the invariant is 'same Arc flows
  down'. Equal-but-distinct Arcs compare unequal (produces a re-compute
  rather than a silent false hit).
- InstalledSourceHints::empty_arc() is a singleton; 'PtrArc::default()'
  on this type returns the singleton so independently-built empty specs
  still dedup.

Enables the two previously-ignored integration tests:
test_duplicate_installed_source_hints_are_order_independent
test_top_level_and_nested_source_hints_for_same_package_are_normalized
Cleans up rustdoc warnings flagged by RUSTDOCFLAGS=-D warnings across:

- pixi_compute_engine: redundant explicit link targets (any_key.rs,
  engine.rs, error.rs, injected.rs) and a non-existent 'EdgeGuard'
  link in active_edges.rs.
- pixi_command_dispatcher: redundant explicit link targets (env_ref.rs,
  install_pixi/ext.rs, resolve_source_package.rs, solve_pixi_environment.rs,
  resolved_backend_command.rs), non-existent Cycle / CycleError /
  SolveCondaEnvironmentSpec::solve / PIXI_BUILD_API_VERSION /
  CondaSolveSemaphore / CURRENT_REPORTER_CONTEXT::scope /
  CommandDispatcher::executor links, ambiguous crate::short_type_name.
- pixi_record: unresolved '9f3c2a7b' link (hash example not escaped).
- pixi_manifest: non-existent 'Manifest', 'KnownFeature' links, unescaped
  [project] and <Platform> tokens.
- pixi_core: non-existent 'OutdatedEnvironments::from_project_and_lock_file',
  'resolve_pypi' / 'resolve_conda' links.
- pixi_reporters: non-existent 'CommandQueue' link.
- pixi_install_pypi: non-existent 'UnresolvedPypiRecord' /
  'distribution_types::Dist' / 'PixiInstallPlan' links.
- pixi_cli: bare URLs in run.rs / self_update.rs wrapped in <>.
…rk dirs

On-disk layout
- Collapse the per-workspace cache layout to a flat set of directories
  directly under .pixi/. The old '.pixi/build/pkgs-v0/{artifacts,workspaces}/'
  nesting went deep enough to hit Windows' MAX_PATH during backend builds.
- New layout under .pixi/:
    artifacts-v0/<pkg>/<key>/                   built packages (content-addressed)
    bld/<pkg>/<key>/                            source-build backend workspaces
    meta-v0/<source>/<host>-<metahash>.json     backend metadata cache
    meta-v0/<source>/work/<key>/                backend scratch for conda/outputs
- Drop the display-only '<host_platform>-' prefix from WorkspaceKey and
  ArtifactCacheKey (host_platform was already folded into the xxh3).
  Saves ~8-11 chars per cache path.

Merged workdir into metadata cache
- The backend metadata cache and the per-source 'work/' scratch (passed
  to conda/outputs) now share one tree per source under meta-v0/<source>/.
  One 'rm -rf meta-v0/<source>/' wipes both. Invalidation granularity is
  unchanged: the metadata cache entry and the work dir key are still
  separate, just co-located.
- Rename CACHED_BUILD_BACKEND_METADATA dir 'metadata' -> 'meta' (shorter).
- Add BACKEND_METADATA_WORK_SUBDIR const; remove CACHED_BUILD_WORK_DIR.
- CacheDirs: rename build_backend_metadata() -> backend_metadata(); add
  backend_metadata_work_dir(&source_unique_key); drop working_dirs(),
  the work_dirs field, with_working_dirs(), set_working_dirs().
- Add with_backend_metadata()/set_backend_metadata() for the
  'pixi build --build-dir' override, which now aims at the unified root.

Dead-code removal
- Remove SourceRecordCache + entry/key types; it was constructed and
  stored on the dispatcher but never read or written.
- Remove CacheDirs::source_metadata(), CACHED_SOURCE_METADATA const,
  CommandDispatcher::source_record_cache() accessor, builder wiring,
  lib.rs re-export, and the source_metadata wipe in pixi clean.
- Remove unused UpstreamCacheRef type alias in cache::common.
- Remove unused coalesced_map workspace dep.

Clean command
- pixi clean and pixi clean --build wipe every per-workspace cache dir
  via workspace_build_cache_dirs(); legacy .pixi/build/ still included
  so users migrating from the old layout see a clean .pixi/.

@hunger hunger left a comment

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.

LGTM, you might want to add the patches I have on top in https://github.com/hunger/pixi/tree/push-zlvknwtkxukr That fixes the tests.

Six packages across C, C++, Rust, and Python sharing a single fat-pointer
C ABI (pc_emitter_t / pc_modifier_t = data + fn pointers). Demonstrates
two backends working together: pixi-build-cmake for particle_core,
particle_cpp, particle_cpp_py (pybind11), and particle_view (SDL2 +
pybind11); pixi-build-python for particle_rs (maturin + PyO3) and
particle_kit (hatchling). Path-based source deps, host vs run dep splits,
Python scenes rendered through SDL.
…umbing

Replaces the pessimistic SourceRecordRequiresRebuild stopgap with a
real check: query BuildBackendMetadataKey for each mutable / partial
source record, pick the matching CondaOutput by name + variants, and
verify the locked build_packages / host_packages still satisfy the
backend's declared build/host specs.

LockedConda<'a> wraps the locked record slice and exposes the
matching predicates (satisfies_binary by name + nameless spec,
satisfies_source by pinned manifest source, contains_name for
pin_compatible). Same surface area the main-env walker
re-implements over PixiRecordsByName today; future work can
converge both call sites once that walker speaks
UnresolvedPixiRecord directly.

verify_locked_against_backend_specs returns Box<PlatformUnsat> (no
more CommandDispatcherError wrapping inside the function); the
caller wraps once via map_err(CommandDispatcherError::Failed). PyPI-
shaped records in build/host are rejected. New PlatformUnsat
variants:
- SourceVariantNotInBackend
- SourceBuildHostUnsat
- SourceBuildHostDisallowsPypi
- SourceBuildHostSourceMissing

Backend is only contacted when the locked record actually needs
re-evaluation: a partial record (no version material in the
lockfile) or a full+mutable record with populated build/host
packages. Full+mutable records with no build/host info (legacy
lockfile shape) are downcast directly so older lockfiles don't
require an installed backend just to pass satisfiability.

Re-lock now stays incremental:
- spawn_solve_conda_environment_task takes
  Arc<UnresolvedPixiRecordsByName> instead of the resolved-only
  view, so partial source records (their pinned manifest source
  plus their build/host package sets) reach the solver via
  installed and InstalledSourceHints.
- pin_overrides defaults to every locked source record's
  build_source minus update_targets.

Workspace-level disregard cascades into source records'
build/host envs because those packages live inside the source
records that the locked_grouped_repodata_records filter drops as
a unit. Documented at the filter site and in the
installed_source_hints module-doc.

Manifest-source pin propagation prevents git/url commit drift:
- New InstalledSourceHints::find_for_location matches by name +
  PinnedSourceSpec::matches_source_spec, so a hint stored under
  the pinned location key still matches a live walk that starts
  from the manifest's unpinned spec.
- ResolveSourcePackageKey looks up the hint and threads
  manifest_pin_override into SourceMetadataSpecV2.
- SourceMetadataKey uses checkout_pinned_source(override) when
  the override matches the requested source location, otherwise
  falls back to pin_and_checkout.

Error-conversion duplication collapsed into
spec_conversion_to_match_spec_error and
failed_to_parse_match_spec_unsat helpers; the four sites that
used to inline the SpecConversionError -> ParseMatchSpecError
match are now one-liners.

Tests:
- 4 new InstalledSourceHints unit tests (unpinned-git lookup, repo
  mismatch, name disambiguation, find_for_location coverage).
- 7 new satisfiability::backend_verification unit tests, including
  a regression test (wrong_name_record_does_not_satisfy_binary_spec)
  for a name-blind matcher bug found while writing the integration
  test.
- Un-ignored test_source_package_lock_file_up_to_date,
  test_build_config_change_invalidates_cache, and
  test_source_record_roundtrips_through_lock_file (previously
  blocked by the stopgap).
- New test_relock_keeps_locked_build_packages_as_installed_hints
  integration test: foo 1.0.0 + foo 2.0.0 in the channel, source
  initially pinned to foo 1.0; loosened build-deps trigger a
  re-lock; locked foo 1.0 must survive (not jump to foo 2.0) and
  the new bar dep is added. Without the installed hint the solver
  would pick foo 2.0, so the assertion discriminates the
  incremental-update guarantee.
- Refreshed snapshots for binary-spec-source-record,
  mismatched-source-spec, and the two source-recursive-dependency
  cases now report the real spec mismatch instead of the generic
  rebuild error.
Pulls in the latest commit on conda/rattler#feature/lockfile-v7
(7b7f53e0 -> f169fe31) for every workspace dep that points at
that branch.
Move the artifact cache lookup ahead of the
`InstantiateBackendKey::compute` call. The cache key only needs a
stable backend identifier string, which is fully determined by the
discovery + ephemeral-env solve — none of it needs the JSON-RPC
backend to be spawned, the activator to be run, or the handshake to
be performed.

New `pixi_command_dispatcher::resolve_backend_identifier` helper
runs the same `DiscoveredBackendKey` -> `ResolvedBackendCommandKey`
-> `EphemeralEnvKey` chain that a real instantiation would, but
stops at the resolved primary-package version and returns
`"<command>@<version>"` for env-spec backends, the system command
for system backends, and `BoxedInMemoryBackend::identifier()` for
in-memory backends. All three lookup steps are content-addressed
Keys, so when an actual instantiation runs after a cache miss it
shares the work via the engine's per-process dedup; the only thing
this skips on a hit is `spawn_json_rpc` + activator.

`source_build::compute_inner` now calls the helper, builds the
artifact cache key, looks up the cache, and only invokes
`InstantiateBackendKey` on a miss.

Side change: `BoxedInMemoryBackend::identifier()` is now a public
accessor on the wrapper struct. The field was already stored; only
the getter is new.

Cache-key format change: the identifier portion went from
`tool.executable()` (the bare backend command name) to
`<command>@<resolved_version>`. Existing
`.pixi/artifacts-v0/*` entries miss once and re-populate; the new
key is also more correct because it now actually invalidates when
the user upgrades the backend version (the bare command name
didn't).

Measured impact in `examples/pixi-build/polyglot-particles` (warm
cache, all 6 source builds hit):
- Before: 380-625 ms wall, 6 backend spawns logged.
- After:  230-360 ms wall, 0 backend spawns logged.
- "Installed environment 'default'" reported time:
  261-409 ms -> 116 ms.
The compute-engine cache is per-process, so every `pixi run` was
re-fetching repodata and re-solving the build-backend tool env
from scratch — even though the resolved prefix was already on
disk from a previous run. On Windows that re-solve costs ~250 ms
per unique backend (pixi-build-cmake / pixi-build-python in
polyglot-particles), serialized at the head of every source-build
fanout because every `SourceBuildKey` waits on `EphemeralEnvKey`
through `resolve_backend_identifier`.

Write a `.pixi-ephemeral-cache.json` marker into the prefix
after a successful install, recording the resolved
`Vec<RepoDataRecord>` plus a small schema version. On the next
process, `EphemeralEnvKey::compute` reads the marker first; if
the prefix exists and the marker parses with the current schema
version, return the cached `InstalledEphemeralEnv` immediately
and skip everything below (binary specs, ToolBuildEnvironmentKey,
fetch_binary_repodata, solve_conda, lock acquire, install,
unlock). Marker writes are atomic (write-temp + rename) and
best-effort: a write failure just costs the next caller one solve.

Schema version is bumped if the marker layout ever changes — old
markers fall through to the slow path.

Measured impact in `examples/pixi-build/polyglot-particles`:
- `pixi run echo hello`: 230-360 ms wall -> 134 ms wall.
- "Installed environment 'default'": 116-130 ms -> 21 ms.

Backend-process spawns are still skipped on artifact-cache hits
(introduced in the prior commit); together the two changes cut
`pixi run echo hello` for this workspace from ~600 ms (before
the source-build spawn fix) to ~134 ms.
@baszalmstra
baszalmstra force-pushed the instantiate-tool-env branch from 9c24b01 to a032ba6 Compare April 28, 2026 15:25
The activation cache key is now a hash of "what is currently in the
prefix" (per-record sha256s for binary records and built source-build
artifacts), not "which URLs the lockfile references". For source
packages those URLs are stable path/git strings that don't change
when the underlying source content changes — so the URL-based key
silently accepted stale activation env vars after a source rebuild.
Hashing the per-record sha256s costs almost nothing because every
record already carries its sha256 from repodata or the artifact
cache sidecar.

New `pixi_command_dispatcher::EnvironmentFingerprint` newtype owns
the value: `compute(records)` produces it during install,
`as_str` / `Display` expose the digest, and `read(env_dir)` /
`write(env_dir)` manage a small `.pixi-environment-fingerprint`
marker file under `<env_dir>/conda-meta/`. The marker write is
atomic (write-temp + rename), best-effort; a write failure costs
the next caller one re-activation, never correctness.

Plumbing:
- `InstallPixiEnvironmentResult.installed_fingerprint`,
  `CondaPrefixUpdated.installed_fingerprint`, and
  `CondaPrefixInstallResult.installed_fingerprint` are now
  `EnvironmentFingerprint` instead of `String`.
- New `LockFileDerivedData::UpdatedPrefix` newtype wraps the prefix
  with its (optional) fingerprint coming out of `update_prefix`. The
  `Option` is `None` for filtered installs, where only a subset of
  packages is touched and the fingerprint wouldn't represent the
  full prefix state.
- `LockFileDerivedData::prefix` writes the fingerprint via
  `EnvironmentFingerprint::write` after a successful update.

`EnvironmentHash` is now two flavours:
- `from_environment(...)` keeps the legacy URL-based hashing for
  task caching, where a task's cached result depends on inputs the
  user can change without an install.
- `for_activation(... &EnvironmentFingerprint)` is the new flavour
  used by the activation cache; folds the fingerprint into the
  hash, drops URL hashing entirely.

Activation cache control flow:
- The read path (`try_get_valid_activation_cache`) short-circuits
  to `None` whenever no fingerprint marker exists for the env, so
  pre-install or `pixi shell-hook` flows trivially fall through to
  fresh activation.
- The write path matches: skip the cache file when no fingerprint
  is available.
- The `experimental.use-environment-activation-cache` config flag
  remains opt-in (default off).

Tests updated: the `test_run_activation_cache_based_on_lockfile`
case is replaced by `test_run_activation_cache_based_on_install_fingerprint`,
which exercises the marker-driven code path and confirms that
bumping the fingerprint invalidates the cache the same way changing
the lockfile used to.

Measured impact in `examples/pixi-build/polyglot-particles` with
`--use-environment-activation-cache`:
- `pixi run echo hello`: ~134 ms wall (default) -> ~105 ms wall.
- The 30 ms saved is the activation-script subprocess that no
  longer runs on cache hit.
@baszalmstra
baszalmstra force-pushed the instantiate-tool-env branch from a032ba6 to 1b76917 Compare April 28, 2026 16:04
When the prefix's recorded install fingerprint already matches the
one we'd install, every source-build sha256 has been re-confirmed by
SourceBuildKey above this point. The rattler installer would have
zero ops, so synthesize an empty Transaction with python_info derived
from the would-be records and return early. Saves ~30ms per pixi run
in steady state on top of the activation-cache short-circuit.
Tests look up backend debug files via Workspace.iter_debug_dirs.
The build folder layout moved from .pixi/build/work/<entry>/debug/
to .pixi/bld/<pkg>/<workspace_key>/debug/ (see DEBUG_OUTPUT_DIR
and cache_dirs::source_build_workspaces). Update the helper to
walk the new two-level structure.
@baszalmstra
baszalmstra force-pushed the instantiate-tool-env branch from 1b76917 to e98888b Compare April 28, 2026 20:46
A `Full+mutable+empty-build/host` source record (the legacy lockfile
shape produced before build/host packages were round-tripped) used to
slip through satisfiability without ever consulting the backend. The
outer gate only fired the backend check for `partial` records or for
`mutable + populated build/host packages`, and a sibling fallback
inside the verifier skipped verification whenever the locked
build/host slices were empty. Together they meant edits to a source
package's `[package.host-dependencies]` (and friends) on a
path-based source were silently accepted and the lockfile was
considered up-to-date.

Fix the gate to fire the backend check for any mutable source, and
drop the inner skip-when-empty fallback. Mutable sources have no
content-pinned identifier we can use to detect manifest edits, so
the backend is the only signal we have; if its declarations don't
match the locked build/host packages (including the empty-vs-some
case for legacy lockfiles) the satisfiability check now correctly
fails and forces a re-lock. Immutable + full records still
short-circuit at the outer gate, so they don't pay any extra cost
and don't require an available backend.

The existing `missing_required_record_in_locked_build_fails` unit
test already covers the empty-locked-vs-declared-deps case at the
verifier level; the fix wires it into the actual control flow.
Stale legacy-shape lockfiles in `examples/pixi-build/*` (notably
array-api-extra, cpp-git-source, recursive-run-dependencies) now
correctly surface as unsat in the `q` snapshot test and need a
`pixi update` to repopulate.
Two `#[ignore]`d integration tests demonstrating that adding or
removing an entry from a path-based source package's
`[package.run-dependencies]` does not invalidate the lock-file. Both
go through `update_lock_file` with `PassthroughBackend` (which
re-reads `run-dependencies` from the source manifest on every
metadata call) and assert that the second solve reports
`was_updated == true`. They currently fail at that assertion, so
they're marked ignored to keep CI green while the fix lands. The
ignore message names the bug so anyone running them with
`--ignored` knows what they're seeing.

Removal is the harder direction the docstring calls out: a one-way
"every backend-declared dep is satisfied by the locked record"
check, which is the shape used for build/host verification, passes
when a run-dep is dropped because the remaining deps are still
locked. The locked record's `depends` carries an extra entry the
backend no longer declares, and detecting that delta requires a
bidirectional check against the backend's `run_dependencies`. The
two tests anchor that contract.
…kages

`pixi update <pkg>` only relaxed the top-level locked entry. Any transitive
copy of `<pkg>` carried inside a source record's `build_packages` /
`host_packages` survived, so source packages kept building against the old
version. Worse, dropping the top-level entry while keeping the transitive
left the lockfile inconsistent: the resolver's graph walker tripped its
cycle detector on the dangling `source_data` indices.

Fix `filter_lock_file` to:

- Route every kept conda package through `LockFileResolver` +
  `UnresolvedPixiRecord::into_conda_package_data`, so source records'
  build/host indices get re-registered against the new builder's package
  table instead of dangling into the old one.
- Apply the user-supplied predicate to the transitive entries inside each
  kept source record's `build_packages` / `host_packages`, in addition to
  the top-level. The predicate now sees a `LockedPackageKind<'_>` (name +
  conda/pypi tag) which is cheap enough to synthesize for transitives.

Add `test_update_invalidates_transitive_in_source_host_packages` covering
the full `pixi update sdl2` CLI path against a path-based source package
whose `host-dependencies` include sdl2.
baszalmstra and others added 23 commits April 29, 2026 16:41
A locked source record's `depends` is the union of the manifest's
declared run-dependencies plus any run-exports contributed by the
resolved host/build packages, so a naive string compare against the
backend's `run_dependencies` cannot tell which entries came from
where. The same trap applies to `constrains` against
`weak_constrains`/`strong_constrains` from host/build run-exports.

`verify_locked_run_deps_against_backend` reassembles the expected
multiset by reusing the dispatcher's `Dependencies::new` plus
`extend_with_run_exports_from_build_and_host` (the same machinery
that produces locked.depends at solve time), reads run_exports off
the locked binary records (now persisted via the rattler_lock bump),
and stringifies through the new `PixiSpec/BinarySpec::to_match_spec`
methods. The check then multiset-diffs the result against
`record.depends()` (and `record.constrains` for Full records) and
surfaces the symmetric difference.

No `MatchSpec::from_str` runs on the locked side: both halves of the
comparison go through the same stringify pipeline that wrote
`depends` originally, so byte-equality is the right comparison.

New `PlatformUnsat::SourceRunDependenciesChanged { package, kind,
added, removed }` reports the drift, with `kind` distinguishing
run-dependencies from run-constraints. Helpers
`collect_direct_run_exports`, `resolved_records`,
`stringify_pixi_dep_map`, `stringify_binary_dep_map`, and
`diff_multisets` keep the verifier compact.

Visibility: `pixi_command_dispatcher::build::dependencies` is now a
public module (was crate-private with selective re-exports);
`filter_match_specs` is now `pub` so satisfiability can convert
locked binary records' `RunExportsJson` into `PixiRunExports` with
the same `ignore_run_exports` filter conda-build semantics expect.

Partial source records skip the constrains check because
`PartialSourceRecordData` only round-trips `depends`. Their
constrains drift remains undetected for now; addressing that needs
the lockfile schema to carry constrains on partial records too.

Tests `test_source_run_dependency_addition_invalidates_lock_file`
and `test_source_run_dependency_removal_invalidates_lock_file` now
pass and are no longer `#[ignore]`d. Existing example lockfiles
under `examples/pixi-build/*` that lack persisted `run_exports`
will need one `pixi update` to repopulate before the `q` snapshot
test passes for them; this is the same forced-re-lock shape the
build/host check already imposes on legacy lockfiles.
Drops the `#[ignore]` attributes from
`test_source_run_dependency_addition_invalidates_lock_file` and
`test_source_run_dependency_removal_invalidates_lock_file`. The
satisfiability check added in the previous commit now detects both
addition and removal of `[package.run-dependencies]` entries on
path-based source packages, so these tests pass.
Adds focused unit coverage for the new drift-detection machinery in
`verify_locked_run_deps_against_backend`:

- diff_multisets: addition-only, removal-only, both-directions, the
  duplicate-as-distinct semantics that catches a locked entry being
  recorded twice when the backend would only emit it once, and the
  ordering-independence (sets, not sequences) baseline.
- verify_locked_run_deps_against_backend, constrains arm:
  passes-when-match, addition (backend declares a new constraint
  the locked record doesn't carry), removal (locked carries a
  constraint the backend no longer declares). All three exercise
  Full source records since constrains aren't round-tripped on
  Partial records.

Pixi's manifest schema doesn't currently expose
`[package.run-constraints]` for source packages (the
`run_constraints` field exists in the build-backend protocol but
no manifest path produces it yet), so an integration-test mirror
of the run-dependency tests isn't reachable from PassthroughBackend
today. The unit tests directly exercise the verifier with
synthesized CondaOutput inputs and cover the same add / remove
contract.
…-sensitive

The locked source record's `depends` and `constrains` are produced
by iterating a `DependencyMap` at solve time, so the `Vec<String>`
ordering is part of the value. A pure reorder is genuine drift
(the lockfile encodes a specific snapshot), not a false positive.

`diff_multisets` becomes `diff_dep_sequences` and now compares the
two `Vec<String>`s directly. On mismatch it still computes the
symmetric multiset difference for the common add/remove case, but
also reports a `reordered` flag for the case where the same set of
specs appears in a different order. The `DepDiff` carrier carries
the locked and expected sequences alongside, so the
`SourceRunDependenciesChanged` variant can render either flavour
clearly.

`PlatformUnsat::SourceRunDependenciesChanged` grows a `reordered:
bool` and `locked` / `expected: Vec<String>` field; the format
string conditionally appends a `; reordered (locked: ...; expected:
...)` clause when only the order drifted. Existing add/remove
diagnostics are unchanged.

Tests in `backend_verification` rename from `diff_multisets_*` to
`diff_sequences_*`, drop the "order should not matter" baseline,
and add `diff_sequences_detects_reorder` to lock the new contract
in. The constrains-arm tests pin `reordered = false` so a future
regression doesn't silently match.
Bumps the rattler feature/lockfile-v7 pin from aa7e481b to 3eeb23ac
to pick up the upstream change that adds `constrains` to
`rattler_lock::PartialSourceMetadata` and threads it through the
v7 source-package wire format. The next commit mirrors the field
on pixi_record's `PartialSourceRecordData` and threads it through
the lockfile round-trip so a mutable source package's manifest
constrains aren't silently dropped on lockfile write.
`PartialSourceRecordData` now carries `constrains: Vec<String>`
alongside `depends`, mirroring the rattler_lock side of the v7
source-package wire format. Without this, mutable (path-based)
sources that declare run-time constraints lost them on every
lockfile write, because `into_conda_source_data` downgrades Full
to Partial when the source is mutable, and the old Partial shape
had nowhere to put `package_record.constrains`.

Threaded through:
- `from_conda_source_data` reads `partial.constrains` from
  `rattler_lock::PartialSourceMetadata` (now non-empty since the
  rattler bump in the previous commit).
- `into_conda_source_data` writes it back, including the Full→Partial
  downgrade for mutable sources which now keeps `constrains`
  alongside `depends`.
- New `SourceRecord::<PartialSourceRecordData>::constrains()` and
  `SourceRecord::<SourceRecordData>::constrains()` accessors mirror
  the existing `depends()` shape.
- Construction sites updated:
  `pixi_command_dispatcher::installed_source_hints` (two), the
  `pixi_record` round-trip tests, and the satisfiability test
  fixture under `make_partial_source_record`.

Satisfiability gain: `verify_locked_run_deps_against_backend` no
longer needs the `if let SourceRecordData::Full(full)` guard around
the run-constrains check. The check now applies symmetrically to
both Full and Partial source records via `record.constrains()`.
The previous comment about "Partial records already force a re-lock
through other paths" was wrong (they didn't force anything in this
code path); the actual reason was the missing field, and that's now
fixed.
…ift integration test

Three small cleanups to verify_locked_run_deps_against_backend
based on the code review:

- Inline `stringify_pixi_dep_map` and `stringify_binary_dep_map`.
  They were `FnOnce` projection wrappers around two call sites
  that just wanted to iterate `Dependencies::dependencies` and
  `Dependencies::constraints`. The closure indirection had no
  second consumer; the call sites are now five-line iterator
  expressions over `iter_specs()` (reference iteration, no map
  clone) feeding `to_match_spec(...).to_string()`. A small
  `spec_unsat` helper avoids repeating the
  SourcePackageMetadataChanged-from-error boilerplate.

- Make `DepDiff` lazy on the reorder fields. The previous shape
  always allocated `locked` and `expected` as `Vec<String>` clones
  even though they're only read when the diagnostic is a pure
  reordering. The fields now live behind `reorder:
  Option<DepDiffReorder>` so the common add/remove path doesn't
  pay for the two clones. A new `DepDiff::into_unsat` consumes
  the diff into the matching `PlatformUnsat` variant, splitting
  the option back out into the variant's flat
  `(reordered, locked, expected)` field shape so the wire
  contract stays unchanged.

- Replace the stale "compare as multisets" comment with the
  accurate "ordered sequences" wording.

Tests in `backend_verification` updated to consume the new
`DepDiff::reorder: Option<DepDiffReorder>` shape (`diff.reordered`
became `diff.reorder.is_some()`, `diff.locked`/`expected` became
`reorder.locked`/`expected`).

Also adds the integration test
`test_host_run_export_constraint_removal_invalidates_lock_file`,
which exercises end-to-end constrains drift via the real
backend / build / lockfile pipeline. `MockRepoData` ships
`libfoo` with `weak_constrains: ["bar <2"]`, a path-based source
package depends on it as a host-dep so the build pipeline applies
the run-export to the built record's `constrains`, and the
second `update_lock_file` runs after the host-dep is dropped from
the source manifest. The host-dep check by itself is one-
directional and would silently accept the locked record's now-
extra `host_packages` entry; the run-constrains drift detector is
what catches the leftover `bar <2` in `constrains`. Mirrors the
unit-level `verify_locked_run_deps_detects_constrain_removal`
test, since pixi's manifest schema doesn't currently expose
`[package.run-constraints]` directly.
…st radius

These four files predate this stack but show fmt drift and clippy
warnings that the rebased stack wants clean. Bundled into one
cleanup commit on top so the stack passes `cargo fmt --check
--all` and `cargo clippy -- -D warnings` for the touched crates.

- `install_pixi/fingerprint.rs`: replace four `std::fs` calls with
  their `fs_err` equivalents to satisfy the workspace's
  `disallowed-methods` clippy config (matches the rest of the
  dispatcher).
- `install_pixi/ext.rs`: add a single
  `#[allow(clippy::result_large_err)]` to `unchanged_transaction`
  with a one-line reason. The function returns the same unboxed
  `InstallPixiEnvironmentError` that `install_inner` already
  returns; the allow is consistent with how the rest of the
  workspace handles this error contract (cf.
  `pixi_record::pinned_source`, `pixi_spec::lib`, etc).
- `lock_file/update.rs`: collapse the nested `if let Some(fp)
  { if let Err(err) = fp.write(...) }` into a single `if let &&
  let` chain.
- `install_pixi/ext.rs`, `environment/mod.rs`: rustfmt drift.
The pre-v7 source-env reify path wrote its on-disk cache to a
hardcoded `<project_root>/.pixi/legacy-source-env/<hash>.json`,
bypassing the dispatcher's `CacheDirs`. In production this happened
to land in the right `.pixi` directory, but it ignored every other
cache-routing knob: `--build-dir` overrides, custom `PIXI_DIR`, and
the temp-dir cache the satisfiability test harness wires up via
`CacheDirs::new(temp_pixi_dir)`. The result was that running the
satisfiability suite against `tests/data/satisfiability/source-dependency`
silently created a `.pixi/legacy-source-env/` inside the checked-in
test fixture.

Add `CacheDirs::legacy_source_env()` (mirroring the existing
`backend_metadata()` / `source_build_artifacts()` accessors) and a
matching `LEGACY_SOURCE_ENV_DIR` constant. Drop the
`workspace_root: Arc<PathBuf>` field from `LegacySourceEnvKey` and
the corresponding parameter from `reify_legacy_source_envs`; the
key now reads its cache directory from `ctx.global_data().cache_dirs()`
inside the compute body, like `BuildBackendMetadataInner` already
does. Layout flips from `<project>/.pixi/legacy-source-env/...` to
`<workspace or root>/legacy-source-env/...`, which collapses to the
same place in production and to the harness tempdir under tests.

Also fold in a trivial `clippy::needless_borrow` fix in the
`build_tests.rs` helper introduced by the same stack.
The original lock-file was generated before rattler_lock learned to
round-trip run_exports, so build/host packages landed without their
run_exports field. The satisfiability check's run-dep verification
reads run_exports off the locked records to re-derive a source
package's depends/constrains; without them it sees no
`libgcc >=15` from gcc's strong run-export and reports drift
against the (correctly populated) source record.

Re-running `pixi lock` rewrites the lock under the bumped
rattler_lock, embedding run_exports for build packages and letting
the q satisfiability test pass for this workspace.
…task cache

The ephemeral-env compute key gained a fast path that returns the
cached records when it finds a `.pixi-ephemeral-cache.json` marker
in the target prefix. This test reuses the user-global cache via
`default_cache_dirs()`, so a marker left by a previous run (or by
any `pixi run` that resolved the same backend) made the future
return without ever firing `CondaSolveStarted`, and the wait timed
out.

Switch to a fresh tempdir-rooted `CacheDirs` so the prefix starts
clean and the slow path the test wants to observe is the only
available code path. Bump the wait timeouts from 2s to 30s while
we're here: the test cares about ordering, not latency, and 2s
isn't enough to weather a cold dispatcher start on slow CI.
…port drift test

The integration test `test_host_run_export_constraint_removal_invalidates_lock_file`
relied on weak_constrains run-exports being applied to the source
record's constrains, but PassthroughBackend hard-coded its outputs
to NoArch. `extend_with_run_exports_from_build_and_host` only
applies weak/strong/strong_constrains/weak_constrains for non-NoArch
targets, so a NoArch source pkg with libfoo (weak_constrains: bar <2)
in host-deps never picked up the constrain. The locked record was
empty all along, so dropping the host-dep produced no drift.

PassthroughBackendConfig already exposed `noarch: Option<bool>` but
nothing read it. Wire it up so an explicit `noarch = false` opts the
output into a platform-specific build using params.host_platform
(conda_outputs) or params.output.subdir (conda_build_v1). Default
behavior is preserved: unset / Some(true) keeps the NoArch path
that every other passthrough test relies on.

Update the failing test's source manifest to set `noarch = false`
so weak_constrains actually flow into the locked record's constrains
and dropping libfoo surfaces real drift the verifier can catch.
…tive

The locked source-record `depends` / `constrains` are persisted in the
order produced by `DependencyMap` iteration at solve time. That order
mirrors the input `Vec<(PackageName, PixiRunExports)>` returned by
`extract_run_exports` (during solve) or `collect_direct_run_exports`
(during satisfiability). The first sees records in solver order
(typically topological); the second reads them back from the lock
file in alphabetical order. Same set of run-exports, different
`Vec` iteration → different `DependencyMap` insertion order →
different `depends` sequence, even though the two represent the
same multiset of specs.

Hit in the wild on a ROS workspace where `ros-humble-navigator-py`
locked `python_abi 3.12.* *_cp312` before `numpy >=1.23,<3` (solver
order put python before numpy) but the verifier re-derived
`numpy ...` before `python_abi ...` (alphabetical), tripping the
drift detector on every `pixi lock` even though nothing about the
manifest had changed.

Order isn't semantically meaningful for these lists — the solver
treats them as a set of specs — so the previous "order is real
drift" assumption was wrong. Switch `diff_dep_sequences` to a
multiset comparison and drop the reorder-payload machinery
(`DepDiffReorder`, `reordered`/`locked`/`expected` fields on
`PlatformUnsat::SourceRunDependenciesChanged`, the
`reorder_msg` portion of the diagnostic). Permutations now pass;
adds and removes still surface verbatim, and the duplicate-spec
case still surfaces as a removal as before.
…ild env

verify_locked_against_backend_specs previously checked pin_compatible
deps against the env being verified, but pin_compatible(foo) in host
deps pins to whatever foo resolved to in the *build* env. A stale
lock where the build env has no foo (or has it at a different
version) was silently accepted.

Pass the build slice as pin_compatible_locked when verifying host
deps, and resolve the pin against that record's version+build
before checking the resulting NamelessMatchSpec against the verified
env.

To make this composable, lift the structural Pin type and its
resolution math out of pixi_command_dispatcher::build::pin_compatible
into pixi_spec::pin (Pin, PinBound, PinExpression, PinError). The
dispatcher's resolve_pin_compatible becomes a thin lookup wrapper
that delegates to Pin::resolve. pixi_build_types is now an optional
dep on pixi_spec, gated behind a feature, providing TryFrom impls
that turn the wire-format PinCompatibleSpec into a Pin.

While here, switch LockedConda to a name-indexed view so the three
name-keyed queries become O(1) lookups.

Drops the #[ignore] on the regression test added in the previous
commit and adds happy-path + version-drift tests, plus pure-resolve
tests in pixi_spec.
The format-upgrade path forced `outdated.conda` for every environment
to drive a no-op re-solve that would refill the v7-only fields v6
omits (source-record timestamps, build/host packages). `outdated.pypi`
was left untouched, but the extract task spawned for every entry in
`all_outdated_envs` unconditionally writes the env's
`solved_pypi_records` cell. With no pypi solve in flight that cell
gets `Arc::default()` — and an empty cell beats the locked-file
fallback in `take_latest_pypi_records`, so the v6→v7 upgrade
silently stripped every pypi entry on the first run and only
re-resolved them on the second.

Mark pypi outdated for the same set of envs/platforms. The pypi
solver receives `locked_group_records` as hints exactly like the
conda side, so the re-solve is a no-op for already-pinned packages,
the file flips to v7 with all entries preserved, and a follow-up
`pixi lock` reports the lock as up-to-date instead of churning the
pypi block.

Verified on F:\projects\issues\missing-pypi: v6 lock with 25 pypi
entries upgrades cleanly to v7 with the same 25 entries, no package
additions or removals reported, and the second `pixi lock` is a
no-op.
The python version (slow + needs network for pixi-build-cmake)
exercised: `pixi install --locked` rejects a git-ref drift between
the manifest and the lock without rewriting the lock; a follow-up
`pixi lock` updates the pin and re-enables `--locked` installs.

The rust port runs offline against a PassthroughBackend and a local
git repo built from the new `lock-behaviour-base` fixture: the
fixture seeds the initial commit on `main`, and the test layers an
`other-feature` branch + a second `main` commit on top through a
small `GitRepoFixture::git` escape hatch (the numbered-fixture format
can't express branches).

The new `repo_path` field on `GitRepoFixture` makes the working
directory addressable for tests like this one. `extract_git_build_sources`
mirrors the python helper that diffs git pins out of the lock.

Currently fails on the second `pixi lock` step: changing the
manifest's git pin from `rev = main_rev` to `branch = other-feature`
makes `pixi install --locked` reject the mismatch (good), but the
follow-up `pixi lock` rewrites the lock to the same rev as before
instead of resolving `other-feature` to its actual HEAD. That's the
underlying bug the test is now in place to drive the fix for.
…ec for git

For git sources `matches_source_spec` only compared repository URL +
subdirectory and ignored which ref the spec was asking for. The
docstring already framed the function as deciding whether a locked
pin still satisfies the manifest's current source spec so locked
commits can flow through a re-lock when the manifest "still points
at the same branch / ref" — but the implementation never actually
checked the ref, so any URL-equal pin satisfied any spec.

That made every caller treat a manifest pin swap (`rev = X` →
`branch = "Y"`, `branch = "a"` → `tag = "b"`, etc.) as a no-op:

- build_backend_metadata::compute_checkouts kept reusing the locked
  build_source pin against the new spec, so `pixi lock` after a
  manifest ref change rewrote the lock to the same commit as before.
  This was the user-visible bug: `pixi install --locked` correctly
  rejected the mismatch, but the follow-up `pixi lock` did not
  refresh the pin.
- The same was true for `source_metadata::compute` /
  `resolve_source_package::compute` (manifest pin reuse),
  `installed_source_hints::find_for_location` (hint lookup), and
  `satisfiability::satisfies_source` (outdated detection).

Compare `pinned.source.reference` against
`source_git.rev.unwrap_or_default()`, treating an absent spec ref as
`DefaultBranch`. Same ref still matches (= no commit drift on
re-lock), different ref no longer matches (= manifest swap forces a
re-resolve). The unit test that asserted the old behavior was
renamed and flipped, and a positive test for same-ref reuse was
added next to it.
Adds an integration test that asserts a relative exclude-newer cutoff
does not invalidate the source-build cache between consecutive
`pixi install`s when the source package itself has not changed.
@baszalmstra
baszalmstra marked this pull request as ready for review April 30, 2026 10:09
@baszalmstra
baszalmstra merged commit 19c8fe2 into prefix-dev:feature/lockfile-v7 Apr 30, 2026
37 of 38 checks passed
baszalmstra added a commit that referenced this pull request May 1, 2026
baszalmstra added a commit that referenced this pull request May 1, 2026
baszalmstra added a commit that referenced this pull request May 1, 2026
baszalmstra added a commit that referenced this pull request May 1, 2026
baszalmstra added a commit that referenced this pull request May 1, 2026
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.

3 participants