Skip to content

feat: rework cycle detection with edge-captured routing - #5916

Merged
baszalmstra merged 2 commits into
prefix-dev:feature/lockfile-v7from
baszalmstra:cycle-work
Apr 17, 2026
Merged

baszalmstra merged 2 commits into
prefix-dev:feature/lockfile-v7from
baszalmstra:cycle-work

Conversation

@baszalmstra

@baszalmstra baszalmstra commented Apr 17, 2026 •

Copy link
Copy Markdown
Contributor

Description

The compute engine previously panicked whenever it detected a dependency cycle that wasn't anticipated by the task chain. That made cycles a correctness-critical concern for every caller instead of a recoverable condition, and it made it impossible for higher-level resolvers (which legitimately want to react to cycles, e.g. to emit a good error or pick an alternate path) to handle them without aborting the whole engine.

This PR turns cycles into a first-class, recoverable outcome:

  • Cycles surface as Err(ComputeError::Cycle(path)) at ComputeEngine::compute, carrying the full ring so callers can produce actionable error messages.
  • User code can opt into catching cycles at a specific scope via ComputeCtx::with_cycle_guard. Only cycles whose path actually passes through that scope's key are caught; unrelated cycles keep propagating, so a guard can't accidentally swallow a cycle it has no business handling.
  • Parallel combinators (compute2, compute_join, ...) now behave predictably when cycles cross branches. Previously the chain-based detector couldn't distinguish sibling branches, which meant cycle notifications could be misrouted or a guard in one branch could influence another. Guards are now branch-local.

The Demand API commit exists to support this: the new detector needs to carry small pieces of metadata on keys without leaking generic parameters through the engine's type-erased core, and Demand is the minimal surface for that.

Net effect for callers:

  • No more panics on unguarded cycles.
  • Resolvers and other higher-level consumers can finally handle cycles the same way they handle any other error.
  • Cycle behaviour across parallel work matches intuition instead of depending on internal task ordering.

Example

/// A module whose dependencies may legitimately form a cycle (e.g. a
/// resolver that wants to report "cyclic import" instead of aborting
/// the whole build).
#[derive(Clone, Hash, PartialEq, Eq)]
struct Module(String);

impl Key for Module {
    // Cycles are folded into the domain Value, so callers of this
    // Module see a regular error and the engine does not panic.
    type Value = Result<Resolved, ResolveError>;

    async fn compute(&self, ctx: &mut ComputeCtx) -> Self::Value {
        let deps = load_deps(&self.0)?;

        // Opt into catching cycles that pass through *this* module.
        // A cycle that forms strictly below us (e.g. between two of
        // our deps that don't touch us) is NOT caught here, it keeps
        // propagating. A guard is a local claim "I can recover from a
        // cycle on me", not a catch-all.
        let resolved = ctx
            .with_cycle_guard(|ctx| async move {
                let mut out = Vec::new();
                for dep in deps {
                    out.push(ctx.compute(&Module(dep)).await?);
                }
                Ok(out)
            }.boxed())
            .await;

        match resolved {
            Ok(deps)    => Ok(Resolved::new(&self.0, deps)),
            Err(cycle)  => Err(ResolveError::Cyclic {
                module: self.0.clone(),
                path: cycle.path(), // full ring for diagnostics
            }),
        }
    }
}

// Top-level: if nobody installs a guard on a key that sits on the
// cycle, the cycle surfaces here as a structured error instead of a
// panic.
match engine.compute(&Module("root".into())).await {
    Ok(value)                          => use_it(value),
    Err(ComputeError::Cycle(path))     => report_unhandled_cycle(path),
    Err(other)                         => report_other(other),
}

How Has This Been Tested?

  • Existing pixi_compute_engine integration tests.
  • Expanded tests/integration/cycle.rs covering guarded and unguarded cycles, cycles across parallel branches, and the "only catch cycles that include my key" guard semantics.
  • New tests/integration/demand.rs for the Demand API.
  • Doctests on every ComputeCtx public method.

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

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.

…e_guard

Replaces the per-task chain-based cycle detector with an engine-wide
active-edge multigraph. Each in-flight ctx.compute(&dep) installs an
edge that captures the notify target visible from the caller's
branch-local guard stack at edge creation time. Cycle detection BFSes
forward from target; on close, every edge-captured target on the ring
is notified.

A user ComputeCtx::with_cycle_guard scope catches cycles whose detected
path contains its own key; unhandled cycles flow up via each task's
synthetic fallback and surface at ComputeEngine::compute as
Err(ComputeError::Cycle(path)) carrying the full ring. No more panic
on unguarded cycles.

Parallel combinators (compute2/compute_join/...) give each sub-ctx a
fresh branch-local guard stack chained to the parent's, so user scopes
opened inside one branch cannot leak into siblings. The ActiveEdges
graph is a multigraph so parallel branches awaiting the same dep each
keep an independent record.

Docs: new internal walkthrough in cycle/mod.rs with ASCII diagrams,
crate-level # Cycles section in lib.rs, and runnable doctests on every
ComputeCtx public method.
//! This makes `ctx.compute(..)` safe to embed inside cancellable
//! `tokio::select!` branches without starving other subscribers.
//!
//! # Cycles

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Explanation of how this is supposed to work from a user perspective.

@baszalmstra
baszalmstra requested a review from hunger April 17, 2026 13:05

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

We need to get this into use to shake out the bugs. I could not spot an obvious problems and the described approach should in theory work.

@baszalmstra
baszalmstra merged commit ef5e7af into prefix-dev:feature/lockfile-v7 Apr 17, 2026
38 of 39 checks passed
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.

2 participants