Skip to main content

fuel_dispatch/
optimize.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! `optimize_graph` — the new "plan IS the graph" entry point.
3//!
4//! Phase A PR-A3a/A4 of the "plan IS the graph" rebuild
5//! ([`../../docs/session-prompts/plan-is-graph-rebuild.md`](
6//! ../../docs/session-prompts/plan-is-graph-rebuild.md), the PR-A3/A4
7//! lines + the "Representation — DECIDED 2026-06-15" blockquote, incl.
8//! the architect-approved arm-0 temporary lowering).
9//!
10//! ## What this is
11//!
12//! [`optimize_graph`] is the **new optimization entry point**: it
13//! transforms a [`Graph`] *in place* into the bounded multi-path form
14//! and returns a transient [`OptimizedGraph`] *view* whose dispatch
15//! order is the **arm-0 single-route lowering** of `fuel-graph`'s
16//! `extract_runs` (PR-A2/A4). The optimized form lives **in the
17//! graph** — a graph with zero [`Op::Branch`] nodes is exactly today's
18//! single-route graph.
19//!
20//! ## PR-A4 — the first pathfinder (deliberate-fork seed)
21//!
22//! [`PlacementForkPathfinder`](crate::driver::PlacementForkPathfinder) is the first real pathfinder: where
23//! the placement DP admitted a kernel-bearing node with **≥2 distinct
24//! `(backend, device)` placements** that has a producer (the diverge)
25//! and exactly one consumer (the reconverge), it records ONE
26//! `Op::Branch` — arm-0 = the DP winner (the route realize uses today),
27//! arm-1 = the runner-up clone (orphaned, read only by the Branch). It
28//! emits a branch only at a genuine placement choice, never at ordinary
29//! DAG fan-out, so the fewness gate holds. A CPU-only build (one
30//! placement per node) emits zero branches ⇒ today's single-route graph.
31//!
32//! [`OptimizedGraph::dispatch_order`] is the architect-approved
33//! **arm-0 single-route lowering**: it follows arm 0 through every
34//! branch and skips the other arms' runs, so a branched graph realizes
35//! to the same result as before (arm-0 = the winner). The Phase-C
36//! runtime picker is what later selects non-arm-0 arms.
37//!
38//! ## A3a origin scope (ADDITIVE — proved equivalence, deleted nothing)
39//!
40//! This entry point landed in the **split** A3a: introduced *alongside*
41//! the old path and proved equivalent before anything old was removed.
42//! PR-A3b-1 then made it the default realize path, and PR-A3b-2 deleted
43//! `PlanStore` and the legacy `compile_plan` route-picking dispatch
44//! entirely (`optimize_graph` is now the only path). As originally
45//! introduced in A3a:
46//!
47//! - There were **no pathfinders yet** — the first
48//!   ([`PlacementForkPathfinder`](crate::driver::PlacementForkPathfinder)) landed in PR-A4. A graph with no
49//!   competing routes is already its own single-route plan, so
50//!   [`optimize_graph`] introduces **zero [`Op::Branch`] nodes** for it.
51//! - It **reuses** the existing placement / cost / `target_backend`
52//!   annotation machinery wholesale by driving
53//!   [`crate::plan::compile_plan`] over the same `execution_plan`
54//!   order the bridge uses — the placement DP, cost composer, filter
55//!   chain, and fail-fast missing-binding diagnostics are *not*
56//!   reinvented. The point of A3a is to establish the new entry point
57//!   + in-place form, not new optimization.
58//! - [`crate::plan::compile_plan`] + [`crate::plan::ExecutionPlan`]
59//!   are reused (the latter as a transient by-product). PR-A3b-1 wired
60//!   `optimize_graph` in as the default realize path; PR-A3b-2 made it
61//!   the ONLY path — the legacy `compile_plan`/`PlanStore` route-picking
62//!   dispatch and the identity-keyed plan store are deleted, and
63//!   `optimize_graph` now surfaces its internal `ExecutionPlan` so the
64//!   bridge's stamp/residency/layout passes reuse it (one `compile_plan`
65//!   per realize).
66//!
67//! ## The equivalence gate
68//!
69//! For a graph with no competing routes, [`optimize_graph`] leaves
70//! zero `Op::Branch` nodes and the `extract_runs` / `lower_run`
71//! dispatch order equals today's
72//! [`crate::plan::compile_plan`]`(...).order` — the exact sequence the
73//! production executor walks. The order today is simply the
74//! `execution_plan` topo order `compile_plan` is handed (it copies it
75//! into `ExecutionPlan::order` verbatim); for a branchless,
76//! single-residency graph the run extractor produces exactly one run
77//! whose members are that same topo order. The gate asserts that
78//! equality exactly (same `NodeId`s, same order) — see
79//! `tests::equivalence_gate_branchless_order_matches_compile_plan`.
80
81use std::collections::{HashMap, HashSet};
82
83use fuel_graph::opt::insert_cross_device_copies;
84use fuel_graph::{Graph, NodeId, Op, extract_runs_multi, topo_order_multi};
85use fuel_ir::probe::BackendId;
86use fuel_ir::{DType, DeviceLocation, Result};
87
88use crate::driver::{OptimizationContext, PassRegistry};
89use crate::kernel::KernelBindingTable;
90use crate::plan::{ExecutionPlan, PlanOptions, compile_plan};
91use crate::topology::SystemTopology;
92
93/// Round cap for the residency-eviction pass `optimize_graph` runs under a device byte budget
94/// (the legacy rule's default; the pass stops earlier once the budget is met).
95const RESIDENCY_EVICTION_MAX_ROUNDS: usize = 16;
96
97/// The transient *view* [`optimize_graph`] returns — the realize-roots
98/// it optimized for plus the topology generation it ran under. It is
99/// **not** stored on the graph; the optimized form is the graph itself
100/// (with its `Op::Branch` decision points, of which A3a emits none).
101///
102/// The dispatch order is derived on demand from `fuel-graph`'s run
103/// extraction so the run view is always recomputed from the current
104/// arena — never a stale snapshot. This is the shape PR-A3b swaps the
105/// bridge onto in place of `ExecutionPlan::order`.
106#[derive(Debug, Clone)]
107pub struct OptimizedGraph {
108    /// The realize roots this optimization targeted (the same
109    /// `targets` the bridge passes today).
110    pub roots: Vec<NodeId>,
111    /// `SystemTopology` generation snapshotted at optimize time —
112    /// mirrors [`crate::plan::ExecutionPlan::generation`] so a later
113    /// chunk-boundary check can detect a topology shift exactly as
114    /// the executor does today.
115    pub generation: u64,
116    /// Final effective placement per node, as the optimizer resolved it.
117    /// Read via [`OptimizedGraph::placement_of`].
118    ///
119    /// `None` when the residency pass did not run — it is gated on
120    /// `PlanOptions::pinned_device`, which the production realize path always
121    /// sets and bare-graph test callers often do not. `None` therefore means
122    /// **"not computed"**, never "placed nowhere".
123    pub(crate) placements: Option<HashMap<NodeId, DeviceLocation>>,
124    /// What the budgeted eviction pass did (ROADMAP row 67 I1): `Some` only when
125    /// `PlanOptions::device_budget_bytes` was set and a device was pinned. Read
126    /// [`crate::residency::EvictionOutcome::fits`] before trusting that the budget was met: today a same-device
127    /// budget cannot be met (the reload is not delayed), and this says so.
128    pub eviction: Option<crate::residency::EvictionOutcome>,
129}
130
131impl OptimizedGraph {
132    /// Extract the runs of the optimized graph, in topological order
133    /// of their entries (delegates to [`extract_runs_multi`]). A
134    /// branchless, single-residency graph yields exactly one run.
135    pub fn runs(&self, graph: &Graph) -> Vec<fuel_graph::Run> {
136        extract_runs_multi(graph, &self.roots)
137    }
138
139    /// **The device the optimizer decided this node runs on** — the observable
140    /// form of the placement decision, for callers that need to check *where*
141    /// work landed rather than infer it from timing.
142    ///
143    /// This is the resolved *effective* placement, not a hint. It is the same
144    /// map the residency pass uses to decide where to stitch cross-device
145    /// copies, resolved by the priority in `effective_placements`:
146    /// residency-declaring ops → explicit `Graph::placement` → input residency
147    /// → **plan winner** → backend stamp → view pass-through.
148    ///
149    /// **Do not substitute [`fuel_graph::Graph::placement`] for this.** That is
150    /// only *level 2* of the six — a hint set by inserted copies and caller
151    /// overrides. The planner's actual choice for a compute node arrives at
152    /// level 4 ("plan winner"), so `Graph::placement` returns `None` for
153    /// precisely the nodes whose placement is interesting, and reading that
154    /// `None` as "unplaced" is a wrong answer that looks like a null one.
155    ///
156    /// Returns `None` if the node is unknown to this optimization **or** if the
157    /// residency pass did not run (no `pinned_device`; see the field docs) —
158    /// the two are deliberately not distinguished here because neither means
159    /// "placed nowhere". Use [`OptimizedGraph::has_placements`] to tell them
160    /// apart before drawing a conclusion from a `None`.
161    pub fn placement_of(&self, node: NodeId) -> Option<DeviceLocation> {
162        self.placements.as_ref()?.get(&node).copied()
163    }
164
165    /// Whether placement was computed at all. Distinguishes "this node has no
166    /// placement" from "no node does, because the pass was skipped" — the
167    /// difference between a real observation and an absent instrument.
168    pub fn has_placements(&self) -> bool {
169        self.placements.is_some()
170    }
171
172    /// Every resolved `(node, device)` pair, for dumping a whole graph's
173    /// placement. Empty iterator when placement was not computed — check
174    /// [`OptimizedGraph::has_placements`] first if that distinction matters.
175    pub fn placements(&self) -> impl Iterator<Item = (NodeId, DeviceLocation)> + '_ {
176        self.placements
177            .iter()
178            .flat_map(|m| m.iter().map(|(&id, &loc)| (id, loc)))
179    }
180
181    /// The flat executable dispatch order — the **arm-0 single-route
182    /// lowering** (PR-A4). It follows arm 0 through every `Op::Branch`
183    /// (pre-run, arm-0's run, post-run) and **skips every non-arm-0
184    /// arm's run**, via [`fuel_graph::lower_runs_arm0`].
185    ///
186    /// For a graph with **zero `Op::Branch` nodes** this is the exact
187    /// `NodeId` sequence today's executor walks via
188    /// [`crate::plan::compile_plan`]`(...).order` — the equivalence gate
189    /// proves it (no arm to skip ⇒ identical to concatenating
190    /// [`fuel_graph::run::lower_run`] over the runs). For a branched graph it is the
191    /// single-route lowering on **arm 0 = the DP winner** (the route
192    /// realize used before the branch was recorded), so a branched graph
193    /// realizes to the same result. The Phase-C runtime picker is what
194    /// will later select non-arm-0 arms at the decision points.
195    pub fn dispatch_order(&self, graph: &Graph) -> Vec<NodeId> {
196        fuel_graph::lower_runs_arm0(graph, &self.roots)
197    }
198
199    /// The number of `Op::Branch` decision points in the arena. Counting
200    /// over the whole arena (not just the roots' reachable set) is the
201    /// stronger claim. Zero for a single-route graph (CPU-only build, or
202    /// any graph with no genuine ≥2-placement fork); PR-A4's
203    /// deliberate-fork pathfinder emits one per genuine placement fork.
204    pub fn branch_count(&self, graph: &Graph) -> usize {
205        (0..graph.len())
206            .map(NodeId)
207            .filter(|&id| matches!(graph.node(id).op, Op::Branch { .. }))
208            .count()
209    }
210}
211
212/// Optimize `graph` **in place** into the "plan IS the graph" form and
213/// return the transient [`OptimizedGraph`] lowering view.
214///
215/// `roots` are the realize targets (the bridge's `targets`);
216/// `bindings_table` is the kernel registry the placement/cost
217/// machinery queries (production passes [`crate::dispatch::global_bindings`];
218/// tests pass a local table); `opts` is the same [`PlanOptions`] the
219/// bridge builds for `compile_plan`.
220///
221/// ## Behavior
222///
223/// `optimize_graph`:
224///
225/// 1. Derives the dispatch order via `fuel_graph::opt::execution_plan`
226///    — exactly the order the bridge feeds `compile_plan` today
227///    (data-flow topo refined by destructive-op ordering edges).
228/// 2. Drives [`compile_plan`] over that order to **reuse** the
229///    existing placement DP / cost composer / filter chain and to
230///    fail-fast at build time on a missing binding or absent device
231///    context (validate-at-graph-build-time per the working
232///    agreement). Its [`crate::plan::ExecutionPlan`] is a transient
233///    by-product here — the source of truth is the graph.
234/// 3. Runs the PR-A4 deliberate-fork pathfinder
235///    ([`PlacementForkPathfinder`](crate::driver::PlacementForkPathfinder)): records ONE `Op::Branch` per
236///    genuine ≥2-placement fork (arm-0 = winner, arm-1 = runner-up). A
237///    graph with no competing routes gets **zero** branches — it is
238///    already its own single-route plan.
239///
240/// The returned view's [`OptimizedGraph::dispatch_order`] is the arm-0
241/// single-route lowering; for any branchless graph it reproduces
242/// `compile_plan(...).order` exactly — the equivalence gate.
243///
244/// ## The internal `ExecutionPlan` (Step D — no longer returned)
245///
246/// `optimize_graph` drives [`compile_plan`] internally for
247/// placement/cost/validation; the resulting `ExecutionPlan` is a
248/// **transient, optimizer-internal** accumulator the stamp / residency /
249/// layout-fixup passes + the lock-step rankers read below. It is NOT
250/// returned or threaded anywhere — the durable output is the graph's
251/// `target_backend` stamps + `Op::Branch` arms. The executor reads the
252/// graph + re-derives any per-arm candidate from the binding registry at
253/// realize time, so the plan never becomes a dispatch-time authority.
254pub fn optimize_graph(
255    graph: &mut Graph,
256    roots: &[NodeId],
257    bindings_table: &KernelBindingTable,
258    opts: &PlanOptions<'_>,
259) -> Result<OptimizedGraph> {
260    optimize_graph_with_passes(
261        graph,
262        roots,
263        bindings_table,
264        opts,
265        PassRegistry::default_passes(),
266    )
267}
268
269/// [`optimize_graph`] with the runtime-fusion pathfinder registered
270/// ([`PassRegistry::default_passes_with_runtime_fusion`]): adopted (Tier-2 /
271/// JIT-synthesized) fused ops get their gated `Op::Branch` arms emitted before
272/// placement runs. This is the **production realize path's** entry once a
273/// process can adopt runtime kernels; `optimize_graph` stays runtime-op-free so
274/// bare-graph callers and tests never scan the process-global sidecar.
275pub fn optimize_graph_with_runtime_fusion(
276    graph: &mut Graph,
277    roots: &[NodeId],
278    bindings_table: &KernelBindingTable,
279    opts: &PlanOptions<'_>,
280) -> Result<OptimizedGraph> {
281    optimize_graph_with_passes(
282        graph,
283        roots,
284        bindings_table,
285        opts,
286        PassRegistry::default_passes_with_runtime_fusion(),
287    )
288}
289
290fn optimize_graph_with_passes(
291    graph: &mut Graph,
292    roots: &[NodeId],
293    bindings_table: &KernelBindingTable,
294    opts: &PlanOptions<'_>,
295    passes: PassRegistry,
296) -> Result<OptimizedGraph> {
297    // (1) The dispatch order today: data-flow topo refined by ordering
298    //     edges. `compile_plan` copies this verbatim into
299    //     `ExecutionPlan::order`, so it IS the executor's walk order.
300    let order = fuel_graph::opt::execution_plan(graph, roots);
301
302    // (2) Reuse the placement/cost/validation machinery. The plan is a
303    //     transient, optimizer-INTERNAL by-product — we drive `compile_plan`
304    //     so the same fail-fast diagnostics (missing binding, no device
305    //     context) fire at optimize time, and so the placement DP / cost
306    //     composer run unchanged. The plan is the working accumulator the
307    //     stamp / residency / layout-fixup passes + the lock-step rankers
308    //     read below; it is NOT returned or threaded (Step D — the graph
309    //     stamps + arms are the only durable output).
310    // (2a) Dtype-reconciliation fixup — insert promoting `Op::Cast`s so a node
311    //      whose per-operand key no compiled-in backend serves natively (e.g. a
312    //      mixed-precision `[F32, BF16, F32]` matmul) becomes servable, instead of
313    //      dead-ending in `compile_plan` below. Runs BEFORE the plan because it
314    //      changes what's enumerable; if it rewrites, re-derive the execution
315    //      order over the mutated graph. The layout/residency fixups are its
316    //      post-plan siblings.
317    let order = if insert_dtype_fixups(graph, roots, bindings_table, opts) {
318        fuel_graph::opt::execution_plan(graph, roots)
319    } else {
320        order
321    };
322
323    let plan = compile_plan(graph, &order, bindings_table, opts)?;
324    let generation = plan.generation;
325
326    // (3) PR-B3: the lock-step pass driver. The pre-B3 hardcoded
327    //     `seed_placement_fork_branches(...)` call is replaced by a
328    //     registry of pathfinders + optimizers run lock-step
329    //     (prune-as-you-go): for each registered pathfinder, ADD its
330    //     candidate paths, then immediately run every registered
331    //     optimizer to MERGE/DISCARD over the region just touched. The
332    //     shipped configuration ([`PassRegistry::default_passes`]) is the
333    //     PR-A4 `PlacementForkPathfinder` (the deliberate-fork seed) +
334    //     the `FrontierConvergenceOptimizer` (duplicate-path convergence
335    //     + the never-strand / no-active-cycle invariant guards) — which
336    //     is exactly the pre-B3 sequence, re-expressed. A CPU-only build
337    //     has one placement per node ⇒ the pathfinder proposes zero
338    //     branches ⇒ today's single-route graph (unchanged).
339    //
340    //     The *ranker* + the PR-B2 per-device Pareto frontier are applied
341    //     per kernel-bearing node *inside* `compile_plan` (the MEASURE +
342    //     per-node PRUNE), and the ranked, frontier-pruned result is the
343    //     `plan` the driver reads via `OptimizationContext::plan`. Batch
344    //     optimize has no executing region, so the cycle guard is empty.
345    let cycle_guard: HashSet<NodeId> = HashSet::new();
346    let ctx = OptimizationContext {
347        order: &order,
348        plan: &plan,
349        cycle_guard: &cycle_guard,
350        bindings: bindings_table,
351    };
352    passes.run_lockstep(graph, &ctx)?;
353
354    // "Plan IS the graph": commit the placement decision INTO the graph's
355    // `target_backend` side-table here, so a fully-optimized graph carries
356    // its own backend stamps and downstream consumers read the graph, not a
357    // threaded plan. Guarded on a pinned device — the production realize
358    // path always sets one (`PlanOptions::with_pinned_device`); bare-graph
359    // test callers that don't are unaffected. (Cleanup Step A: this is
360    // idempotent with the bridge's transitional `stamp_plan_backends`, which
361    // re-stamps the identical result; Step A2 removes the bridge copy.)
362    // Stays `None` when the residency pass below is skipped (no pinned device),
363    // so a caller can tell "not computed" from "no placement" — see
364    // `OptimizedGraph::has_placements`.
365    let mut resolved_placements: Option<HashMap<NodeId, DeviceLocation>> = None;
366    let mut eviction: Option<crate::residency::EvictionOutcome> = None;
367    if let Some(pinned) = opts.pinned_device {
368        stamp_plan_backends(graph, roots, &plan, pinned);
369        // Optimize-time kernel-variant bake: resolve **same-device**
370        // kernel-variant branches (a decomposed region vs. a fused kernel on
371        // the SAME device — e.g. the CUDA flash decode arm) to their cost
372        // winner and COLLAPSE them, so the winning variant is selectable
373        // without a runtime pick (04-optimization: kernel-variant choice is
374        // "largely baked at optimize time"). Runs AFTER `stamp_plan_backends`
375        // (the arms now carry `target_backend`, which the same-device gate
376        // reads) and BEFORE `insert_residency_copies` (so the residency pass
377        // stitches inbound copies only for the surviving winner arm, not a
378        // pruned one). A **placement** branch (arms on ≥2 devices) is left
379        // LIVE for the runtime route picker; a graph with no same-device
380        // variant branch — every CPU/Vulkan build today, since no CUDA flash
381        // arm is offered there — is a strict no-op. Ties / unknown costs /
382        // capability-missing default to arm 0 (the decomposed oracle).
383        // The cost provider consults the Judge's MEASURED latency (Layer-2)
384        // FIRST per arm node, falling back to the Layer-1 composite where the
385        // Judge has no cell (the hybrid sum). With `opts.judge == None` this is
386        // byte-identical to the Layer-1-only provider, so the no-Judge path is
387        // unchanged. The same oracle `cost.rs`/`plan.rs` read is threaded here.
388        let judge = opts.judge;
389        crate::variant_bake::bake_variant_branches(graph, roots, &|g, branch, arm, interior| {
390            let backend = g.target_backend(g.node(branch).inputs.first().copied()?)?;
391            crate::variant_bake::decode_arm_composite_ns_judged(
392                g, branch, arm, interior, backend, judge,
393            )
394        });
395        // Cleanup Step B (residency): the optimizer-side cross-device copy pass
396        // (was the bridge's `insert_resident_input_copies`). Runs AFTER stamping
397        // (it reads `target_backend`) and BEFORE layout-fixup, preserving the
398        // prior residency→layout order. Cache residency (where persistent /
399        // const inputs already live) arrives via the `opts.input_residency`
400        // provider the realize path already threads in — the optimizer reads
401        // that fact, it does not touch realize-time storage.
402        // Capture the resolved placement map on the way past — it is the pass's
403        // own input, and surfacing it is what makes `OptimizedGraph::placement_of`
404        // an observation rather than an inference.
405        let placements = insert_residency_copies(graph, roots, &plan, pinned, opts.input_residency);
406        // ROADMAP row 67 (I1): with a device byte budget, evict + reload around the
407        // best candidates while the analysed peak exceeds it. Runs after the copy pass
408        // (it reads the resolved placements) and before layout fixups. No budget = no-op.
409        if let Some(budget) = opts.device_budget_bytes {
410            let mut outcome = crate::residency::insert_residency_evictions_in(
411                graph,
412                roots,
413                pinned,
414                budget,
415                RESIDENCY_EVICTION_MAX_ROUNDS,
416                |id| placements.get(&id).copied(),
417            )?;
418            outcome.budget_source = opts.device_budget_source;
419            eviction = Some(outcome);
420        }
421        resolved_placements = Some(placements);
422        // Cleanup Step B (layout): insert `Op::Contiguize` before any kernel
423        // whose chosen winner rejects strided inputs and whose input layout is
424        // non-contiguous — the optimizer writing the layout-fixup decision INTO
425        // the graph (was the bridge's `apply_layout_fixups`, now retired). No
426        // runtime deps: reads only the in-scope `plan` winner caps + graph
427        // layout. CSE-deduped + idempotent. Gated on `pinned_device` so it runs
428        // on the realize path (which always sets one), matching the prior
429        // bridge behavior; bare-graph test callers without a pin are unaffected.
430        fuel_graph::opt::insert_layout_fixups(graph, roots, |id| {
431            plan.alternatives(id)
432                .and_then(|set| set.winner())
433                .map(|cand| cand.caps.strided_input)
434                .unwrap_or(true)
435        });
436    }
437
438    Ok(OptimizedGraph {
439        roots: roots.to_vec(),
440        generation,
441        placements: resolved_placements,
442        eviction,
443    })
444}
445
446/// Dtype-reconciliation fixup (runs BEFORE `compile_plan`): for any kernel-
447/// bearing node whose per-operand `(op, dtypes)` key is not servable by any
448/// compiled-in backend, insert `Op::Cast`(s) promoting the mismatched input(s)
449/// to the node's OUTPUT dtype — IF that lossless upcast yields a key some backend
450/// DOES support. This is "backends advertise; the optimizer adapts"
451/// ([04-optimization], [05-backend-contract]) applied to dtype, and the sibling
452/// of `insert_layout_fixups` (`Op::Contiguize`) and `insert_residency_copies`
453/// (`Op::Copy`).
454///
455/// It is the non-native-kernel fallback the mixed-precision matmul path already
456/// ASSUMED exists — `vulkan_dispatch`'s matmul route picker documents "otherwise
457/// falls back to f32 matmul (after a Cast)" — but which was never built as a
458/// pass, so a graph builder emitting a mixed `[F32, BF16] → F32` matmul
459/// dead-ended at `NoBackendForOp` on every backend without the native mixed key
460/// (all but Vulkan; and CPU-only default builds have none).
461///
462/// SAFE + CONSERVATIVE: promotes ONLY by a value-LOSSLESS upcast to the output
463/// dtype ([`lossless_upcast`]), so it never changes op semantics (a comparison's
464/// `U8` output is not a lossless upcast target, so comparisons are left alone) and
465/// never corrupts a value.
466///
467/// **NUMERIC CAVEAT:** the upcast is value-lossless but the promoted op is NOT
468/// numerically identical to a native mixed-precision kernel — it accumulates in
469/// the higher precision, so the *same graph* can differ by which arm ran (a CPU
470/// upcast vs a native `[F32,BF16,F32]` kernel; and it already differs
471/// CPU-vs-CUDA). The pass REPORTS every promotion via `tracing` (visibility, per
472/// C-6's "never silently deoptimize"). Making a promoting cast **forbiddable
473/// under a C-5 determinism/tolerance constraint** (so a byte-exact-oracle or
474/// CPU-vs-CUDA-parity consumer gets the native path or a hard fail, not a silent
475/// upcast) and **accounting its extra resident bytes under C-4** (BF16→F32
476/// doubles a weight) are tracked ROADMAP follow-ups.
477///
478/// When no lossless promotion yields a supported key, the node is left unchanged
479/// and fails cleanly at `compile_plan` with the truthful coverage diagnostic — a
480/// genuine gap, surfaced honestly. Returns whether it changed the graph (so the
481/// caller re-derives the execution order).
482///
483/// The broader fix — expanding per-op dtype coverage across kernels (starting
484/// CPU) so fewer combos need reconciling — is a tracked ROADMAP item; this pass
485/// makes the graph builder's mixed-precision promise executable everywhere today.
486fn insert_dtype_fixups(
487    graph: &mut Graph,
488    roots: &[NodeId],
489    bindings: &KernelBindingTable,
490    options: &PlanOptions<'_>,
491) -> bool {
492    let order = topo_order_multi(graph, roots);
493    // Decision only (immutable graph reads): the `(consumer, input, target)` edges
494    // to promote. The mechanical Cast-insert + rewire is
495    // `fuel_graph::opt::insert_cast_fixups` (the dtype-changing sibling of the
496    // layout fixup). Built in topo order ⇒ deterministic cast-node assignment.
497    let mut casts: Vec<(NodeId, NodeId, DType)> = Vec::new();
498
499    for &id in &order {
500        let (op, inputs, out_dtype) = {
501            let node = graph.node(id);
502            (node.op.clone(), node.inputs.clone(), node.dtype)
503        };
504        let op_kind = match crate::pipelined::op_to_op_kind(&op) {
505            Some(k) => k,
506            None => continue, // view / Const / not-dispatched → no binding key
507        };
508        // The exact per-operand key the dispatcher will look up.
509        let native_key = crate::pipelined::build_lookup_dtypes(graph, graph.node(id));
510        // Only reconcile the generic `[in0, in1, …, out]` key shape. Ops whose
511        // key is canonicalized (Concat, WriteSlice*) share a uniform input dtype
512        // by construction, so they never present a mixed-input miss here.
513        if native_key.len() != inputs.len() + 1 {
514            continue;
515        }
516        // The backends THIS node may actually be placed on. Asked via the
517        // planner's own resolver so the two cannot drift: a weaker predicate
518        // here (e.g. "does any registered backend serve it?") lets a backend
519        // the node can never run on suppress the reconciliation the node needs,
520        // and `compile_plan` below then dead-ends at `NoBackendForOp`.
521        let candidates = crate::plan::candidate_backends_for(graph, options, id, graph.node(id));
522        let servable = |key: &[DType]| {
523            candidates
524                .iter()
525                .any(|&backend| bindings.backend_supports(op_kind, key, backend))
526        };
527
528        if servable(&native_key) {
529            continue; // a backend this node can run on serves it natively
530        }
531        // Promotion target = the output dtype ("compute dtype"), taken ONLY when
532        // every input can losslessly upcast to it — else decline.
533        let target = out_dtype;
534        if !inputs
535            .iter()
536            .all(|&i| lossless_upcast(graph.node(i).dtype, target))
537        {
538            continue;
539        }
540        // Uniform promoted key `[target, …, target, out]` (target == out).
541        let promoted_key: Vec<DType> = inputs
542            .iter()
543            .map(|_| target)
544            .chain(std::iter::once(out_dtype))
545            .collect();
546        if promoted_key == native_key {
547            continue; // inputs already == target; nothing to promote
548        }
549        if !servable(&promoted_key) {
550            continue; // the lossless promotion still isn't servable — genuine gap
551        }
552        for &input_id in &inputs {
553            if graph.node(input_id).dtype != target {
554                casts.push((id, input_id, target));
555            }
556        }
557    }
558
559    if casts.is_empty() {
560        return false;
561    }
562    // Visibility (C-6 "fuel never silently deoptimizes without saying so", applied
563    // to precision rather than fusion): a promoting cast is NOT numerically
564    // identical to a native mixed-precision kernel — it accumulates the upcast in
565    // higher precision, so the same graph can diverge by which arm ran (CPU upcast
566    // vs CUDA native mixed) — and it increases the promoted operand's resident
567    // bytes (e.g. BF16→F32 doubles a weight). A byte-exact-oracle or determinism
568    // consumer must be able to SEE it. Reported via `tracing`; forbidding it under
569    // a C-5 constraint + full C-4 cost accounting are tracked ROADMAP follow-ups.
570    tracing::warn!(
571        promoting_casts = casts.len(),
572        "dtype-reconciliation inserted {} promoting Cast(s): a node's per-operand \
573         dtype key had no native kernel on any backend, so input(s) were upcast to \
574         the output dtype. This CHANGES numerics vs a native mixed-precision kernel \
575         and increases resident bytes for the promoted operand(s).",
576        casts.len(),
577    );
578    fuel_graph::opt::insert_cast_fixups(graph, &casts);
579    true
580}
581
582/// Lossless dtype upcast predicate for [`insert_dtype_fixups`] — `true` ONLY for
583/// conversions that preserve every value exactly (identity + float widenings
584/// where the target's exponent AND mantissa cover the source's). Deliberately
585/// conservative: an unlisted pair returns `false`, so the pass declines rather
586/// than risk a lossy or semantics-changing promotion.
587fn lossless_upcast(from: DType, to: DType) -> bool {
588    use DType::*;
589    if from == to {
590        return true;
591    }
592    matches!(
593        (from, to),
594        (BF16, F32) | (BF16, F64) | (F16, F32) | (F16, F64) | (F32, F64)
595    )
596}
597
598/// Commit the plan's per-node winner backend to the graph's
599/// `target_backend` side-table — the optimizer writing its placement
600/// decision into the graph.
601///
602/// Per kernel-bearing node: stamp `winner.backend` if the plan has an
603/// `AlternativeSet` for it, else the pinned device's backend (structural
604/// ops the planner skips — `Op::Copy`/`Op::Move`/`Op::Alloc`/`Op::ZeroFill`
605/// — plus any op without an `OpKind` mapping). `Op::Const`/`Op::Release`/
606/// `Op::Contiguize`/view ops/`Op::Reshape` inherit or don't need a stamp
607/// and are skipped. Always overwrites, so re-optimizing after a
608/// `TopologyChanged` retry re-stamps consistently from the fresh plan.
609fn stamp_plan_backends(
610    graph: &mut Graph,
611    roots: &[NodeId],
612    plan: &ExecutionPlan,
613    pinned_loc: DeviceLocation,
614) {
615    let pinned_backend = location_to_backend_id(pinned_loc);
616    let order = topo_order_multi(graph, roots);
617    for &id in &order {
618        let node = graph.node(id);
619        if matches!(node.op, Op::Const | Op::Release | Op::Contiguize)
620            || node.op.is_view_op()
621            || matches!(node.op, Op::Reshape(_))
622        {
623            continue;
624        }
625        let stamp = plan
626            .alternatives(id)
627            .and_then(|set| set.winner())
628            .map(|c| c.backend)
629            .unwrap_or(pinned_backend);
630        graph.set_target_backend(id, stamp);
631    }
632}
633
634/// Cleanup Step B (residency): the optimizer-side cross-device copy pass —
635/// insert `Op::Copy { target }` on every edge whose producer's resident
636/// location doesn't share a storage substrate with the consumer's placement,
637/// then stamp each inserted copy's `target_backend` with the SOURCE backend
638/// (the pipelined executor's `Op::Copy` convention: the transfer kernel runs
639/// on the backend the bytes come FROM). Was the bridge's
640/// `insert_resident_input_copies`; moved here so the optimizer — not the
641/// realize-time bridge — owns the residency decision and writes it into the
642/// graph.
643///
644/// Placements come from graph-knowable facts only (no realize-time storage):
645/// residency-declaring ops, explicit `Graph::placement` (the bridge converts
646/// cache residency into placement stamps before optimize — cleanup Step B),
647/// the plan winner's device, the `target_backend` stamp (→ pinned), and view
648/// pass-through. Substrate sharing is queried via the process-global
649/// `SystemTopology` (available pre-realize once backends are registered).
650///
651/// Runs after `stamp_plan_backends` (it reads `target_backend`); the re-stamp
652/// sweep below restores the source-backend stamp on copies/moves that the
653/// stamping pass overwrote with the pinned backend.
654/// Returns the effective-placement map it resolved, so the optimizer can hand
655/// it out via [`OptimizedGraph::placement_of`]. The map is the pass's own input
656/// — surfacing it costs nothing and makes the placement decision observable
657/// instead of inferable.
658///
659/// Note the snapshot is taken BEFORE copy insertion (see the `placements`
660/// comment below), which is the right vantage for "where did this node land":
661/// it reports the placement of the original nodes, with the inserted copies
662/// being the consequence rather than part of the answer.
663fn insert_residency_copies(
664    graph: &mut Graph,
665    roots: &[NodeId],
666    plan: &ExecutionPlan,
667    pinned_loc: DeviceLocation,
668    input_residency: Option<&dyn Fn(NodeId) -> Option<DeviceLocation>>,
669) -> HashMap<NodeId, DeviceLocation> {
670    // Step E Phase C, PR C-0: walk the ARM-INCLUSIVE reachable set, not bare
671    // `roots`. A finalized `Op::Branch` is orphaned (its `reconverge_at` reads
672    // arm-0 directly, per the PR-A1 runnability invariant), so a plain
673    // `topo_order_multi(roots)` never reaches it — and therefore never reaches
674    // its non-arm-0 arms. The residency pass MUST stitch inbound cross-device
675    // copies for EVERY surviving arm so the executor can legally re-pick
676    // arm-1+ at runtime by live load (C2): whichever arm it picks, that arm's
677    // device-inputs are already resident. `effective_roots` (the same seeding
678    // the run extractor + route picker use) pulls every Branch's arms into the
679    // walk. On a branchless graph it returns exactly `roots` ⇒ byte-identical.
680    let eff_roots = fuel_graph::effective_roots(graph, roots);
681    let placements = effective_placements(graph, &eff_roots, plan, pinned_loc, input_residency);
682    let topology = SystemTopology::current();
683    // Identical locations short-circuit to `true` BEFORE the topology lookup
684    // (a location trivially shares bytes with itself; `shares_storage` returns
685    // `false` for unknown backends, so without this an unprobed topology would
686    // wrap every same-device edge in a copy).
687    let shares = |a: DeviceLocation, b: DeviceLocation| -> bool {
688        if a == b {
689            return true;
690        }
691        topology.shares_storage(
692            (location_to_backend_id(a), a),
693            (location_to_backend_id(b), b),
694        )
695    };
696    // Hop-count oracle: an edge whose transfer path is `HostStaging` can't
697    // be done as a single `Op::Copy` (no direct device-to-device copy
698    // kernel between distinct GPU substrates — the cross-VENDOR CUDA↔Vulkan
699    // case), so the residency pass routes it through a CPU intermediate as
700    // TWO hops. `SystemTopology::transfer_path` already returns `HostStaging`
701    // for such pairs and `SameDevice` for `a == b`; CPU↔CUDA / CPU↔Vulkan
702    // resolve to a direct path (or the universal host-staging fallback only
703    // when CPU is NOT one of the endpoints), so any CPU-touching edge stays
704    // single-hop. We additionally guard on neither endpoint being CPU: a CPU
705    // intermediate for a CPU-touching edge would be nonsensical (and the
706    // single-hop CPU↔GPU Copy kernels exist and are byte-identical to
707    // today). Same-vendor GPU pairs that don't share storage (e.g. CUDA gpu0
708    // ↔ gpu1) fall back to `HostStaging` too — correctly two-hop, since
709    // there's no direct cross-gpu_id copy kernel today either.
710    let needs_host_staging = |a: DeviceLocation, b: DeviceLocation| -> bool {
711        if a == DeviceLocation::Cpu || b == DeviceLocation::Cpu {
712            return false;
713        }
714        matches!(
715            topology.transfer_path(a, b),
716            fuel_ir::backend::TransferPath::HostStaging
717        )
718    };
719    let inserted = insert_cross_device_copies(
720        graph,
721        &eff_roots,
722        |id| placements.get(&id).copied(),
723        shares,
724        needs_host_staging,
725    );
726    // Source-location resolver for stamping inserted copies. The
727    // `placements` snapshot was computed BEFORE insertion, so it does NOT
728    // contain the freshly-inserted CPU intermediate of a two-hop edge. That
729    // intermediate's placement was written into the graph by the pass
730    // (`set_placement(cpu_id, Cpu)`), so fall back to `graph.placement(src)`
731    // when the snapshot lacks the node — this is what stamps a two-hop's
732    // consumer-side hop with `Cpu` (its bytes come FROM the CPU intermediate,
733    // so its Copy kernel is the CPU `copy_from_cpu_wrapper`).
734    let src_location = |graph: &Graph, src: NodeId| -> Option<DeviceLocation> {
735        placements
736            .get(&src)
737            .copied()
738            .or_else(|| graph.placement(src))
739    };
740    // Stamp the new copies: target_backend = SOURCE backend. The pass only
741    // inserts a copy when the producer's placement resolved to Some.
742    for &copy_id in &inserted {
743        if let Some(&src) = graph.node(copy_id).inputs.first()
744            && let Some(src_loc) = src_location(graph, src)
745        {
746            graph.set_target_backend(copy_id, location_to_backend_id(src_loc));
747        }
748    }
749    // Re-stamp ALL copies/moves with their SOURCE backend — graph rewrites are
750    // sticky and `stamp_plan_backends` just overwrote pre-existing ones (e.g.
751    // realize-root splices) with the pinned backend; the transfer kernel runs
752    // where the bytes come from. The freshly-inserted copies are visited too,
753    // but their input's placement resolves to the same source location, so the
754    // sweep re-applies the identical stamp (idempotent). Copies whose source
755    // placement is absent keep whatever stamp they already have. The two-hop
756    // CPU intermediate's source is the original GPU producer (stamped to that
757    // GPU); the consumer-side hop's source is the CPU intermediate (stamped
758    // Cpu via the `graph.placement` fallback in `src_location`).
759    // Arm-inclusive (C-0): re-walk from the arm-seeded roots so copies just
760    // inserted inside non-arm-0 arms are re-stamped too. The `eff_roots` seed
761    // set (Branch nodes are unchanged by insertion) reaches the fresh arm
762    // copies via the now-rewired arm-input edges.
763    let order = topo_order_multi(graph, &eff_roots);
764    for &id in &order {
765        if !matches!(graph.node(id).op, Op::Copy { .. } | Op::Move { .. }) {
766            continue;
767        }
768        let Some(&src) = graph.node(id).inputs.first() else {
769            continue;
770        };
771        let Some(src_loc) = src_location(graph, src) else {
772            continue;
773        };
774        graph.set_target_backend(id, location_to_backend_id(src_loc));
775    }
776
777    placements
778}
779
780/// Compute every reachable node's *effective placement* for the residency
781/// pass, mirroring the bridge's old `effective_placements`. Priority per node:
782///
783/// 1. **Residency-declaring ops** — `Op::Copy`/`Op::Move`/`Op::Alloc` carry
784///    their output location in the variant (definitional).
785/// 2. **Explicit `Graph::placement`** — set by inserted copies (and any
786///    caller-provided placement hints).
787/// 3. **Input residency** — where a persistent / const input already lives,
788///    supplied by the realize path via `PlanOptions::input_residency`. This is
789///    the only runtime fact, read through the provider closure — the optimizer
790///    never touches the storage itself.
791/// 4. **Plan winner** — a planned node runs on its winner's device.
792/// 5. **Backend stamp** — a node with `target_backend` but no plan entry
793///    (structural ops) follows the pinned device.
794/// 6. **View pass-throughs** — view ops / `Reshape` / `Contiguize` follow
795///    their data input (already resolved; `order` is topological).
796fn effective_placements(
797    g: &Graph,
798    roots: &[NodeId],
799    plan: &ExecutionPlan,
800    pinned_loc: DeviceLocation,
801    input_residency: Option<&dyn Fn(NodeId) -> Option<DeviceLocation>>,
802) -> HashMap<NodeId, DeviceLocation> {
803    let order = topo_order_multi(g, roots);
804    let mut map: HashMap<NodeId, DeviceLocation> = HashMap::with_capacity(order.len());
805    for &id in &order {
806        let node = g.node(id);
807        match node.op {
808            Op::Copy { target } | Op::Move { target } | Op::Alloc { target } => {
809                map.insert(id, target);
810                continue;
811            }
812            _ => {}
813        }
814        if let Some(loc) = g.placement(id) {
815            map.insert(id, loc);
816            continue;
817        }
818        if let Some(loc) = input_residency.and_then(|f| f(id)) {
819            map.insert(id, loc);
820            continue;
821        }
822        if let Some(winner) = plan.alternatives(id).and_then(|set| set.winner()) {
823            map.insert(id, winner.device);
824            continue;
825        }
826        if g.target_backend(id).is_some() {
827            map.insert(id, pinned_loc);
828            continue;
829        }
830        if (node.op.is_view_op() || matches!(node.op, Op::Reshape(_) | Op::Contiguize))
831            && let Some(&loc) = node.inputs.first().and_then(|i| map.get(i))
832        {
833            map.insert(id, loc);
834        }
835    }
836    map
837}
838
839fn location_to_backend_id(loc: DeviceLocation) -> BackendId {
840    match loc {
841        DeviceLocation::Cpu => BackendId::Cpu,
842        DeviceLocation::Cuda { .. } => BackendId::Cuda,
843        DeviceLocation::Vulkan { .. } => BackendId::Vulkan,
844        DeviceLocation::Metal { .. } => BackendId::Metal,
845    }
846}
847
848/// The PR-A4 deliberate-fork pathfinder + the PR-B2 frontier
849/// convergence optimizer now live in [`crate::driver`] as registered
850/// [`crate::driver::Pathfinder`] / [`crate::driver::Optimizer`] impls
851/// ([`crate::driver::PlacementForkPathfinder`] /
852/// [`crate::driver::FrontierConvergenceOptimizer`]). PR-B3 replaced the
853/// hardcoded `seed_placement_fork_branches(...)` call in
854/// [`optimize_graph`] with a lock-step
855/// [`crate::driver::PassRegistry::run_lockstep`] drive over those
856/// registered passes (see the module docs). The pathfinder body is
857/// unchanged — it moved verbatim behind the trait.
858#[cfg(test)]
859mod tests {
860    use super::*;
861    use crate::fused::PrecisionGuarantee;
862    use crate::kernel::{KernelCaps, OpParams, unknown_cost};
863    use fuel_graph::opt::execution_plan;
864    use fuel_graph::{Node, Op};
865    use fuel_ir::dispatch::OpKind;
866    use fuel_ir::probe::BackendId;
867    use fuel_ir::{DType, DeviceLocation, Layout, Result as FuelResult, Shape};
868    use fuel_memory::Storage;
869    use std::sync::{Arc, RwLock};
870
871    fn noop_kernel(
872        _i: &[Arc<RwLock<Storage>>],
873        _o: &mut [Arc<RwLock<Storage>>],
874        _l: &[Layout],
875        _p: &OpParams,
876    ) -> FuelResult<()> {
877        Ok(())
878    }
879
880    fn register_elementwise(table: &mut KernelBindingTable, op: OpKind, n_in: usize) {
881        let mut dtypes = vec![DType::F32; n_in];
882        dtypes.push(DType::F32); // output dtype
883        table.register_full(
884            op,
885            &dtypes,
886            BackendId::Cpu,
887            noop_kernel,
888            KernelCaps::empty(),
889            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
890            unknown_cost,
891        );
892    }
893
894    fn f32_node(g: &mut Graph, op: Op, inputs: Vec<NodeId>) -> NodeId {
895        // No pre-stamp: post-Step-A `optimize_graph` writes `target_backend`
896        // itself, so pre-stamping here is redundant for the tests that run the
897        // optimizer — and it would falsify the `*_stamps_backends_*` tests'
898        // "unstamped before optimize" / "Const leaf not stamped" preconditions.
899        g.push(Node {
900            op,
901            inputs,
902            shape: Shape::from_dims(&[4]),
903            dtype: DType::F32,
904        })
905    }
906
907    /// A representative branchless CPU graph the optimizer can fully
908    /// place: a fan-in (`Add` over two unary chains) feeding a unary
909    /// tail. Every kernel-bearing op has a CPU binding registered. The
910    /// fan-in exercises the run extractor's multi-predecessor boundary,
911    /// so the equivalence holds across more than a single straight
912    /// chain.
913    fn build_branchless_graph(table: &mut KernelBindingTable) -> (Graph, NodeId) {
914        register_elementwise(table, OpKind::ReluElementwise, 1);
915        register_elementwise(table, OpKind::SiluElementwise, 1);
916        register_elementwise(table, OpKind::AddElementwise, 2);
917        register_elementwise(table, OpKind::TanhElementwise, 1);
918
919        let mut g = Graph::new();
920        let a = f32_node(&mut g, Op::Const, vec![]);
921        let a1 = f32_node(&mut g, Op::Relu, vec![a]);
922        let b = f32_node(&mut g, Op::Const, vec![]);
923        let b1 = f32_node(&mut g, Op::Silu, vec![b]);
924        let sum = f32_node(&mut g, Op::Add, vec![a1, b1]);
925        let out = f32_node(&mut g, Op::Tanh, vec![sum]);
926        (g, out)
927    }
928
929    /// ROADMAP row 67 (I1): a graph whose analysed peak exceeds a small budget. `a` is read by `b` early and
930    /// by `c` late, so its longest inactive gap is evictable (the same shape the residency tests use).
931    fn build_over_budget_graph(table: &mut KernelBindingTable) -> (Graph, NodeId) {
932        register_elementwise(table, OpKind::ReluElementwise, 1);
933        register_elementwise(table, OpKind::NegElementwise, 1);
934        register_elementwise(table, OpKind::MulElementwise, 2);
935        register_elementwise(table, OpKind::AddElementwise, 2);
936        let mut g = Graph::new();
937        let a = f32_node(&mut g, Op::Const, vec![]);
938        let b = f32_node(&mut g, Op::Relu, vec![a]);
939        let pad = f32_node(&mut g, Op::Neg, vec![b]);
940        let pad2 = f32_node(&mut g, Op::Neg, vec![pad]);
941        let c = f32_node(&mut g, Op::Mul, vec![pad2, a]);
942        let out = f32_node(&mut g, Op::Add, vec![b, c]);
943        (g, out)
944    }
945
946    fn count_ops(g: &Graph, pred: impl Fn(&Op) -> bool) -> usize {
947        (0..g.len())
948            .filter(|i| pred(&g.node(NodeId(*i)).op))
949            .count()
950    }
951
952    fn peak_bytes(g: &Graph, root: NodeId) -> usize {
953        crate::residency::ResidencyPlanner::analyze(g, &[root]).peak_bytes
954    }
955
956    #[test]
957    fn a_device_budget_below_the_peak_inserts_evict_reload_chains() {
958        let mut table = KernelBindingTable::new();
959        let (mut g, root) = build_over_budget_graph(&mut table);
960        let before = peak_bytes(&g, root);
961        let opts = cpu_opts().with_device_budget_bytes(before - 1);
962        let optimized =
963            optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph under a budget");
964        let outcome = optimized
965            .eviction
966            .as_ref()
967            .expect("a budgeted run reports what the eviction pass did");
968        assert!(
969            !outcome.chains.is_empty(),
970            "the outcome lists the inserted chains"
971        );
972        assert_eq!(outcome.budget_bytes, before - 1);
973        assert!(
974            count_ops(&g, |op| matches!(op, Op::Move { .. })) >= 1,
975            "a budget below the peak must insert an Op::Move eviction"
976        );
977        assert!(
978            count_ops(&g, |op| matches!(op, Op::Copy { .. })) >= 1,
979            "and its reload Op::Copy"
980        );
981        // Not asserted here: a drop in the analysed peak. This graph is pinned to the CPU, and a
982        // spill to the CPU cannot lower CPU residency; that property is pinned in
983        // `residency::tests::today_the_reload_runs_eagerly_so_the_device_peak_does_not_drop`
984        // (which documents that no round lowers the analysed peak until ROADMAP row 67 I3).
985    }
986
987    #[test]
988    fn the_plan_report_names_where_the_budget_came_from() {
989        use crate::device_budget::{BudgetSource, ResolvedBudget};
990        let run = |opts: PlanOptions<'_>| {
991            let mut table = KernelBindingTable::new();
992            let (mut g, root) = build_over_budget_graph(&mut table);
993            optimize_graph(&mut g, &[root], &table, &opts)
994                .expect("optimize_graph")
995                .eviction
996                .expect("a budgeted run reports an outcome")
997        };
998        let mut table = KernelBindingTable::new();
999        let (g, root) = build_over_budget_graph(&mut table);
1000        let budget = peak_bytes(&g, root) - 1;
1001        let resolved = ResolvedBudget {
1002            bytes: budget,
1003            source: BudgetSource::Probed {
1004                available: (budget as u64) * 10 / 9,
1005                fraction: 0.9,
1006            },
1007        };
1008        let from_policy = run(cpu_opts().with_resolved_device_budget(resolved));
1009        assert_eq!(from_policy.budget_bytes, budget);
1010        assert_eq!(from_policy.budget_source, Some(resolved.source));
1011        // Control: a hand-set number carries no source, so the two paths are told apart.
1012        let by_hand = run(cpu_opts().with_device_budget_bytes(budget));
1013        assert_eq!(by_hand.budget_source, None);
1014    }
1015
1016    #[test]
1017    fn no_budget_a_roomy_budget_or_no_pinned_device_leave_the_graph_alone() {
1018        let nodes_of = |opts: &PlanOptions<'_>| {
1019            let mut table = KernelBindingTable::new();
1020            let (mut g, root) = build_over_budget_graph(&mut table);
1021            if opts.pinned_device.is_none() {
1022                // No pinned device: nodes need explicit placements to plan at all.
1023                for i in 0..g.len() {
1024                    g.set_placement(NodeId(i), DeviceLocation::Cpu);
1025                }
1026            }
1027            let optimized = optimize_graph(&mut g, &[root], &table, opts).expect("optimize_graph");
1028            if opts.device_budget_bytes.is_none() {
1029                assert!(optimized.eviction.is_none(), "no budget: no outcome");
1030            }
1031            (g.len(), count_ops(&g, |op| matches!(op, Op::Move { .. })))
1032        };
1033        // Negative control: no budget at all.
1034        assert_eq!(nodes_of(&cpu_opts()).1, 0, "no budget: no eviction");
1035        // A budget the graph already fits.
1036        assert_eq!(
1037            nodes_of(&cpu_opts().with_device_budget_bytes(usize::MAX)).1,
1038            0,
1039            "roomy budget: no eviction"
1040        );
1041        // The pass is gated on a pinned device, like the residency pass it follows.
1042        let unpinned = PlanOptions::new()
1043            .without_cost_population()
1044            .with_device_budget_bytes(1);
1045        assert_eq!(nodes_of(&unpinned).1, 0, "no pinned device: no eviction");
1046        // Node counts match the no-budget run exactly.
1047        assert_eq!(
1048            nodes_of(&cpu_opts()).0,
1049            nodes_of(&cpu_opts().with_device_budget_bytes(usize::MAX)).0
1050        );
1051    }
1052
1053    /// A pure straight-line CPU graph — the simplest no-competing-route
1054    /// case (exactly one run by construction).
1055    fn build_straight_line_graph(table: &mut KernelBindingTable) -> (Graph, NodeId) {
1056        register_elementwise(table, OpKind::ReluElementwise, 1);
1057        register_elementwise(table, OpKind::SiluElementwise, 1);
1058        register_elementwise(table, OpKind::TanhElementwise, 1);
1059
1060        let mut g = Graph::new();
1061        let a = f32_node(&mut g, Op::Const, vec![]);
1062        let b = f32_node(&mut g, Op::Relu, vec![a]);
1063        let c = f32_node(&mut g, Op::Silu, vec![b]);
1064        let d = f32_node(&mut g, Op::Tanh, vec![c]);
1065        (g, d)
1066    }
1067
1068    fn cpu_opts() -> PlanOptions<'static> {
1069        // No cost machinery: A3a only needs placement/validation, not
1070        // ranking. Pin the realize device so every node resolves.
1071        PlanOptions::new()
1072            .without_cost_population()
1073            .with_pinned_device(DeviceLocation::Cpu)
1074    }
1075
1076    /// Cleanup Step A: `optimize_graph` stamps each computational node's
1077    /// chosen backend onto the graph (the optimizer writes its placement
1078    /// decision INTO the graph). On a pinned-CPU straight-line graph every
1079    /// kernel-bearing node is stamped `Cpu`; the leaf `Op::Const` is
1080    /// skipped (it inherits / needs no stamp). When `pinned_device` is
1081    /// unset, no stamping occurs (the bare-graph test contract).
1082    #[test]
1083    fn optimize_graph_stamps_backends_onto_the_graph() {
1084        let mut table = KernelBindingTable::new();
1085        let (mut g, root) = build_straight_line_graph(&mut table);
1086        // a=Const(0), b=Relu(1), c=Silu(2), d=Tanh(3) by construction.
1087        let (a, b, c, d) = (NodeId(0), NodeId(1), NodeId(2), NodeId(3));
1088        assert!(g.target_backend(b).is_none(), "unstamped before optimize");
1089
1090        let _optimized = optimize_graph(&mut g, &[root], &table, &cpu_opts())
1091            .expect("optimize_graph on a straight-line CPU graph");
1092
1093        assert_eq!(
1094            g.target_backend(b),
1095            Some(BackendId::Cpu),
1096            "Relu stamped Cpu"
1097        );
1098        assert_eq!(
1099            g.target_backend(c),
1100            Some(BackendId::Cpu),
1101            "Silu stamped Cpu"
1102        );
1103        assert_eq!(
1104            g.target_backend(d),
1105            Some(BackendId::Cpu),
1106            "Tanh stamped Cpu"
1107        );
1108        assert!(
1109            g.target_backend(a).is_none(),
1110            "Op::Const leaf is not stamped"
1111        );
1112    }
1113
1114    /// `OptimizedGraph::placement_of` makes the placement DECISION observable,
1115    /// so a consumer can check where work landed instead of inferring it from
1116    /// timing (or from `Graph::placement`, which is only level 2 of the six-way
1117    /// resolution and returns `None` for exactly the compute nodes that matter).
1118    ///
1119    /// Two halves, and the second is the **positive control**: an accessor that
1120    /// silently returned `None` for everything would satisfy any test that only
1121    /// asserted `is_none()` on the unpinned path. So the pinned path asserts
1122    /// concrete `Some(Cpu)` values AND a non-empty map — if placement were never
1123    /// captured, that half fails loudly rather than passing vacuously.
1124    #[test]
1125    fn placement_of_observes_the_decision_and_marks_not_computed() {
1126        // --- pinned: the residency pass runs, placements are captured ---
1127        let mut table = KernelBindingTable::new();
1128        let (mut g, root) = build_straight_line_graph(&mut table);
1129        let (_a, b, c, d) = (NodeId(0), NodeId(1), NodeId(2), NodeId(3));
1130
1131        let optimized = optimize_graph(&mut g, &[root], &table, &cpu_opts())
1132            .expect("optimize_graph on a straight-line CPU graph");
1133
1134        assert!(
1135            optimized.has_placements(),
1136            "a pinned device runs the residency pass, so placements must be computed",
1137        );
1138        // POSITIVE CONTROL: concrete values, not merely "not None". An empty or
1139        // never-populated map would fail here instead of passing quietly.
1140        assert_eq!(
1141            optimized.placement_of(b),
1142            Some(DeviceLocation::Cpu),
1143            "Relu placed Cpu"
1144        );
1145        assert_eq!(
1146            optimized.placement_of(c),
1147            Some(DeviceLocation::Cpu),
1148            "Silu placed Cpu"
1149        );
1150        assert_eq!(
1151            optimized.placement_of(d),
1152            Some(DeviceLocation::Cpu),
1153            "Tanh placed Cpu"
1154        );
1155        assert!(
1156            optimized.placements().count() >= 3,
1157            "the map must actually be populated, got {} entries",
1158            optimized.placements().count(),
1159        );
1160
1161        // --- unpinned: the pass is skipped, and that is DISTINGUISHABLE ---
1162        // This is the property that keeps a `None` from being misread as
1163        // "placed nowhere" — the failure mode this accessor exists to prevent.
1164        //
1165        // Device context has to come from SOMEWHERE or `compile_plan` refuses
1166        // outright ("node has no device context — set PlanOptions::pinned_device,
1167        // a graph placement, or the node's target_backend"). So supply it via
1168        // per-node graph placement instead of a pin: the graph optimizes fine,
1169        // but `pinned_device` is unset so the residency pass never runs — which
1170        // is exactly the "optimized successfully, placement not computed" state
1171        // a caller must be able to tell apart from "placed nowhere".
1172        let mut table2 = KernelBindingTable::new();
1173        let (mut g2, root2) = build_straight_line_graph(&mut table2);
1174        for n in [NodeId(0), NodeId(1), NodeId(2), NodeId(3)] {
1175            g2.set_placement(n, DeviceLocation::Cpu);
1176        }
1177        let bare = PlanOptions::new().without_cost_population();
1178        let unpinned = optimize_graph(&mut g2, &[root2], &table2, &bare)
1179            .expect("optimize_graph with graph placements but no pinned device");
1180
1181        assert!(
1182            !unpinned.has_placements(),
1183            "no pinned device => residency pass skipped => placements NOT computed",
1184        );
1185        assert_eq!(
1186            unpinned.placement_of(b),
1187            None,
1188            "and every lookup is None — which `has_placements()` explains as \
1189             'not computed', never 'placed nowhere'",
1190        );
1191    }
1192
1193    /// Dtype-reconciliation declines on the REAL CPU table: the mixed-precision `[F32, BF16, F32]`
1194    /// and `[F32, F16, F32]` matmuls (f32 activation x half weight) are served natively by the CPU
1195    /// kernels `matmul_f32_bf16` / `matmul_f32_f16` (ROADMAP row 34), so `optimize_graph` plans them
1196    /// as they are and inserts no `Cast`: the weight stays half-width instead of being promoted to a
1197    /// resident f32 copy. Before row 34 this test asserted the opposite (a `Cast(F32)` on the
1198    /// weight, the fallback that the local-table tests below still pin for a backend WITHOUT the
1199    /// native key).
1200    #[test]
1201    fn optimize_graph_keeps_mixed_precision_matmul_native_on_cpu() {
1202        for weight in [DType::BF16, DType::F16] {
1203            let bindings = crate::dispatch::global_bindings(); // real populated CPU table
1204            let mut g = Graph::new();
1205            let lhs = g.push(Node {
1206                op: Op::Const,
1207                inputs: vec![],
1208                shape: Shape::from_dims(&[2, 3]),
1209                dtype: DType::F32,
1210            });
1211            let rhs = g.push(Node {
1212                op: Op::Const,
1213                inputs: vec![],
1214                shape: Shape::from_dims(&[3, 2]),
1215                dtype: weight,
1216            });
1217            let mm = g.push(Node {
1218                op: Op::MatMul,
1219                inputs: vec![lhs, rhs],
1220                shape: Shape::from_dims(&[2, 2]),
1221                dtype: DType::F32,
1222            });
1223
1224            optimize_graph(&mut g, &[mm], &bindings, &cpu_opts())
1225                .expect("mixed-precision matmul plans natively on CPU");
1226
1227            assert_eq!(
1228                g.node(mm).inputs,
1229                vec![lhs, rhs],
1230                "{weight:?}: no Cast, the CPU serves [F32, {weight:?}, F32] natively",
1231            );
1232            assert_eq!(g.node(rhs).dtype, weight, "the weight stays {weight:?}");
1233        }
1234    }
1235
1236    fn register_matmul(table: &mut KernelBindingTable, dtypes: &[DType], backend: BackendId) {
1237        table.register_full(
1238            OpKind::MatMul,
1239            dtypes,
1240            backend,
1241            noop_kernel,
1242            KernelCaps::empty(),
1243            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
1244            unknown_cost,
1245        );
1246    }
1247
1248    /// The reconciling `Op::Cast` the pass inserts needs a binding of its own to
1249    /// plan. The production table has these (`(Cpu, Cast, [BF16, F32])`); a
1250    /// hand-built test table must register them explicitly.
1251    fn register_cast(table: &mut KernelBindingTable, from: DType, to: DType, backend: BackendId) {
1252        table.register_full(
1253            OpKind::Cast,
1254            &[from, to],
1255            backend,
1256            noop_kernel,
1257            KernelCaps::empty(),
1258            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
1259            unknown_cost,
1260        );
1261    }
1262
1263    /// `[F32] @ [BF16] -> [F32]` on a graph pinned to `pinned`.
1264    fn mixed_matmul_graph() -> (Graph, NodeId, NodeId, NodeId) {
1265        let mut g = Graph::new();
1266        let lhs = g.push(Node {
1267            op: Op::Const,
1268            inputs: vec![],
1269            shape: Shape::from_dims(&[2, 3]),
1270            dtype: DType::F32,
1271        });
1272        let rhs = g.push(Node {
1273            op: Op::Const,
1274            inputs: vec![],
1275            shape: Shape::from_dims(&[3, 2]),
1276            dtype: DType::BF16,
1277        });
1278        let mm = g.push(Node {
1279            op: Op::MatMul,
1280            inputs: vec![lhs, rhs],
1281            shape: Shape::from_dims(&[2, 2]),
1282            dtype: DType::F32,
1283        });
1284        (g, lhs, rhs, mm)
1285    }
1286
1287    /// **Born-red regression guard: a backend must never break a graph that
1288    /// isn't running on it.**
1289    ///
1290    /// `insert_dtype_fixups` used to guard on `any_backend_supports` — a
1291    /// predicate over the WHOLE binding table that ignores the key's backend
1292    /// component. `compile_plan` enumerates over the node's *candidate
1293    /// placement set*. So when a non-candidate backend owned the only native
1294    /// mixed-dtype kernel, the pass saw "someone serves it", declined to
1295    /// reconcile, and the planner then dead-ended at `NoBackendForOp`.
1296    ///
1297    /// In-tree that surfaced as `--features vulkan` breaking CPU-pinned
1298    /// mixed-precision matmul, because Vulkan happens to be the only backend
1299    /// registering `MatMul[F32, BF16, F32]`. This test builds that situation
1300    /// from a LOCAL table so it reproduces in **every** build configuration —
1301    /// the feature-gated version is why the defect shipped unnoticed.
1302    #[test]
1303    fn dtype_reconciliation_ignores_kernels_on_non_candidate_backends() {
1304        let mut table = KernelBindingTable::new();
1305        // The pinned backend serves only the uniform key...
1306        register_matmul(
1307            &mut table,
1308            &[DType::F32, DType::F32, DType::F32],
1309            BackendId::Cpu,
1310        );
1311        // ...while a backend this graph will never run on owns the mixed key.
1312        register_matmul(
1313            &mut table,
1314            &[DType::F32, DType::BF16, DType::F32],
1315            BackendId::Vulkan,
1316        );
1317        register_cast(&mut table, DType::BF16, DType::F32, BackendId::Cpu);
1318
1319        let (mut g, lhs, rhs, mm) = mixed_matmul_graph();
1320        optimize_graph(&mut g, &[mm], &table, &cpu_opts()).expect(
1321            "CPU-pinned mixed-precision matmul must reconcile via Cast even though \
1322             a NON-candidate backend owns the native mixed kernel",
1323        );
1324
1325        let mm_inputs = g.node(mm).inputs.clone();
1326        assert_eq!(mm_inputs[0], lhs, "lhs (already F32) untouched");
1327        let cast_id = mm_inputs[1];
1328        assert_ne!(cast_id, rhs, "rhs was rewired to a Cast");
1329        assert!(
1330            matches!(g.node(cast_id).op, Op::Cast(DType::F32)),
1331            "rhs cast to F32"
1332        );
1333        assert_eq!(
1334            g.node(cast_id).inputs,
1335            vec![rhs],
1336            "cast reads the original BF16 weight"
1337        );
1338    }
1339
1340    /// The converse guard — the fix must not over-cast. When the node's own
1341    /// candidate backend serves the mixed key natively, reconciliation must
1342    /// decline, so the native mixed-precision kernel is preserved (casting
1343    /// would change numerics and double the promoted operand's bytes).
1344    #[test]
1345    fn dtype_reconciliation_declines_when_the_candidate_backend_serves_it_natively() {
1346        let mut table = KernelBindingTable::new();
1347        register_matmul(
1348            &mut table,
1349            &[DType::F32, DType::BF16, DType::F32],
1350            BackendId::Cpu,
1351        );
1352
1353        let (mut g, lhs, rhs, mm) = mixed_matmul_graph();
1354        optimize_graph(&mut g, &[mm], &table, &cpu_opts()).expect("native mixed kernel plans");
1355
1356        assert_eq!(
1357            g.node(mm).inputs,
1358            vec![lhs, rhs],
1359            "no Cast: the candidate backend has the native mixed kernel",
1360        );
1361    }
1362
1363    /// Multi-device behavior must be PRESERVED, not sacrificed to fix the bug
1364    /// above. When an off-device fallback is admitted, the foreign backend IS
1365    /// a candidate for this node — so its native mixed kernel is reachable and
1366    /// reconciliation must still decline. This is why the fix mirrors the
1367    /// planner's candidate set rather than narrowing to the pinned device.
1368    #[test]
1369    fn dtype_reconciliation_counts_admitted_off_device_fallback_as_a_candidate() {
1370        let mut table = KernelBindingTable::new();
1371        register_matmul(
1372            &mut table,
1373            &[DType::F32, DType::F32, DType::F32],
1374            BackendId::Cpu,
1375        );
1376        register_matmul(
1377            &mut table,
1378            &[DType::F32, DType::BF16, DType::F32],
1379            BackendId::Vulkan,
1380        );
1381
1382        let fallback = |_from: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
1383            vec![(BackendId::Vulkan, DeviceLocation::Vulkan { gpu_id: 0 })]
1384        };
1385        let opts = PlanOptions::new()
1386            .without_cost_population()
1387            .with_pinned_device(DeviceLocation::Cpu)
1388            .with_fallback_placements_for(&fallback);
1389
1390        let (mut g, lhs, rhs, mm) = mixed_matmul_graph();
1391        optimize_graph(&mut g, &[mm], &table, &opts).expect("off-device native mixed kernel plans");
1392
1393        assert_eq!(
1394            g.node(mm).inputs,
1395            vec![lhs, rhs],
1396            "no Cast: the admitted off-device fallback backend serves the mixed key natively",
1397        );
1398    }
1399
1400    /// The stamping is guarded on a pinned device — an `optimize_graph`
1401    /// with no `pinned_device` leaves the graph unstamped (so the bare
1402    /// optimize.rs test callers below are unaffected by Step A).
1403    #[test]
1404    fn optimize_graph_without_pinned_device_does_not_stamp() {
1405        let mut table = KernelBindingTable::new();
1406        let (mut g, root) = build_straight_line_graph(&mut table);
1407        // Give each node a device context via a graph PLACEMENT (a distinct
1408        // side-table from `target_backend`), so `compile_plan` resolves without
1409        // a pinned device — then assert `optimize_graph` performs no
1410        // `target_backend` stamping (the stamping arm is guarded on
1411        // `pinned_device`, so without a pin nothing is stamped).
1412        for id in [NodeId(0), NodeId(1), NodeId(2), NodeId(3)] {
1413            g.set_placement(id, DeviceLocation::Cpu);
1414        }
1415        let opts = PlanOptions::new().without_cost_population(); // no pinned device
1416        let _ = optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph");
1417        assert!(
1418            g.target_backend(NodeId(1)).is_none(),
1419            "no pinned device ⇒ no target_backend stamping",
1420        );
1421    }
1422
1423    /// Cleanup Step B (layout): `optimize_graph` inserts an `Op::Contiguize`
1424    /// before a kernel whose chosen winner rejects strided inputs
1425    /// (`caps.strided_input == false`, e.g. the `KernelCaps::empty()`
1426    /// elementwise bindings) and whose input layout is non-contiguous — the
1427    /// layout-fixup pass moved from the realize-time bridge into the optimizer.
1428    /// The pass itself is exhaustively tested in `fuel-graph::opt`; this guards
1429    /// the optimizer-side wiring (callback reads the plan winner's caps, runs
1430    /// inside the pinned guard).
1431    #[test]
1432    fn optimize_graph_inserts_layout_fixup_for_strided_input() {
1433        let mut table = KernelBindingTable::new();
1434        register_elementwise(&mut table, OpKind::ReluElementwise, 1); // empty caps ⇒ rejects strided
1435        let mut g = Graph::new();
1436        let a = f32_node(&mut g, Op::Const, vec![]);
1437        let r = f32_node(&mut g, Op::Relu, vec![a]);
1438        // Make `a`'s effective layout non-contiguous (non-zero start_offset),
1439        // so the strided-rejecting Relu needs a Contiguize on its input.
1440        g.set_layout(a, Layout::contiguous_with_offset(Shape::from_dims(&[4]), 1));
1441
1442        let _optimized = optimize_graph(&mut g, &[r], &table, &cpu_opts())
1443            .expect("optimize_graph with a strided input");
1444
1445        // Relu's input was `a`; after the fixup it must read through an inserted
1446        // Op::Contiguize wrapping `a`.
1447        let relu_input = g.node(r).inputs[0];
1448        assert!(
1449            matches!(g.node(relu_input).op, Op::Contiguize),
1450            "strided input to a strided-rejecting kernel must be fixed up via \
1451             Op::Contiguize, got {:?}",
1452            g.node(relu_input).op,
1453        );
1454        assert_eq!(
1455            g.node(relu_input).inputs,
1456            vec![a],
1457            "the inserted Op::Contiguize wraps the original strided input",
1458        );
1459    }
1460
1461    // ---- Cleanup Step B (residency) — insert_residency_copies tests ----
1462    // (migrated from the bridge's insert_resident_input_copies unit tests;
1463    // cache residency is supplied via an `input_residency` closure instead of a
1464    // live StorageCache. Placement metadata only — no GPU needed; the unprobed
1465    // test `SystemTopology` reports Cpu/Cuda as non-sharing, so a crossing is
1466    // detected and a copy inserted.)
1467
1468    /// Co-located graph ⇒ `insert_residency_copies` is a no-op (no crossings).
1469    #[test]
1470    fn residency_noop_when_colocated() {
1471        let mut g = Graph::new();
1472        let c1 = f32_node(&mut g, Op::Const, vec![]);
1473        let c2 = f32_node(&mut g, Op::Const, vec![]);
1474        let add = f32_node(&mut g, Op::Add, vec![c1, c2]);
1475        g.set_target_backend(add, BackendId::Cpu);
1476        let residency = |id: NodeId| (id == c1 || id == c2).then_some(DeviceLocation::Cpu);
1477        let pre = g.len();
1478        insert_residency_copies(
1479            &mut g,
1480            &[add],
1481            &ExecutionPlan::empty(),
1482            DeviceLocation::Cpu,
1483            Some(&residency),
1484        );
1485        assert_eq!(g.len(), pre, "co-located graph must be a no-op");
1486        assert_eq!(g.node(add).inputs, vec![c1, c2], "edges untouched");
1487    }
1488
1489    /// A CPU-resident input feeding two CUDA-pinned consumers ⇒ exactly ONE
1490    /// `Op::Copy` bridges the crossing (CSE-deduped), targeting the consumer
1491    /// device, stamped `target_backend = SOURCE` (Cpu, the H2D wrapper) with
1492    /// its output placed on the consumer device.
1493    #[test]
1494    fn residency_one_copy_per_crossing_deduped() {
1495        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
1496        let mut g = Graph::new();
1497        let c1 = f32_node(&mut g, Op::Const, vec![]);
1498        let neg = f32_node(&mut g, Op::Neg, vec![c1]);
1499        let sqr = f32_node(&mut g, Op::Sqr, vec![c1]);
1500        g.set_target_backend(neg, BackendId::Cuda);
1501        g.set_target_backend(sqr, BackendId::Cuda);
1502        let residency = |id: NodeId| (id == c1).then_some(DeviceLocation::Cpu);
1503
1504        let pre = g.len();
1505        insert_residency_copies(
1506            &mut g,
1507            &[neg, sqr],
1508            &ExecutionPlan::empty(),
1509            cuda0,
1510            Some(&residency),
1511        );
1512
1513        assert_eq!(g.len(), pre + 1, "one crossing → one copy, CSE-deduped");
1514        let neg_in = g.node(neg).inputs[0];
1515        let sqr_in = g.node(sqr).inputs[0];
1516        assert_eq!(neg_in, sqr_in, "both consumers share the one copy");
1517        assert_ne!(neg_in, c1, "consumers rewired off the raw input");
1518        let copy = g.node(neg_in);
1519        assert!(
1520            matches!(copy.op, Op::Copy { target } if target == cuda0),
1521            "copy targets the consumer device; got {:?}",
1522            copy.op,
1523        );
1524        assert_eq!(copy.inputs, vec![c1], "copy reads the resident slot");
1525        assert_eq!(
1526            g.target_backend(neg_in),
1527            Some(BackendId::Cpu),
1528            "stamped with the SOURCE backend (H2D runs on the CPU wrapper)",
1529        );
1530        assert_eq!(
1531            g.placement(neg_in),
1532            Some(cuda0),
1533            "copy output placed on the consumer device",
1534        );
1535    }
1536
1537    /// Idempotence + re-stamp: a second pass on the rewritten graph inserts
1538    /// nothing and restores the source-backend stamp even after a clobber
1539    /// (mimicking `stamp_plan_backends` overwriting it with the pinned backend).
1540    #[test]
1541    fn residency_idempotent_and_restamped_on_second_call() {
1542        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
1543        let mut g = Graph::new();
1544        let c1 = f32_node(&mut g, Op::Const, vec![]);
1545        let neg = f32_node(&mut g, Op::Neg, vec![c1]);
1546        g.set_target_backend(neg, BackendId::Cuda);
1547        let residency = |id: NodeId| (id == c1).then_some(DeviceLocation::Cpu);
1548
1549        insert_residency_copies(
1550            &mut g,
1551            &[neg],
1552            &ExecutionPlan::empty(),
1553            cuda0,
1554            Some(&residency),
1555        );
1556        let copy_id = g.node(neg).inputs[0];
1557        // Simulate stamp_plan_backends clobbering the copy with the pinned backend.
1558        g.set_target_backend(copy_id, BackendId::Cuda);
1559
1560        let pre = g.len();
1561        insert_residency_copies(
1562            &mut g,
1563            &[neg],
1564            &ExecutionPlan::empty(),
1565            cuda0,
1566            Some(&residency),
1567        );
1568        assert_eq!(g.len(), pre, "re-run inserts nothing");
1569        assert_eq!(
1570            g.target_backend(copy_id),
1571            Some(BackendId::Cpu),
1572            "re-stamp sweep restores the source-backend stamp",
1573        );
1574    }
1575
1576    // ---- Step E Phase C, PR C-0: arm residency-copy audit ----
1577    //
1578    // C2 lets the executor re-pick an `Op::Branch` arm at runtime by live
1579    // device load — it may choose arm-1+ instead of the static arm-0 winner.
1580    // That is only legal if the optimizer's residency pass has ALREADY
1581    // stitched the inbound cross-device `Op::Copy` for EVERY surviving arm,
1582    // so whichever arm the executor picks, that arm's device-inputs are
1583    // resident on its device. This test builds a 2-arm diamond whose two arms
1584    // live on DIFFERENT devices (arm-0 CPU, arm-1 CUDA) sharing one CPU
1585    // producer, runs the residency pass, and asserts BOTH arms' cross-device
1586    // inputs got their copy — not just arm-0's.
1587    //
1588    // The finalized `Op::Branch` is orphaned (its `reconverge_at` reads arm-0
1589    // directly, per the PR-A1 runnability invariant), so arm-1 is reachable
1590    // ONLY through the Branch node. `insert_residency_copies` walks
1591    // `topo_order_multi(roots)` directly (NOT `effective_roots`), so it never
1592    // reaches an orphaned Branch — and therefore never reaches arm-1. The
1593    // run/route machinery (`extract_runs_multi`, `branches_in_topo_order`)
1594    // does use `effective_roots`; the residency pass does not. This is the
1595    // C-0 prerequisite gap.
1596
1597    /// Build a 2-arm diamond: a CPU producer `diverge` fans into arm-0 (CPU)
1598    /// and arm-1 (`arm1_loc`); `reconverge` reads arm-0 (the runnability
1599    /// invariant); the Branch merges {arm0, arm1} at `reconverge`. Returns
1600    /// `(graph, branch, diverge, arm0, arm1, post)`. Placements are set via
1601    /// `set_placement` so the residency pass reads them with no plan/winner.
1602    fn residency_diamond(
1603        arm1_loc: DeviceLocation,
1604    ) -> (Graph, NodeId, NodeId, NodeId, NodeId, NodeId) {
1605        let mut g = Graph::new();
1606        let pre = f32_node(&mut g, Op::Const, vec![]);
1607        let diverge = f32_node(&mut g, Op::Relu, vec![pre]);
1608        let arm0 = f32_node(&mut g, Op::Silu, vec![diverge]);
1609        let arm1 = f32_node(&mut g, Op::GeluTanh, vec![diverge]);
1610        let reconverge = f32_node(&mut g, Op::Relu, vec![arm0]);
1611        let mut b = g.open_branch(diverge);
1612        b.add_arm(arm0);
1613        b.add_arm(arm1);
1614        let branch = b
1615            .finalize_branches(&mut g, reconverge)
1616            .expect("well-formed 2-arm branch")
1617            .expect("2 arms survive");
1618        let post = f32_node(&mut g, Op::Tanh, vec![reconverge]);
1619        // Producer + arm-0 + the post-merge region on CPU; arm-1 elsewhere.
1620        g.set_placement(pre, DeviceLocation::Cpu);
1621        g.set_placement(diverge, DeviceLocation::Cpu);
1622        g.set_placement(arm0, DeviceLocation::Cpu);
1623        g.set_placement(reconverge, DeviceLocation::Cpu);
1624        g.set_placement(post, DeviceLocation::Cpu);
1625        g.set_placement(arm1, arm1_loc);
1626        (g, branch, diverge, arm0, arm1, post)
1627    }
1628
1629    /// C-0 PREREQUISITE: the residency pass must insert the inbound
1630    /// cross-device `Op::Copy` for BOTH arms of a 2-device branch — arm-0
1631    /// (CPU, same device as the producer ⇒ no copy needed) AND arm-1 (CUDA,
1632    /// crosses ⇒ MUST get a copy). If only arm-0 were stitched, re-picking
1633    /// arm-1 at runtime (C2) would dispatch a CUDA kernel whose input was
1634    /// never copied to the GPU → the un-bridged-mixed-edge error / a UAF.
1635    #[test]
1636    fn residency_stitches_every_branch_arm_not_just_arm0() {
1637        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
1638        let (mut g, _branch, diverge, arm0, arm1, post) = residency_diamond(cuda0);
1639
1640        insert_residency_copies(
1641            &mut g,
1642            &[post],
1643            &ExecutionPlan::empty(),
1644            DeviceLocation::Cpu,
1645            None,
1646        );
1647
1648        // arm-0 is CPU, same substrate as the CPU producer ⇒ its input edge
1649        // does NOT cross ⇒ no copy (and must stay reading `diverge`).
1650        assert_eq!(
1651            g.node(arm0).inputs,
1652            vec![diverge],
1653            "arm-0 is co-located with its producer ⇒ no copy, edge untouched",
1654        );
1655
1656        // arm-1 is CUDA, its producer `diverge` is CPU ⇒ the edge crosses ⇒
1657        // the residency pass MUST have inserted an Op::Copy targeting CUDA on
1658        // arm-1's input. THIS is the C-0 invariant: every surviving arm's
1659        // device-inputs are made resident, not just arm-0's.
1660        let arm1_in = g.node(arm1).inputs[0];
1661        assert_ne!(
1662            arm1_in, diverge,
1663            "arm-1 (CUDA) reads the CPU producer directly — its inbound \
1664             cross-device Op::Copy was NEVER inserted. Re-picking arm-1 at \
1665             runtime (C2) would dispatch a CUDA kernel over un-copied CPU \
1666             bytes. The residency pass stitched only arm-0's route.",
1667        );
1668        let copy = g.node(arm1_in);
1669        assert!(
1670            matches!(copy.op, Op::Copy { target } if target == cuda0),
1671            "arm-1's inbound copy must target CUDA; got {:?}",
1672            copy.op,
1673        );
1674        assert_eq!(
1675            copy.inputs,
1676            vec![diverge],
1677            "arm-1's copy reads the shared CPU producer",
1678        );
1679    }
1680
1681    // ---- PR-A4 deliberate-fork-seed test substrate ----
1682
1683    fn noop_kernel_b(
1684        _i: &[Arc<RwLock<Storage>>],
1685        _o: &mut [Arc<RwLock<Storage>>],
1686        _l: &[Layout],
1687        _p: &OpParams,
1688    ) -> FuelResult<()> {
1689        Ok(())
1690    }
1691
1692    /// Register a CPU AND a (synthetic) CUDA binding for `op` so a node
1693    /// enumerated against both placements gets two viable
1694    /// `(backend, device)` candidates — the genuine placement fork the
1695    /// A4 pathfinder seeds a branch from.
1696    fn register_two_backend(table: &mut KernelBindingTable, op: OpKind, n_in: usize) {
1697        let mut dtypes = vec![DType::F32; n_in];
1698        dtypes.push(DType::F32);
1699        table.register_full(
1700            op,
1701            &dtypes,
1702            BackendId::Cpu,
1703            noop_kernel,
1704            KernelCaps::empty(),
1705            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
1706            unknown_cost,
1707        );
1708        table.register_full(
1709            op,
1710            &dtypes,
1711            BackendId::Cuda,
1712            noop_kernel_b,
1713            KernelCaps::empty(),
1714            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
1715            unknown_cost,
1716        );
1717    }
1718
1719    fn two_backend_placements(dev: DeviceLocation) -> Vec<BackendId> {
1720        if dev == DeviceLocation::Cpu {
1721            vec![BackendId::Cpu, BackendId::Cuda]
1722        } else {
1723            vec![]
1724        }
1725    }
1726
1727    /// Two backends co-located at the realize device, so every
1728    /// kernel-bearing node enumerates ≥2 placements — the multi-backend
1729    /// build the A4 pathfinder forks on. CPU-only builds (one placement
1730    /// per node) never hit this; the equivalence/idempotence gates above
1731    /// cover that.
1732    fn two_backend_opts() -> PlanOptions<'static> {
1733        PlanOptions::new()
1734            .without_cost_population()
1735            .with_pinned_device(DeviceLocation::Cpu)
1736            .with_placements_for_device(&two_backend_placements)
1737    }
1738
1739    /// A graph with a single kernel-bearing node that has a genuine
1740    /// ≥2-placement choice AND exactly one consumer (so it is a
1741    /// deliberate fork, not plain fan-out). Only `fork`'s op (`Silu`) is
1742    /// registered on two backends, so it is the ONLY node with a real
1743    /// ≥2-placement choice — exactly the "most ops are CPU-only, the
1744    /// matmul has cuBLAS too" shape.
1745    ///
1746    /// A long CPU-only `Relu` body surrounds the fork so the single
1747    /// deliberate branch sits far below the fewness threshold (a tiny
1748    /// graph would be all-branch by node count): `c -> body* -> prod ->
1749    /// fork -> tail -> body*`. `prod` is the diverge; `tail` is the
1750    /// reconverge (it reads `fork`).
1751    fn build_single_fork_graph(
1752        table: &mut KernelBindingTable,
1753    ) -> (Graph, NodeId, NodeId, NodeId, NodeId) {
1754        register_elementwise(table, OpKind::ReluElementwise, 1);
1755        register_two_backend(table, OpKind::SiluElementwise, 1); // the fork
1756        register_elementwise(table, OpKind::TanhElementwise, 1);
1757
1758        let mut g = Graph::new();
1759        let mut prev = f32_node(&mut g, Op::Const, vec![]);
1760        // Straight-line CPU body before the fork.
1761        for _ in 0..20 {
1762            prev = f32_node(&mut g, Op::Relu, vec![prev]);
1763        }
1764        let prod = prev; // the diverge (fork's producer)
1765        let fork = f32_node(&mut g, Op::Silu, vec![prod]);
1766        let tail = f32_node(&mut g, Op::Tanh, vec![fork]); // reconverge
1767        // Straight-line CPU body after the reconverge — the realize root
1768        // is the body's tail, so the whole graph is reachable and the
1769        // single fork sits far below the fewness threshold.
1770        let mut prev = tail;
1771        for _ in 0..20 {
1772            prev = f32_node(&mut g, Op::Relu, vec![prev]);
1773        }
1774        let root = prev;
1775        (g, prod, fork, tail, root)
1776    }
1777
1778    /// THE A4 DELIBERATE-FORK GATE (born-red until the pathfinder
1779    /// emits a Branch).
1780    ///
1781    /// (a) A node with two viable `(backend, device)` placements and a
1782    /// single consumer ⇒ `optimize_graph` emits exactly ONE 2-arm
1783    /// `Op::Branch` whose arm-0 is the DP winner, and the result passes
1784    /// the fewness gate.
1785    #[test]
1786    fn deliberate_fork_emits_one_two_arm_branch() {
1787        use fuel_graph::{branch_density, passes_fewness_gate};
1788        let mut table = KernelBindingTable::new();
1789        let (mut g, _prod, fork, _tail, root) = build_single_fork_graph(&mut table);
1790        let opts = two_backend_opts();
1791
1792        let nodes_before = g.len();
1793        let optimized = optimize_graph(&mut g, &[root], &table, &opts)
1794            .expect("optimize_graph succeeds on a 2-placement graph");
1795
1796        // Exactly one Op::Branch in the arena.
1797        assert_eq!(
1798            optimized.branch_count(&g),
1799            1,
1800            "a single genuine placement fork emits exactly one Op::Branch",
1801        );
1802
1803        // It is a 2-arm branch (arm-0 = the winner = `fork`).
1804        let branch_id = (nodes_before..g.len())
1805            .map(NodeId)
1806            .find(|&id| matches!(g.node(id).op, Op::Branch { .. }))
1807            .expect("a Branch node was appended");
1808        let branch = g.node(branch_id);
1809        assert_eq!(branch.inputs.len(), 2, "the branch has exactly two arms");
1810        assert_eq!(
1811            branch.inputs[0], fork,
1812            "arm-0 is the DP winner node (the route realize uses today)",
1813        );
1814        assert_ne!(
1815            branch.inputs[1], fork,
1816            "arm-1 is a distinct (runner-up placement) node",
1817        );
1818
1819        // The fewness gate holds — one branch among many nodes.
1820        assert!(
1821            passes_fewness_gate(&g, root),
1822            "a single deliberate fork passes the fewness gate; density={}",
1823            branch_density(&g, root),
1824        );
1825    }
1826
1827    /// (b) An ordinary DAG fan-out (one result, two distinct consumers)
1828    /// with the SAME 2-placement freedom is NOT flagged as a branch —
1829    /// fan-out is not a decision point.
1830    #[test]
1831    fn plain_fan_out_is_not_a_branch() {
1832        let mut table = KernelBindingTable::new();
1833        // Only the fan-out node's op (`Relu`) is dual-backend, so it is
1834        // the sole ≥2-placement candidate — and it is excluded purely
1835        // because it fans out (two consumers), not because it lacks a
1836        // placement choice. The consumers are CPU-only.
1837        register_two_backend(&mut table, OpKind::ReluElementwise, 1);
1838        register_elementwise(&mut table, OpKind::SiluElementwise, 1);
1839        register_elementwise(&mut table, OpKind::TanhElementwise, 1);
1840        register_elementwise(&mut table, OpKind::AddElementwise, 2);
1841
1842        // `shared` has two distinct consumers (c0, c1) that join at
1843        // `out` — plain fan-out, not a fork — even though it has a real
1844        // 2-placement choice.
1845        let mut g = Graph::new();
1846        let c = f32_node(&mut g, Op::Const, vec![]);
1847        let shared = f32_node(&mut g, Op::Relu, vec![c]);
1848        let c0 = f32_node(&mut g, Op::Silu, vec![shared]);
1849        let c1 = f32_node(&mut g, Op::Tanh, vec![shared]);
1850        let out = f32_node(&mut g, Op::Add, vec![c0, c1]);
1851        let opts = two_backend_opts();
1852
1853        let optimized =
1854            optimize_graph(&mut g, &[out], &table, &opts).expect("optimize_graph succeeds");
1855        assert_eq!(
1856            optimized.branch_count(&g),
1857            0,
1858            "plain fan-out (multiple consumers) is not a deliberate fork",
1859        );
1860        let _ = shared;
1861    }
1862
1863    /// (c) A branched graph realizes correctly via arm-0: the dispatch
1864    /// order follows {pre, arm-0, post} and SKIPS arm-1's run.
1865    #[test]
1866    fn branched_graph_realizes_via_arm0() {
1867        let mut table = KernelBindingTable::new();
1868        let (mut g, prod, fork, tail, root) = build_single_fork_graph(&mut table);
1869        let opts = two_backend_opts();
1870
1871        // Capture the single-route order BEFORE the branch is emitted —
1872        // this is the order realize must reproduce on arm-0.
1873        let pre_order = execution_plan(&g, &[root]);
1874
1875        let optimized =
1876            optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph succeeds");
1877        assert_eq!(optimized.branch_count(&g), 1, "exactly one branch");
1878
1879        // The arm-1 node is the branch's second input — it must NOT
1880        // appear in the arm-0 dispatch order.
1881        let branch_id = (0..g.len())
1882            .map(NodeId)
1883            .find(|&id| matches!(g.node(id).op, Op::Branch { .. }))
1884            .expect("a Branch node exists");
1885        let arm1 = g.node(branch_id).inputs[1];
1886
1887        let order = optimized.dispatch_order(&g);
1888        assert!(
1889            !order.contains(&arm1),
1890            "arm-0 lowering must skip arm-1's run; order={order:?} arm1={arm1:?}",
1891        );
1892        // arm-0 (fork) and the pre/post nodes ARE executed.
1893        assert!(order.contains(&prod), "pre-run (diverge producer) executes");
1894        assert!(order.contains(&fork), "arm-0 (the winner) executes");
1895        assert!(order.contains(&tail), "post-run (reconverge) executes");
1896        assert!(order.contains(&root), "the realize root executes");
1897
1898        // Behavior preserving: arm-0 lowering reproduces exactly the
1899        // pre-branch single-route order (arm-0 = the DP winner = the
1900        // graph realize used before the branch was recorded).
1901        assert_eq!(
1902            order, pre_order,
1903            "arm-0 dispatch order equals the pre-branch single-route order",
1904        );
1905    }
1906
1907    /// Return type of [`cached_env_test_fixture`] — named purely to dodge
1908    /// `clippy::type_complexity`, not because any caller needs the alias.
1909    type CachedEnvTestFixture = (
1910        Arc<RwLock<Graph>>,
1911        crate::pipelined::StorageCache,
1912        OptimizedGraph,
1913        std::sync::OnceLock<Vec<NodeId>>,
1914        Arc<dyn crate::ranker::RuntimeSelector>,
1915        NodeId,
1916    );
1917
1918    /// Shared setup for the two `cached_env_*` tests below: a single-fork
1919    /// graph, a two-backend `OptimizedGraph`, a seeded `StorageCache`, a
1920    /// fresh `order_cache`, and a real (non-stub) `WinnerSelector`.
1921    /// Factored out purely to keep each test under Codacy's method-length
1922    /// bound — no behavior lives here that either test's own body needs to
1923    /// see inline.
1924    fn cached_env_test_fixture() -> CachedEnvTestFixture {
1925        use crate::pipelined::StorageCache;
1926        use crate::ranker::runtime_selector::WinnerSelector;
1927
1928        let mut table = KernelBindingTable::new();
1929        let (mut g, _prod, _fork, _tail, root) = build_single_fork_graph(&mut table);
1930        let opts = two_backend_opts();
1931        let optimized =
1932            optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph succeeds");
1933        assert_eq!(optimized.branch_count(&g), 1, "exactly one branch");
1934
1935        let graph = Arc::new(RwLock::new(g));
1936        let mut cache = StorageCache::new();
1937        cache.insert(
1938            NodeId(0), // the leaf Const build_single_fork_graph pushes first.
1939            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
1940                1.0_f32, 2.0, 3.0, 4.0,
1941            ]))),
1942        );
1943        let order_cache: std::sync::OnceLock<Vec<NodeId>> = std::sync::OnceLock::new();
1944        let selector: Arc<dyn crate::ranker::RuntimeSelector> = Arc::new(WinnerSelector);
1945        (graph, cache, optimized, order_cache, selector, root)
1946    }
1947
1948    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
1949    /// §5), answering the PM's review question directly: on a graph with a
1950    /// REAL `Op::Branch` and a REAL selector (so the executor's picking
1951    /// entry point resolves a genuine pick, not just "no branches to
1952    /// pick"), `realize_with_optimized_picking_cached_env` must route
1953    /// through `OrderSource::Streaming`, NEVER through `OrderSource::Cached`
1954    /// — proven here by checking `order_cache` stays EMPTY across two
1955    /// separate picking realizes, not merely by reading the routing code.
1956    /// This is the stronger property PR review asked for: the fix doesn't
1957    /// need a cache key that "covers the pick" because picked graphs never
1958    /// reach the cache in the first place — `realize_with_optimized_picking_env`'s
1959    /// OWN routing (`streaming_pick_for` returning `Some` whenever a
1960    /// selector is given over a branched graph) already excludes them, and
1961    /// this test is what proves that exclusion actually holds for the
1962    /// cached sibling too, not just the uncached original.
1963    ///
1964    /// `result`/`result2` tolerate `Error::TopologyChanged` as a passing
1965    /// outcome, not just `Ok`: `optimized.generation` is stamped once, from
1966    /// the process-wide `topology_generation()` counter, at `optimize_graph`
1967    /// time above — and that counter is shared by every test in this binary
1968    /// (`register_runtime_kernel`/`extend_global_bindings`'s own doc admits
1969    /// this; see `register_runtime_kernel_into`'s test-only escape hatch).
1970    /// A sibling test registering a runtime-fused kernel between here and
1971    /// either realize call bumps it, and `realize_inner`'s chunk-boundary
1972    /// check (pipelined.rs) deliberately does NOT retry at this layer —
1973    /// only `pipelined_bridge`'s wrapper does (by design, so a low-level
1974    /// `PipelinedExecutor` caller sees the typed error, not a silent stall).
1975    /// A real retry would need a fresh `optimize_graph` call, which would
1976    /// defeat this test's actual subject (whether the same `OptimizedGraph`
1977    /// and `order_cache` stay consistent across repeat calls), so instead
1978    /// of retrying we just don't fail on the one outcome this test was
1979    /// never about. The `order_cache`-emptiness assertions stay
1980    /// unconditional: the `Streaming` path never touches `order_cache`
1981    /// regardless of whether the realize that invoked it succeeded or hit
1982    /// this race.
1983    #[test]
1984    fn cached_env_never_caches_a_branched_graph_with_a_real_selector() {
1985        use crate::PipelinedExecutor;
1986        use fuel_ir::{Error, SymEnv};
1987
1988        let (graph, cache, optimized, order_cache, selector, root) = cached_env_test_fixture();
1989
1990        let result = PipelinedExecutor::realize_with_optimized_picking_cached_env(
1991            graph.clone(),
1992            root,
1993            cache.clone(),
1994            &optimized,
1995            &order_cache,
1996            Some(selector.clone()),
1997            None,
1998            SymEnv::default(),
1999        );
2000        assert!(
2001            result.is_ok() || matches!(result, Err(Error::TopologyChanged { .. })),
2002            "a picked realize over a branched graph must either succeed or hit the \
2003             (unrelated, expected-under-concurrency) TopologyChanged race: {:?}",
2004            result.err()
2005        );
2006        assert!(
2007            order_cache.get().is_none(),
2008            "a branched graph with a real selector pick must NEVER populate order_cache — \
2009             it must route through OrderSource::Streaming, not OrderSource::Cached",
2010        );
2011
2012        // A second call, same cache slot: still must not populate it.
2013        let result2 = PipelinedExecutor::realize_with_optimized_picking_cached_env(
2014            graph,
2015            root,
2016            cache,
2017            &optimized,
2018            &order_cache,
2019            Some(selector),
2020            None,
2021            SymEnv::default(),
2022        );
2023        assert!(
2024            result2.is_ok() || matches!(result2, Err(Error::TopologyChanged { .. })),
2025            "second picked realize must either succeed or hit the same expected-under- \
2026             concurrency TopologyChanged race: {:?}",
2027            result2.err()
2028        );
2029        assert!(
2030            order_cache.get().is_none(),
2031            "order_cache must still be empty after a second picked realize",
2032        );
2033    }
2034
2035    /// Deterministic sibling of the test above: forces the EXACT race
2036    /// `Error::TopologyChanged` tolerance was added for, instead of relying
2037    /// on another test in the binary to collide by chance. Proves two
2038    /// things the flaky-under-`-j4` observation alone couldn't: (1) that a
2039    /// stale `optimized.generation` is SUFFICIENT to reproduce the exact
2040    /// failure this test's sibling hit (confirming the root cause, not
2041    /// just a plausible story), and (2) that `order_cache` stays empty
2042    /// even on the `Err` branch (the property this test file is actually
2043    /// about, independent of the race).
2044    ///
2045    /// Deliberately does NOT call the real, process-wide
2046    /// `bump_topology_generation()` to force this — that would inflict the
2047    /// exact `-j4` cross-test hazard this test documents onto every OTHER
2048    /// concurrently-running test in the binary that assumes a stable
2049    /// generation (an earlier draft of this test did exactly that, and
2050    /// broke `realize_with_optimized_picking_cached_env_matches_arm0_cold_and_warm`
2051    /// under `-j4`). `OptimizedGraph::generation` is `pub`, so mutating
2052    /// this test's own LOCAL copy to a value that can't match the live
2053    /// counter reproduces the identical code path with zero blast radius.
2054    #[test]
2055    fn cached_env_tolerates_a_concurrent_topology_generation_bump() {
2056        use crate::PipelinedExecutor;
2057        use fuel_ir::{Error, SymEnv};
2058
2059        let (graph, cache, mut optimized, order_cache, selector, root) = cached_env_test_fixture();
2060
2061        // Simulate a sibling test's legitimate `register_runtime_kernel`/
2062        // `extend_global_bindings` call landing between `optimize_graph`
2063        // (which stamped `optimized.generation` above) and this realize —
2064        // exactly the collision `cached_env_never_caches_a_branched_graph_with_a_real_selector`
2065        // hit under `-j4` — by staling THIS test's own copy of the stamp,
2066        // not the shared live counter every other test also reads.
2067        optimized.generation = optimized.generation.wrapping_add(1);
2068
2069        let result = PipelinedExecutor::realize_with_optimized_picking_cached_env(
2070            graph,
2071            root,
2072            cache,
2073            &optimized,
2074            &order_cache,
2075            Some(selector),
2076            None,
2077            SymEnv::default(),
2078        );
2079        assert!(
2080            matches!(result, Err(Error::TopologyChanged { .. })),
2081            "a forced generation bump before realize must surface as TopologyChanged, \
2082             not silently succeed or fail some other way: {:?}",
2083            result
2084        );
2085        assert!(
2086            order_cache.get().is_none(),
2087            "order_cache must stay empty even when the realize that would have \
2088             populated it (if it were ever going to) failed with TopologyChanged",
2089        );
2090    }
2091
2092    /// (d) No `DEFAULT_MAX_N` truncation: the fork records the winner +
2093    /// a runner-up without a fixed top-N cap stranding placements. Both
2094    /// arms survive; the per-device frontier — not a fixed N — bounds
2095    /// the arms.
2096    #[test]
2097    fn no_default_max_n_truncation() {
2098        let mut table = KernelBindingTable::new();
2099        let (mut g, _prod, fork, _tail, root) = build_single_fork_graph(&mut table);
2100        let opts = two_backend_opts();
2101
2102        let optimized =
2103            optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph succeeds");
2104        assert_eq!(optimized.branch_count(&g), 1);
2105        let branch_id = (0..g.len())
2106            .map(NodeId)
2107            .find(|&id| matches!(g.node(id).op, Op::Branch { .. }))
2108            .expect("a Branch node exists");
2109        // Two distinct placements ⇒ two arms survive; the runner-up was
2110        // not dropped by any top-N cap.
2111        assert_eq!(g.node(branch_id).inputs.len(), 2);
2112        assert_eq!(g.node(branch_id).inputs[0], fork);
2113    }
2114
2115    /// THE EQUIVALENCE GATE (born-red until `optimize_graph` exists and
2116    /// its lowered order matches `compile_plan`).
2117    ///
2118    /// On representative no-competing-route graphs, assert:
2119    ///   (a) `optimize_graph` leaves ZERO `Op::Branch` nodes, and
2120    ///   (b) the concatenated `extract_runs`/`lower_run` dispatch order
2121    ///       EQUALS today's `compile_plan(...).order` exactly (same
2122    ///       NodeIds, same order).
2123    #[test]
2124    fn equivalence_gate_branchless_order_matches_compile_plan() {
2125        for build in [
2126            build_straight_line_graph as fn(&mut KernelBindingTable) -> (Graph, NodeId),
2127            build_branchless_graph as fn(&mut KernelBindingTable) -> (Graph, NodeId),
2128        ] {
2129            let mut table = KernelBindingTable::new();
2130            let (mut g, root) = build(&mut table);
2131            let opts = cpu_opts();
2132
2133            // Today's path: the exact order the executor walks.
2134            let order = execution_plan(&g, &[root]);
2135            let plan = compile_plan(&g, &order, &table, &opts)
2136                .expect("today's compile_plan succeeds on a placeable graph");
2137
2138            // New path.
2139            let optimized = optimize_graph(&mut g, &[root], &table, &opts)
2140                .expect("optimize_graph succeeds on the same graph");
2141
2142            // (a) zero competing routes => zero Branch nodes.
2143            assert_eq!(
2144                optimized.branch_count(&g),
2145                0,
2146                "a no-competing-route graph optimizes to zero Op::Branch nodes",
2147            );
2148
2149            // (b) EXACT order equality against compile_plan(...).order.
2150            let lowered = optimized.dispatch_order(&g);
2151            assert_eq!(
2152                lowered, plan.order,
2153                "the extract_runs/lower_run dispatch order must equal \
2154                 compile_plan(...).order exactly (same NodeIds, same order)",
2155            );
2156            // And it covers every reachable node — the executor walks
2157            // the whole graph, runs partition it with no gaps/dupes.
2158            assert_eq!(
2159                lowered.len(),
2160                order.len(),
2161                "the lowered order covers every node compile_plan ordered",
2162            );
2163        }
2164    }
2165
2166    /// `optimize_graph` on a branchless graph is idempotent and adds no
2167    /// nodes: the node count is unchanged across repeated calls, the
2168    /// branch count stays zero, and the lowered order is stable.
2169    #[test]
2170    fn optimize_graph_branchless_is_idempotent_and_adds_no_nodes() {
2171        let mut table = KernelBindingTable::new();
2172        let (mut g, root) = build_branchless_graph(&mut table);
2173        let opts = cpu_opts();
2174
2175        let nodes_before = g.len();
2176        let first =
2177            optimize_graph(&mut g, &[root], &table, &opts).expect("first optimize succeeds");
2178        let order_first = first.dispatch_order(&g);
2179        let nodes_after_first = g.len();
2180
2181        let second =
2182            optimize_graph(&mut g, &[root], &table, &opts).expect("second optimize succeeds");
2183        let order_second = second.dispatch_order(&g);
2184        let nodes_after_second = g.len();
2185
2186        assert_eq!(
2187            nodes_before, nodes_after_first,
2188            "optimize_graph adds no nodes (A3a is single-route-only)",
2189        );
2190        assert_eq!(
2191            nodes_after_first, nodes_after_second,
2192            "a second optimize_graph adds no further nodes — idempotent",
2193        );
2194        assert_eq!(first.branch_count(&g), 0, "no branches after first");
2195        assert_eq!(second.branch_count(&g), 0, "no branches after second");
2196        assert_eq!(
2197            order_first, order_second,
2198            "the lowered dispatch order is stable across repeated optimize",
2199        );
2200    }
2201
2202    /// Identity proof for `docs/design/incremental-consumer-index.md` §5's
2203    /// `order_for` fix track: that fix proposes memoizing `dispatch_order`'s
2204    /// output WHOLESALE once per plan-once session, instead of recomputing
2205    /// it (via `extract_runs_multi` + `non_chosen_arm_nodes`, measured
2206    /// ~56ms/step, the single largest named sub-cost in a live decode step)
2207    /// on every `realize_inner` call. That's only valid if calling
2208    /// `dispatch_order` repeatedly on the SAME `OptimizedGraph` view with NO
2209    /// intervening graph mutation — exactly the plan-once decode shape,
2210    /// where only leaf values are rebound between tokens, never the graph's
2211    /// structure — yields a byte-identical `Vec<NodeId>` every time. Proven
2212    /// here, not assumed: five repeated calls, two structurally different
2213    /// branchless graphs (a fan-in boundary and a plain chain), zero
2214    /// mutation between calls (deliberately — this is NOT the existing
2215    /// `optimize_graph_branchless_is_idempotent_and_adds_no_nodes` test
2216    /// above, which re-runs `optimize_graph` itself between its two
2217    /// `dispatch_order` calls; this one proves `dispatch_order` is pure on
2218    /// its own, independent of re-optimizing).
2219    #[test]
2220    fn dispatch_order_is_stable_across_repeated_calls_with_no_mutation() {
2221        for build in [
2222            build_branchless_graph as fn(&mut KernelBindingTable) -> (Graph, NodeId),
2223            build_straight_line_graph,
2224        ] {
2225            let mut table = KernelBindingTable::new();
2226            let (mut g, root) = build(&mut table);
2227            let opts = cpu_opts();
2228            let optimized = optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph");
2229
2230            let orders: Vec<Vec<NodeId>> = (0..5).map(|_| optimized.dispatch_order(&g)).collect();
2231            for (i, order) in orders.iter().enumerate().skip(1) {
2232                assert_eq!(
2233                    &orders[0], order,
2234                    "dispatch_order call {i} diverged from call 0 with no intervening \
2235                     mutation — the order_for memoization fix would be UNSAFE if this failed",
2236                );
2237            }
2238        }
2239    }
2240
2241    /// Build-time validation: optimize_graph fails fast (Result, never
2242    /// panic) when a kernel-bearing node has no registered binding —
2243    /// reusing compile_plan's missing-binding diagnostic.
2244    #[test]
2245    fn optimize_graph_fails_fast_on_missing_binding() {
2246        let table = KernelBindingTable::new(); // empty — no bindings.
2247        let mut g = Graph::new();
2248        let a = f32_node(&mut g, Op::Const, vec![]);
2249        let relu = f32_node(&mut g, Op::Relu, vec![a]);
2250        let opts = cpu_opts();
2251
2252        let err = optimize_graph(&mut g, &[relu], &table, &opts)
2253            .map(|_| ())
2254            .unwrap_err();
2255        match err {
2256            fuel_ir::Error::NoBackendForOp { op, .. } => {
2257                assert_eq!(op, OpKind::ReluElementwise);
2258            }
2259            other => panic!("expected NoBackendForOp, got {other:?}"),
2260        }
2261    }
2262
2263    // ===== Phase B PR-B3: the lock-step pathfinder/ranker/optimizer
2264    //        driver. =====
2265
2266    use crate::driver::{
2267        FrontierConvergenceOptimizer, OptimizationContext, Optimizer, PassRegistry, Pathfinder,
2268        PlacementForkPathfinder,
2269    };
2270    use std::collections::HashSet;
2271
2272    /// Snapshot of a graph's `Op::Branch` decision points, keyed by
2273    /// arena order: `(branch_id, reconverge_at, arm NodeIds)`. Two
2274    /// optimization paths that produce the same snapshot produced the
2275    /// same multi-path graph (behavior-preservation).
2276    fn branch_snapshot(g: &Graph) -> Vec<(NodeId, NodeId, Vec<NodeId>)> {
2277        (0..g.len())
2278            .map(NodeId)
2279            .filter_map(|id| match g.node(id).op {
2280                Op::Branch { reconverge_at } => {
2281                    Some((id, reconverge_at, g.node(id).inputs.clone()))
2282                }
2283                _ => None,
2284            })
2285            .collect()
2286    }
2287
2288    /// THE LOAD-BEARING BEHAVIOR-PRESERVATION GATE (born-red until
2289    /// `optimize_graph` routes through the lock-step driver).
2290    ///
2291    /// On a representative multi-placement graph, the driver
2292    /// (`PassRegistry::default_passes().run_lockstep`) produces the
2293    /// **identical** multi-path graph as the old hardcoded sequence
2294    /// (pathfinder then optimizer, in that order): same branch count,
2295    /// same arm-0 winner, same arms, same reconverge points, and the
2296    /// same arm-0 dispatch order. B3 is a structural refactor — the
2297    /// optimized result must not change.
2298    #[test]
2299    fn driver_matches_legacy_sequence() {
2300        // (A) The reference: drive the registered passes BY HAND in the
2301        //     legacy order (propose, then prune) onto a freshly compiled
2302        //     plan — exactly what the pre-B3 hardcoded sequence did.
2303        let mut ref_table = KernelBindingTable::new();
2304        let (mut ref_g, _prod, ref_fork, _tail, ref_root) = build_single_fork_graph(&mut ref_table);
2305        let opts = two_backend_opts();
2306        let ref_order = execution_plan(&ref_g, &[ref_root]);
2307        let ref_plan = compile_plan(&ref_g, &ref_order, &ref_table, &opts)
2308            .expect("reference compile_plan succeeds");
2309        {
2310            let guard: HashSet<NodeId> = HashSet::new();
2311            let ctx = OptimizationContext {
2312                order: &ref_order,
2313                plan: &ref_plan,
2314                cycle_guard: &guard,
2315                bindings: &ref_table,
2316            };
2317            // Legacy order: the pathfinder ADDs, then the optimizer
2318            // prunes — the same two operations the hardcoded sequence ran.
2319            PlacementForkPathfinder
2320                .propose(&mut ref_g, &ctx)
2321                .expect("pathfinder proposes");
2322            FrontierConvergenceOptimizer
2323                .prune(&mut ref_g, &ctx)
2324                .expect("optimizer prunes");
2325        }
2326        let ref_snapshot = branch_snapshot(&ref_g);
2327        let ref_dispatch = fuel_graph::lower_runs_arm0(&ref_g, &[ref_root]);
2328
2329        // (B) The driver path: optimize_graph routes through
2330        //     PassRegistry::default_passes().run_lockstep.
2331        let mut table = KernelBindingTable::new();
2332        let (mut g, _p, fork, _t, root) = build_single_fork_graph(&mut table);
2333        let optimized =
2334            optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph succeeds");
2335        let got_snapshot = branch_snapshot(&g);
2336        let got_dispatch = optimized.dispatch_order(&g);
2337
2338        // Identical multi-path graph: same branches, arms, reconverge.
2339        assert_eq!(
2340            got_snapshot, ref_snapshot,
2341            "driver produces the identical Op::Branch structure as the legacy \
2342             pathfinder→optimizer sequence",
2343        );
2344        assert_eq!(
2345            got_snapshot.len(),
2346            1,
2347            "the representative multi-placement graph produces exactly one branch",
2348        );
2349        assert_eq!(
2350            got_snapshot[0].2[0], fork,
2351            "arm-0 is the DP winner (the route realize uses)",
2352        );
2353        // Identical dispatch order (arm-0 single-route lowering).
2354        assert_eq!(
2355            got_dispatch, ref_dispatch,
2356            "driver yields the identical arm-0 dispatch order as the legacy sequence",
2357        );
2358        let _ = ref_fork;
2359    }
2360
2361    /// A no-op registry (no registered pathfinders) leaves a branchless
2362    /// graph unchanged: no nodes added, zero branches, identical
2363    /// dispatch order. Proves the driver itself introduces no structure.
2364    #[test]
2365    fn noop_registry_leaves_branchless_graph_unchanged() {
2366        let mut table = KernelBindingTable::new();
2367        let (mut g, root) = build_branchless_graph(&mut table);
2368        let opts = cpu_opts();
2369
2370        let order = execution_plan(&g, &[root]);
2371        let plan = compile_plan(&g, &order, &table, &opts).expect("compile_plan succeeds");
2372
2373        let dispatch_before = fuel_graph::lower_runs_arm0(&g, &[root]);
2374        let nodes_before = g.len();
2375
2376        let registry = PassRegistry::new(); // empty — no passes.
2377        assert_eq!(registry.pathfinder_count(), 0);
2378        assert_eq!(registry.optimizer_count(), 0);
2379
2380        let guard: HashSet<NodeId> = HashSet::new();
2381        let ctx = OptimizationContext {
2382            order: &order,
2383            plan: &plan,
2384            cycle_guard: &guard,
2385            bindings: &table,
2386        };
2387        registry
2388            .run_lockstep(&mut g, &ctx)
2389            .expect("empty registry runs cleanly");
2390
2391        assert_eq!(g.len(), nodes_before, "no-op registry adds no nodes");
2392        let branches = (0..g.len())
2393            .map(NodeId)
2394            .filter(|&id| matches!(g.node(id).op, Op::Branch { .. }))
2395            .count();
2396        assert_eq!(branches, 0, "no-op registry adds no branches");
2397        let dispatch_after = fuel_graph::lower_runs_arm0(&g, &[root]);
2398        assert_eq!(
2399            dispatch_before, dispatch_after,
2400            "no-op registry leaves the dispatch order unchanged",
2401        );
2402    }
2403
2404    /// Lock-step ordering: a pathfinder ADDs before its dependent
2405    /// optimizer PRUNEs. We register a recording pathfinder and a
2406    /// recording optimizer that each stamp a shared log when invoked;
2407    /// `run_lockstep` must invoke the pathfinder strictly before the
2408    /// optimizer (prune-as-you-go, never optimizer-first).
2409    #[test]
2410    fn lockstep_runs_pathfinder_before_dependent_optimizer() {
2411        use std::sync::{Arc, Mutex};
2412
2413        #[derive(Clone)]
2414        struct RecordPathfinder(Arc<Mutex<Vec<&'static str>>>);
2415        impl Pathfinder for RecordPathfinder {
2416            fn name(&self) -> &'static str {
2417                "RecordPathfinder"
2418            }
2419            fn propose(
2420                &self,
2421                _g: &mut Graph,
2422                _ctx: &OptimizationContext<'_>,
2423            ) -> fuel_ir::Result<()> {
2424                self.0.lock().unwrap().push("propose");
2425                Ok(())
2426            }
2427        }
2428        #[derive(Clone)]
2429        struct RecordOptimizer(Arc<Mutex<Vec<&'static str>>>);
2430        impl Optimizer for RecordOptimizer {
2431            fn name(&self) -> &'static str {
2432                "RecordOptimizer"
2433            }
2434            fn prune(&self, _g: &mut Graph, _ctx: &OptimizationContext<'_>) -> fuel_ir::Result<()> {
2435                self.0.lock().unwrap().push("prune");
2436                Ok(())
2437            }
2438        }
2439
2440        let log = Arc::new(Mutex::new(Vec::new()));
2441        let registry = PassRegistry::new()
2442            .with_pathfinder(Box::new(RecordPathfinder(log.clone())))
2443            .with_optimizer(Box::new(RecordOptimizer(log.clone())));
2444
2445        let mut g = Graph::new();
2446        let _a = f32_node(&mut g, Op::Const, vec![]);
2447        let plan = ExecutionPlan::empty();
2448        let order: Vec<NodeId> = Vec::new();
2449        let guard: HashSet<NodeId> = HashSet::new();
2450        let table = KernelBindingTable::new();
2451        let ctx = OptimizationContext {
2452            order: &order,
2453            plan: &plan,
2454            cycle_guard: &guard,
2455            bindings: &table,
2456        };
2457        registry.run_lockstep(&mut g, &ctx).expect("drive runs");
2458
2459        let seq = log.lock().unwrap().clone();
2460        assert_eq!(
2461            seq,
2462            vec!["propose", "prune"],
2463            "lock-step drive runs the pathfinder ADD strictly before its \
2464             dependent optimizer PRUNE (prune-as-you-go)",
2465        );
2466    }
2467
2468    /// **Where does `PagedAttn`'s DECOMPOSED form land on CUDA?** — the
2469    /// measurement that gates whether offering a decomposed arm is worth
2470    /// building, and what to ask Baracuda for.
2471    ///
2472    /// Established already: the FUSED `Op::PagedAttn` node executes on the CPU
2473    /// under CUDA decode (`paged_decode_node_placement_report_cuda`), because
2474    /// no CUDA backend advertises it — so "runs on host" is not a decision the
2475    /// planner made, it is the only move it had. `decompose` exists and is
2476    /// closed-basis, but the planner is never offered it.
2477    ///
2478    /// This asks the question that decides the next build, and it is a
2479    /// GPU-vs-GPU question that the 186× host-ward figure cannot answer —
2480    /// **any** on-device path removes that round-trip equally, so its magnitude
2481    /// says something must be built without saying what:
2482    ///
2483    /// - **every recipe node CUDA-placed** → the round-trip is removable with
2484    ///   NO kernel work at all; the ask to Baracuda may be nothing.
2485    /// - **some primitive falls back to host** → *that primitive* is the ask,
2486    ///   far smaller and better-specified than "paged attention".
2487    ///
2488    /// A grep cannot answer this. I tried: it reported `Permute` in zero
2489    /// CUDA-backend files while the measured placement dump showed
2490    /// `Permute Cuda×6` — it undercounts ops served by generic dispatch. Only
2491    /// the planner's own resolved map settles it.
2492    ///
2493    /// REPORTS rather than asserting a verdict, for the same reason as the
2494    /// fused-node report: pre-committing to an answer is the error being
2495    /// corrected. What it DOES assert is that the instrument ran
2496    /// (`has_placements()`) and that decomposition actually happened (the root
2497    /// moved off the fused node) — an all-`None` dump would read as "nothing
2498    /// is on CUDA", a wrong answer wearing a null answer's clothes.
2499    #[test]
2500    #[ignore = "live GPU (CUDA); run via scripts/gpu-run.ps1"]
2501    #[cfg(feature = "cuda")]
2502    fn paged_attn_decomposed_arm_placement_report_cuda() {
2503        use fuel_graph::registry::{FusedOpParams, FusedOps};
2504        use std::collections::BTreeMap;
2505
2506        const B: usize = 1;
2507        const HQ: usize = 4;
2508        const HKV: usize = 4;
2509        const SQ: usize = 1;
2510        const D: usize = 4;
2511        const NUM_BLOCKS: usize = 32;
2512        const BLOCK_SIZE: usize = 4;
2513        const MAX_BLK: usize = 8;
2514
2515        let mut g = Graph::new();
2516        let leaf = |g: &mut Graph, dims: &[usize], dtype: DType| {
2517            g.push(Node {
2518                op: Op::Const,
2519                inputs: vec![],
2520                shape: Shape::from_dims(dims),
2521                dtype,
2522            })
2523        };
2524        let q = leaf(&mut g, &[B, HQ, SQ, D], DType::F32);
2525        let kc = leaf(&mut g, &[NUM_BLOCKS, BLOCK_SIZE, HKV, D], DType::F32);
2526        let vc = leaf(&mut g, &[NUM_BLOCKS, BLOCK_SIZE, HKV, D], DType::F32);
2527        let bt = leaf(&mut g, &[B, MAX_BLK], DType::U32);
2528        let cl = leaf(&mut g, &[B], DType::U32);
2529
2530        let params = FusedOpParams::PagedAttn {
2531            softmax_scale: 1.0 / (D as f32).sqrt(),
2532            block_size: BLOCK_SIZE,
2533            softcap: None,
2534        };
2535        let fused = g.push(Node {
2536            op: Op::Fused(FusedOps::PAGED_ATTN, params.clone()),
2537            inputs: vec![q, kc, vc, bt, cl],
2538            shape: Shape::from_dims(&[B, HQ, SQ, D]),
2539            dtype: DType::F32,
2540        });
2541
2542        // Lower the fused node to its primitive recipe — the arm the planner is
2543        // never currently offered.
2544        let root = fuel_graph::registry::paged_attn::decompose(&mut g, fused, &params);
2545        assert_ne!(
2546            root, fused,
2547            "PRECONDITION: decompose must actually lower. A self-return is the \
2548             G2 fixpoint signal (malformed node / declined recipe), and every \
2549             placement below would then describe the FUSED node, silently \
2550             answering a different question than the one asked.",
2551        );
2552
2553        // THE PRODUCTION TABLE, not a hand-assembled one. An earlier version of
2554        // this test built the table with `register_cuda_kernels` alone and got
2555        // "no backend supports index_select" — which was an artifact of the
2556        // HARNESS, not a fact about Fuel: that function makes ~5 registrations
2557        // and the bulk of CUDA lives in `register_baracuda_cuda_kernels`, which
2558        // the real path (`register_optional_backends`) also calls, on top of
2559        // `register_cpu_kernels` and a cost fill. Reproducing that assembly by
2560        // hand is precisely the kind of thing that silently drifts, so ask for
2561        // the table the realize path actually uses.
2562        let table = crate::dispatch::global_bindings();
2563
2564        // POSITIVE CONTROL — the instrument must be able to see a CUDA binding
2565        // at all. Without this, an under-populated table reports "no CUDA
2566        // support" for EVERY op, which reads exactly like a real finding: it is
2567        // specific, it names a primitive, and it is completely wrong. That is
2568        // how the first run of this test nearly shipped a false Baracuda ask.
2569        // MatMul is the control because the fuel-core placement report measured
2570        // `MatMul Cuda×15` on a real decode graph — an independently observed
2571        // fact this table must reproduce.
2572        assert!(
2573            table
2574                .lookup(
2575                    OpKind::MatMul,
2576                    &[DType::F32, DType::F32, DType::F32],
2577                    BackendId::Cuda
2578                )
2579                .is_ok(),
2580            "INSTRUMENT BROKEN: the binding table has no CUDA MatMul, so every \
2581             'no CUDA support' conclusion below would be an artifact of the \
2582             harness. Fix the table before reading any verdict from this test.",
2583        );
2584
2585        // ---- THE COMPLETE MISSING-BINDING SET, asked directly ----
2586        //
2587        // `optimize_graph` fails at the FIRST unplaceable node, so driving this
2588        // off its error yields one op per run — a trickle, and each run costs a
2589        // CUDA rebuild. Worse, it conflates two different things: "CUDA has no
2590        // kernel for this op" and "the planner could not place it under THIS
2591        // pin". Asking the binding table per node separates them and returns the
2592        // whole set at once.
2593        let mut missing_cuda: Vec<String> = Vec::new();
2594        let mut present_cuda: Vec<String> = Vec::new();
2595        for i in 0..g.len() {
2596            let id = NodeId(i);
2597            let node = g.node(id);
2598            let Some(kind) = crate::pipelined::op_to_op_kind(&node.op) else {
2599                continue; // Const / view / fused — not a binding-table lookup
2600            };
2601            let mut dtypes: Vec<DType> = node.inputs.iter().map(|&i| g.node(i).dtype).collect();
2602            dtypes.push(node.dtype); // binding key is [inputs.., output]
2603            let sig = format!(
2604                "{kind:?}{:?}",
2605                dtypes.iter().map(|d| format!("{d:?}")).collect::<Vec<_>>()
2606            );
2607            if table.lookup(kind, &dtypes, BackendId::Cuda).is_ok() {
2608                present_cuda.push(sig);
2609            } else {
2610                missing_cuda.push(sig);
2611            }
2612        }
2613        missing_cuda.sort();
2614        missing_cuda.dedup();
2615        present_cuda.sort();
2616        present_cuda.dedup();
2617
2618        println!("\n=== PagedAttn recipe: CUDA binding coverage (asked per node) ===");
2619        println!("PRESENT on CUDA ({}):", present_cuda.len());
2620        for s in &present_cuda {
2621            println!("    {s}");
2622        }
2623        println!("MISSING on CUDA ({}):", missing_cuda.len());
2624        for s in &missing_cuda {
2625            println!("    {s}");
2626        }
2627        // A run where NOTHING resolves would mean the table is empty again — the
2628        // MatMul control above already guards that, but state the invariant that
2629        // makes the "missing" list meaningful rather than vacuous.
2630        assert!(
2631            !present_cuda.is_empty(),
2632            "INSTRUMENT BROKEN: not one recipe node resolved on CUDA, so the \
2633             MISSING list is a property of the lookup, not of the backend",
2634        );
2635        println!(
2636            "\n>>> THE ASK: the {} signature(s) above are what CUDA lacks for the \
2637             §1 dense recipe. Each is a small, named primitive — not \"paged \
2638             attention\".\n",
2639            missing_cuda.len()
2640        );
2641
2642        let opts = PlanOptions::new().with_pinned_device(DeviceLocation::Cuda { gpu_id: 0 });
2643        let optimized = match optimize_graph(&mut g, &[root], &table, &opts) {
2644            Ok(o) => o,
2645            Err(e) => {
2646                println!("\n=== DECOMPOSED ARM DOES NOT PLAN ON CUDA ===");
2647                println!("optimize_graph error: {e:?}");
2648                println!("That is itself the answer: some recipe primitive has no CUDA");
2649                println!("binding, and the error names it. THAT is the Baracuda ask.");
2650                return;
2651            }
2652        };
2653
2654        assert!(
2655            optimized.has_placements(),
2656            "placement NOT COMPUTED — every placement_of would be None and the \
2657             report below would describe the missing instrument, not the graph",
2658        );
2659
2660        let mut by_op: BTreeMap<String, BTreeMap<String, usize>> = BTreeMap::new();
2661        let mut host_ops: Vec<String> = Vec::new();
2662        for i in 0..g.len() {
2663            let id = NodeId(i);
2664            let op_name = match &g.node(id).op {
2665                Op::Fused(fid, _) => format!("Fused({fid:?})"),
2666                other => format!("{other:?}")
2667                    .split(' ')
2668                    .next()
2669                    .unwrap_or("?")
2670                    .to_string(),
2671            };
2672            let place = match optimized.placement_of(id) {
2673                Some(d) => format!("{d:?}"),
2674                None => "None".to_string(),
2675            };
2676            if place.starts_with("Cpu") {
2677                host_ops.push(op_name.clone());
2678            }
2679            *by_op.entry(op_name).or_default().entry(place).or_insert(0) += 1;
2680        }
2681
2682        println!("\n=== PagedAttn DECOMPOSED arm: node placement (CUDA-pinned) ===");
2683        println!(
2684            "total nodes: {} (fused node #{} lowered to root #{})",
2685            g.len(),
2686            fused.0,
2687            root.0
2688        );
2689        for (op, places) in &by_op {
2690            let rendered: Vec<String> = places.iter().map(|(d, n)| format!("{d}×{n}")).collect();
2691            println!("  {op:<40} {}", rendered.join("  "));
2692        }
2693
2694        println!("\n--- VERDICT ---");
2695        if host_ops.is_empty() {
2696            println!(
2697                "EVERY recipe node is off-host. The decomposed paged attention runs \
2698                 ON DEVICE, so the 186x round-trip is removable by OFFERING THIS ARM \
2699                 — no Baracuda kernel required to eliminate it. A kernel would then \
2700                 be a throughput question (the recipe materialises padded capacity, \
2701                 not live context_len), not a round-trip one."
2702            );
2703        } else {
2704            host_ops.sort();
2705            host_ops.dedup();
2706            println!(
2707                "HOST-PLACED recipe primitives: {host_ops:?}\n\
2708                 These are the ask — each is a far smaller and better-specified \
2709                 request than \"paged attention\", and until they exist on device \
2710                 the decomposed arm cannot win."
2711            );
2712        }
2713        println!("--- END VERDICT ---\n");
2714    }
2715}