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::{DType, DeviceLocation, Result};
86
87use crate::driver::{OptimizationContext, PassRegistry};
88use crate::kernel::KernelBindingTable;
89use crate::plan::{ExecutionPlan, PlanOptions, compile_plan};
90use crate::topology::SystemTopology;
91
92/// Round cap for the residency-eviction pass `optimize_graph` runs under a device byte budget
93/// (the legacy rule's default; the pass stops earlier once the budget is met).
94const RESIDENCY_EVICTION_MAX_ROUNDS: usize = 16;
95
96/// The transient *view* [`optimize_graph`] returns — the realize-roots
97/// it optimized for plus the topology generation it ran under. It is
98/// **not** stored on the graph; the optimized form is the graph itself
99/// (with its `Op::Branch` decision points, of which A3a emits none).
100///
101/// The dispatch order is derived on demand from `fuel-graph`'s run
102/// extraction so the run view is always recomputed from the current
103/// arena — never a stale snapshot. This is the shape PR-A3b swaps the
104/// bridge onto in place of `ExecutionPlan::order`.
105#[derive(Debug, Clone)]
106pub struct OptimizedGraph {
107    /// The realize roots this optimization targeted (the same
108    /// `targets` the bridge passes today).
109    pub roots: Vec<NodeId>,
110    /// `SystemTopology` generation snapshotted at optimize time —
111    /// mirrors [`crate::plan::ExecutionPlan::generation`] so a later
112    /// chunk-boundary check can detect a topology shift exactly as
113    /// the executor does today.
114    pub generation: u64,
115    /// Final effective placement per node, as the optimizer resolved it.
116    /// Read via [`OptimizedGraph::placement_of`].
117    ///
118    /// `None` when the residency pass did not run — it is gated on
119    /// `PlanOptions::pinned_device`, which the production realize path always
120    /// sets and bare-graph test callers often do not. `None` therefore means
121    /// **"not computed"**, never "placed nowhere".
122    pub(crate) placements: Option<HashMap<NodeId, DeviceLocation>>,
123    /// What the budgeted eviction pass did (ROADMAP row 67 I1): `Some` only when
124    /// `PlanOptions::device_budget_bytes` was set and a device was pinned. Read
125    /// [`crate::residency::EvictionOutcome::fits`] before trusting that the budget was met: today a same-device
126    /// budget cannot be met (the reload is not delayed), and this says so.
127    pub eviction: Option<crate::residency::EvictionOutcome>,
128}
129
130impl OptimizedGraph {
131    /// Extract the runs of the optimized graph, in topological order
132    /// of their entries (delegates to [`extract_runs_multi`]). A
133    /// branchless, single-residency graph yields exactly one run.
134    pub fn runs(&self, graph: &Graph) -> Vec<fuel_graph::Run> {
135        extract_runs_multi(graph, &self.roots)
136    }
137
138    /// **The device the optimizer decided this node runs on** — the observable
139    /// form of the placement decision, for callers that need to check *where*
140    /// work landed rather than infer it from timing.
141    ///
142    /// This is the resolved *effective* placement, not a hint. It is the same
143    /// map the residency pass uses to decide where to stitch cross-device
144    /// copies, resolved by the priority in `effective_placements`:
145    /// residency-declaring ops → explicit `Graph::placement` → input residency
146    /// → **plan winner** → backend stamp → view pass-through.
147    ///
148    /// **Do not substitute [`fuel_graph::Graph::placement`] for this.** That is
149    /// only *level 2* of the six — a hint set by inserted copies and caller
150    /// overrides. The planner's actual choice for a compute node arrives at
151    /// level 4 ("plan winner"), so `Graph::placement` returns `None` for
152    /// precisely the nodes whose placement is interesting, and reading that
153    /// `None` as "unplaced" is a wrong answer that looks like a null one.
154    ///
155    /// Returns `None` if the node is unknown to this optimization **or** if the
156    /// residency pass did not run (no `pinned_device`; see the field docs) —
157    /// the two are deliberately not distinguished here because neither means
158    /// "placed nowhere". Use [`OptimizedGraph::has_placements`] to tell them
159    /// apart before drawing a conclusion from a `None`.
160    pub fn placement_of(&self, node: NodeId) -> Option<DeviceLocation> {
161        self.placements.as_ref()?.get(&node).copied()
162    }
163
164    /// Whether placement was computed at all. Distinguishes "this node has no
165    /// placement" from "no node does, because the pass was skipped" — the
166    /// difference between a real observation and an absent instrument.
167    pub fn has_placements(&self) -> bool {
168        self.placements.is_some()
169    }
170
171    /// Every resolved `(node, device)` pair, for dumping a whole graph's
172    /// placement. Empty iterator when placement was not computed — check
173    /// [`OptimizedGraph::has_placements`] first if that distinction matters.
174    pub fn placements(&self) -> impl Iterator<Item = (NodeId, DeviceLocation)> + '_ {
175        self.placements
176            .iter()
177            .flat_map(|m| m.iter().map(|(&id, &loc)| (id, loc)))
178    }
179
180    /// The flat executable dispatch order — the **arm-0 single-route
181    /// lowering** (PR-A4). It follows arm 0 through every `Op::Branch`
182    /// (pre-run, arm-0's run, post-run) and **skips every non-arm-0
183    /// arm's run**, via [`fuel_graph::lower_runs_arm0`].
184    ///
185    /// For a graph with **zero `Op::Branch` nodes** this is the exact
186    /// `NodeId` sequence today's executor walks via
187    /// [`crate::plan::compile_plan`]`(...).order` — the equivalence gate
188    /// proves it (no arm to skip ⇒ identical to concatenating
189    /// [`fuel_graph::run::lower_run`] over the runs). For a branched graph it is the
190    /// single-route lowering on **arm 0 = the DP winner** (the route
191    /// realize used before the branch was recorded), so a branched graph
192    /// realizes to the same result. The Phase-C runtime picker is what
193    /// will later select non-arm-0 arms at the decision points.
194    pub fn dispatch_order(&self, graph: &Graph) -> Vec<NodeId> {
195        fuel_graph::lower_runs_arm0(graph, &self.roots)
196    }
197
198    /// The number of `Op::Branch` decision points in the arena. Counting
199    /// over the whole arena (not just the roots' reachable set) is the
200    /// stronger claim. Zero for a single-route graph (CPU-only build, or
201    /// any graph with no genuine ≥2-placement fork); PR-A4's
202    /// deliberate-fork pathfinder emits one per genuine placement fork.
203    pub fn branch_count(&self, graph: &Graph) -> usize {
204        (0..graph.len())
205            .map(NodeId)
206            .filter(|&id| matches!(graph.node(id).op, Op::Branch { .. }))
207            .count()
208    }
209}
210
211/// Optimize `graph` **in place** into the "plan IS the graph" form and
212/// return the transient [`OptimizedGraph`] lowering view.
213///
214/// `roots` are the realize targets (the bridge's `targets`);
215/// `bindings_table` is the kernel registry the placement/cost
216/// machinery queries (production passes [`crate::dispatch::global_bindings`];
217/// tests pass a local table); `opts` is the same [`PlanOptions`] the
218/// bridge builds for `compile_plan`.
219///
220/// ## Behavior
221///
222/// `optimize_graph`:
223///
224/// 1. Derives the dispatch order via `fuel_graph::opt::execution_plan`
225///    — exactly the order the bridge feeds `compile_plan` today
226///    (data-flow topo refined by destructive-op ordering edges).
227/// 2. Drives [`compile_plan`] over that order to **reuse** the
228///    existing placement DP / cost composer / filter chain and to
229///    fail-fast at build time on a missing binding or absent device
230///    context (validate-at-graph-build-time per the working
231///    agreement). Its [`crate::plan::ExecutionPlan`] is a transient
232///    by-product here — the source of truth is the graph.
233/// 3. Runs the PR-A4 deliberate-fork pathfinder
234///    ([`PlacementForkPathfinder`](crate::driver::PlacementForkPathfinder)): records ONE `Op::Branch` per
235///    genuine ≥2-placement fork (arm-0 = winner, arm-1 = runner-up). A
236///    graph with no competing routes gets **zero** branches — it is
237///    already its own single-route plan.
238///
239/// The returned view's [`OptimizedGraph::dispatch_order`] is the arm-0
240/// single-route lowering; for any branchless graph it reproduces
241/// `compile_plan(...).order` exactly — the equivalence gate.
242///
243/// ## The internal `ExecutionPlan` (Step D — no longer returned)
244///
245/// `optimize_graph` drives [`compile_plan`] internally for
246/// placement/cost/validation; the resulting `ExecutionPlan` is a
247/// **transient, optimizer-internal** accumulator the stamp / residency /
248/// layout-fixup passes + the lock-step rankers read below. It is NOT
249/// returned or threaded anywhere — the durable output is the graph's
250/// `target_backend` stamps + `Op::Branch` arms. The executor reads the
251/// graph + re-derives any per-arm candidate from the binding registry at
252/// realize time, so the plan never becomes a dispatch-time authority.
253pub fn optimize_graph(
254    graph: &mut Graph,
255    roots: &[NodeId],
256    bindings_table: &KernelBindingTable,
257    opts: &PlanOptions<'_>,
258) -> Result<OptimizedGraph> {
259    optimize_graph_with_passes(
260        graph,
261        roots,
262        bindings_table,
263        opts,
264        PassRegistry::default_passes(),
265    )
266}
267
268/// [`optimize_graph`] with the runtime-fusion pathfinder registered
269/// ([`PassRegistry::default_passes_with_runtime_fusion`]): adopted (Tier-2 /
270/// JIT-synthesized) fused ops get their gated `Op::Branch` arms emitted before
271/// placement runs. This is the **production realize path's** entry once a
272/// process can adopt runtime kernels; `optimize_graph` stays runtime-op-free so
273/// bare-graph callers and tests never scan the process-global sidecar.
274pub fn optimize_graph_with_runtime_fusion(
275    graph: &mut Graph,
276    roots: &[NodeId],
277    bindings_table: &KernelBindingTable,
278    opts: &PlanOptions<'_>,
279) -> Result<OptimizedGraph> {
280    optimize_graph_with_passes(
281        graph,
282        roots,
283        bindings_table,
284        opts,
285        PassRegistry::default_passes_with_runtime_fusion(),
286    )
287}
288
289fn optimize_graph_with_passes(
290    graph: &mut Graph,
291    roots: &[NodeId],
292    bindings_table: &KernelBindingTable,
293    opts: &PlanOptions<'_>,
294    passes: PassRegistry,
295) -> Result<OptimizedGraph> {
296    // (1) The dispatch order today: data-flow topo refined by ordering
297    //     edges. `compile_plan` copies this verbatim into
298    //     `ExecutionPlan::order`, so it IS the executor's walk order.
299    let mut order = fuel_graph::opt::execution_plan(graph, roots);
300
301    // (1a) GAP-380 (a1): lower a fused op with NO kernel on the pinned device to its primitive recipe
302    //      BEFORE placement, so the recipe's nodes are placed on the device instead of the whole fused
303    //      op landing on the host (a round trip of its device-resident operands every call). Runs first
304    //      because it changes what the planner enumerates; the order is re-derived if it rewrote.
305    if lower_fused_unbound_on_pinned_device(graph, roots, opts, &|id, backend| {
306        crate::fused::default_kernel_registry()
307            .impls_for(id)
308            .iter()
309            .any(|(b, _)| *b == backend)
310    }) > 0
311    {
312        order = fuel_graph::opt::execution_plan(graph, roots);
313    }
314
315    // (2) Reuse the placement/cost/validation machinery. The plan is a
316    //     transient, optimizer-INTERNAL by-product — we drive `compile_plan`
317    //     so the same fail-fast diagnostics (missing binding, no device
318    //     context) fire at optimize time, and so the placement DP / cost
319    //     composer run unchanged. The plan is the working accumulator the
320    //     stamp / residency / layout-fixup passes + the lock-step rankers
321    //     read below; it is NOT returned or threaded (Step D — the graph
322    //     stamps + arms are the only durable output).
323    // (2a) Dtype-reconciliation fixup — insert promoting `Op::Cast`s so a node
324    //      whose per-operand key no compiled-in backend serves natively (e.g. a
325    //      mixed-precision `[F32, BF16, F32]` matmul) becomes servable, instead of
326    //      dead-ending in `compile_plan` below. Runs BEFORE the plan because it
327    //      changes what's enumerable; if it rewrites, re-derive the execution
328    //      order over the mutated graph. The layout/residency fixups are its
329    //      post-plan siblings.
330    let order = if insert_dtype_fixups(graph, roots, bindings_table, opts) {
331        fuel_graph::opt::execution_plan(graph, roots)
332    } else {
333        order
334    };
335
336    let plan = compile_plan(graph, &order, bindings_table, opts)?;
337    let generation = plan.generation;
338
339    // (3) PR-B3: the lock-step pass driver. The pre-B3 hardcoded
340    //     `seed_placement_fork_branches(...)` call is replaced by a
341    //     registry of pathfinders + optimizers run lock-step
342    //     (prune-as-you-go): for each registered pathfinder, ADD its
343    //     candidate paths, then immediately run every registered
344    //     optimizer to MERGE/DISCARD over the region just touched. The
345    //     shipped configuration ([`PassRegistry::default_passes`]) is the
346    //     PR-A4 `PlacementForkPathfinder` (the deliberate-fork seed) +
347    //     the `FrontierConvergenceOptimizer` (duplicate-path convergence
348    //     + the never-strand / no-active-cycle invariant guards) — which
349    //     is exactly the pre-B3 sequence, re-expressed. A CPU-only build
350    //     has one placement per node ⇒ the pathfinder proposes zero
351    //     branches ⇒ today's single-route graph (unchanged).
352    //
353    //     The *ranker* + the PR-B2 per-device Pareto frontier are applied
354    //     per kernel-bearing node *inside* `compile_plan` (the MEASURE +
355    //     per-node PRUNE), and the ranked, frontier-pruned result is the
356    //     `plan` the driver reads via `OptimizationContext::plan`. Batch
357    //     optimize has no executing region, so the cycle guard is empty.
358    let cycle_guard: HashSet<NodeId> = HashSet::new();
359    let ctx = OptimizationContext {
360        order: &order,
361        plan: &plan,
362        cycle_guard: &cycle_guard,
363        bindings: bindings_table,
364    };
365    passes.run_lockstep(graph, &ctx)?;
366
367    // "Plan IS the graph": commit the placement decision INTO the graph's
368    // `target_backend` side-table here, so a fully-optimized graph carries
369    // its own backend stamps and downstream consumers read the graph, not a
370    // threaded plan. Guarded on a pinned device — the production realize
371    // path always sets one (`PlanOptions::with_pinned_device`); bare-graph
372    // test callers that don't are unaffected. (Cleanup Step A: this is
373    // idempotent with the bridge's transitional `stamp_plan_backends`, which
374    // re-stamps the identical result; Step A2 removes the bridge copy.)
375    // Stays `None` when the residency pass below is skipped (no pinned device),
376    // so a caller can tell "not computed" from "no placement" — see
377    // `OptimizedGraph::has_placements`.
378    let mut resolved_placements: Option<HashMap<NodeId, DeviceLocation>> = None;
379    let mut eviction: Option<crate::residency::EvictionOutcome> = None;
380    if let Some(pinned) = opts.pinned_device {
381        stamp_plan_backends(graph, roots, &plan, pinned);
382        // Every node stamped for a backend must have an executor arm there (typed plan-time error
383        // rather than an executor failure mid-run).
384        crate::pipelined::check_direct_arms_wired(graph, roots)?;
385        // Optimize-time kernel-variant bake: resolve **same-device**
386        // kernel-variant branches (a decomposed region vs. a fused kernel on
387        // the SAME device — e.g. the CUDA flash decode arm) to their cost
388        // winner and COLLAPSE them, so the winning variant is selectable
389        // without a runtime pick (04-optimization: kernel-variant choice is
390        // "largely baked at optimize time"). Runs AFTER `stamp_plan_backends`
391        // (the arms now carry `target_backend`, which the same-device gate
392        // reads) and BEFORE `insert_residency_copies` (so the residency pass
393        // stitches inbound copies only for the surviving winner arm, not a
394        // pruned one). A **placement** branch (arms on ≥2 devices) is left
395        // LIVE for the runtime route picker; a graph with no same-device
396        // variant branch — every CPU/Vulkan build today, since no CUDA flash
397        // arm is offered there — is a strict no-op. Ties / unknown costs /
398        // capability-missing default to arm 0 (the decomposed oracle).
399        // The cost provider consults the Judge's MEASURED latency (Layer-2)
400        // FIRST per arm node, falling back to the Layer-1 composite where the
401        // Judge has no cell (the hybrid sum). With `opts.judge == None` this is
402        // byte-identical to the Layer-1-only provider, so the no-Judge path is
403        // unchanged. The same oracle `cost.rs`/`plan.rs` read is threaded here.
404        let judge = opts.judge;
405        crate::variant_bake::bake_variant_branches(graph, roots, &|g, branch, arm, interior| {
406            let backend = g.target_backend(g.node(branch).inputs.first().copied()?)?;
407            crate::variant_bake::decode_arm_composite_ns_judged(
408                g, branch, arm, interior, backend, judge,
409            )
410        });
411        // Cleanup Step B (residency): the optimizer-side cross-device copy pass
412        // (was the bridge's `insert_resident_input_copies`). Runs AFTER stamping
413        // (it reads `target_backend`) and BEFORE layout-fixup, preserving the
414        // prior residency→layout order. Cache residency (where persistent /
415        // const inputs already live) arrives via the `opts.input_residency`
416        // provider the realize path already threads in — the optimizer reads
417        // that fact, it does not touch realize-time storage.
418        // Capture the resolved placement map on the way past — it is the pass's
419        // own input, and surfacing it is what makes `OptimizedGraph::placement_of`
420        // an observation rather than an inference.
421        let placements = insert_residency_copies(graph, roots, &plan, pinned, opts.input_residency);
422        // ROADMAP row 67 (I1): with a device byte budget, evict + reload around the
423        // best candidates while the analysed peak exceeds it. Runs after the copy pass
424        // (it reads the resolved placements) and before layout fixups. No budget = no-op.
425        if let Some(budget) = opts.device_budget_bytes {
426            let mut outcome = crate::residency::insert_residency_evictions_in(
427                graph,
428                roots,
429                pinned,
430                budget,
431                RESIDENCY_EVICTION_MAX_ROUNDS,
432                |id| placements.get(&id).copied(),
433            )?;
434            outcome.budget_source = opts.device_budget_source;
435            eviction = Some(outcome);
436        }
437        resolved_placements = Some(placements);
438        // Cleanup Step B (layout): insert `Op::Contiguize` before any kernel
439        // whose chosen winner rejects strided inputs and whose input layout is
440        // non-contiguous — the optimizer writing the layout-fixup decision INTO
441        // the graph (was the bridge's `apply_layout_fixups`, now retired). No
442        // runtime deps: reads only the in-scope `plan` winner caps + graph
443        // layout. CSE-deduped + idempotent. Gated on `pinned_device` so it runs
444        // on the realize path (which always sets one), matching the prior
445        // bridge behavior; bare-graph test callers without a pin are unaffected.
446        fuel_graph::opt::insert_layout_fixups(graph, roots, |id| {
447            plan.alternatives(id)
448                .and_then(|set| set.winner())
449                .map(|cand| cand.caps.strided_input)
450                .unwrap_or(true)
451        });
452    }
453
454    Ok(OptimizedGraph {
455        roots: roots.to_vec(),
456        generation,
457        placements: resolved_placements,
458        eviction,
459    })
460}
461
462/// Fused ops the optimizer lowers to their primitive recipe when the pinned device has no kernel
463/// for them (GAP-380 / ROADMAP row 149 (a1)). Deliberately a short allowlist: a fused op belongs
464/// here only after the recipe's placement was measured on the device. `PAGED_ATTN`: 25 -> 1
465/// host-placed nodes and 104.8 -> 50.7 ms/token at the mid Llama decode fixture (Fuel 1,
466/// 2026-11-12, n=1, ROADMAP row 149).
467const LOWER_WHEN_NO_DEVICE_KERNEL: &[fuel_graph::registry::FusedOpId] =
468    &[fuel_graph::registry::FusedOps::PAGED_ATTN];
469
470/// Lower every reachable [`LOWER_WHEN_NO_DEVICE_KERNEL`] fused node whose pinned backend has no
471/// kernel (`bound(op, backend)` is false) to its primitive recipe, in place. A no-op unless the
472/// pinned device is CUDA (the measured case; a CPU or Vulkan pin keeps the fused host kernel).
473/// Returns the number of nodes lowered; reported through `tracing` so a deoptimization is visible
474/// (C-6: fuel never changes a plan silently).
475///
476/// Not a numerics-neutral swap: the recipe computes the attention in the primitives' dtype order,
477/// so a consumer that needs the fused kernel's exact bits must pin a backend that has one.
478fn lower_fused_unbound_on_pinned_device(
479    graph: &mut Graph,
480    roots: &[NodeId],
481    opts: &PlanOptions<'_>,
482    bound: &dyn Fn(fuel_graph::registry::FusedOpId, fuel_ir::probe::BackendId) -> bool,
483) -> usize {
484    let Some(pinned) = opts.pinned_device else {
485        return 0;
486    };
487    let backend = pinned.backend();
488    if backend != fuel_ir::probe::BackendId::Cuda {
489        return 0;
490    }
491    let lowered = fuel_graph::opt::lower_selected_fused(graph, roots, &|g, id| {
492        matches!(&g.node(id).op, Op::Fused(fid, _)
493            if LOWER_WHEN_NO_DEVICE_KERNEL.contains(fid) && !bound(*fid, backend))
494    });
495    if lowered > 0 {
496        tracing::info!(
497            lowered,
498            "GAP-380: lowered {lowered} fused node(s) with no {backend:?} kernel to their primitive              recipe so they place on the pinned device instead of the host"
499        );
500    }
501    lowered
502}
503
504/// Dtype-reconciliation fixup (runs BEFORE `compile_plan`): for any kernel-
505/// bearing node whose per-operand `(op, dtypes)` key is not servable by any
506/// compiled-in backend, insert `Op::Cast`(s) promoting the mismatched input(s)
507/// to the node's OUTPUT dtype — IF that lossless upcast yields a key some backend
508/// DOES support. This is "backends advertise; the optimizer adapts"
509/// ([04-optimization], [05-backend-contract]) applied to dtype, and the sibling
510/// of `insert_layout_fixups` (`Op::Contiguize`) and `insert_residency_copies`
511/// (`Op::Copy`).
512///
513/// It is the non-native-kernel fallback the mixed-precision matmul path already
514/// ASSUMED exists — `vulkan_dispatch`'s matmul route picker documents "otherwise
515/// falls back to f32 matmul (after a Cast)" — but which was never built as a
516/// pass, so a graph builder emitting a mixed `[F32, BF16] → F32` matmul
517/// dead-ended at `NoBackendForOp` on every backend without the native mixed key
518/// (all but Vulkan; and CPU-only default builds have none).
519///
520/// SAFE + CONSERVATIVE: promotes ONLY by a value-LOSSLESS upcast to the output
521/// dtype ([`lossless_upcast`]), so it never changes op semantics (a comparison's
522/// `U8` output is not a lossless upcast target, so comparisons are left alone) and
523/// never corrupts a value.
524///
525/// **NUMERIC CAVEAT:** the upcast is value-lossless but the promoted op is NOT
526/// numerically identical to a native mixed-precision kernel — it accumulates in
527/// the higher precision, so the *same graph* can differ by which arm ran (a CPU
528/// upcast vs a native `[F32,BF16,F32]` kernel; and it already differs
529/// CPU-vs-CUDA). The pass REPORTS every promotion via `tracing` (visibility, per
530/// C-6's "never silently deoptimize"). Making a promoting cast **forbiddable
531/// under a C-5 determinism/tolerance constraint** (so a byte-exact-oracle or
532/// CPU-vs-CUDA-parity consumer gets the native path or a hard fail, not a silent
533/// upcast) and **accounting its extra resident bytes under C-4** (BF16→F32
534/// doubles a weight) are tracked ROADMAP follow-ups.
535///
536/// When no lossless promotion yields a supported key, the node is left unchanged
537/// and fails cleanly at `compile_plan` with the truthful coverage diagnostic — a
538/// genuine gap, surfaced honestly. Returns whether it changed the graph (so the
539/// caller re-derives the execution order).
540///
541/// The broader fix — expanding per-op dtype coverage across kernels (starting
542/// CPU) so fewer combos need reconciling — is a tracked ROADMAP item; this pass
543/// makes the graph builder's mixed-precision promise executable everywhere today.
544fn insert_dtype_fixups(
545    graph: &mut Graph,
546    roots: &[NodeId],
547    bindings: &KernelBindingTable,
548    options: &PlanOptions<'_>,
549) -> bool {
550    let order = topo_order_multi(graph, roots);
551    // Decision only (immutable graph reads): the `(consumer, input, target)` edges
552    // to promote. The mechanical Cast-insert + rewire is
553    // `fuel_graph::opt::insert_cast_fixups` (the dtype-changing sibling of the
554    // layout fixup). Built in topo order ⇒ deterministic cast-node assignment.
555    let mut casts: Vec<(NodeId, NodeId, DType)> = Vec::new();
556
557    for &id in &order {
558        let (op, inputs, out_dtype) = {
559            let node = graph.node(id);
560            (node.op.clone(), node.inputs.clone(), node.dtype)
561        };
562        let op_kind = match crate::pipelined::op_to_op_kind(&op) {
563            Some(k) => k,
564            None => continue, // view / Const / not-dispatched → no binding key
565        };
566        // The exact per-operand key the dispatcher will look up.
567        let native_key = crate::pipelined::build_lookup_dtypes(graph, graph.node(id));
568        // Only reconcile the generic `[in0, in1, …, out]` key shape. Ops whose
569        // key is canonicalized (Concat, WriteSlice*) share a uniform input dtype
570        // by construction, so they never present a mixed-input miss here.
571        if native_key.len() != inputs.len() + 1 {
572            continue;
573        }
574        // The backends THIS node may actually be placed on. Asked via the
575        // planner's own resolver so the two cannot drift: a weaker predicate
576        // here (e.g. "does any registered backend serve it?") lets a backend
577        // the node can never run on suppress the reconciliation the node needs,
578        // and `compile_plan` below then dead-ends at `NoBackendForOp`.
579        let candidates = crate::plan::candidate_backends_for(graph, options, id, graph.node(id));
580        let servable = |key: &[DType]| {
581            candidates
582                .iter()
583                .any(|&backend| bindings.backend_supports(op_kind, key, backend))
584        };
585
586        if servable(&native_key) {
587            continue; // a backend this node can run on serves it natively
588        }
589        // Promotion target = the output dtype ("compute dtype"), taken ONLY when
590        // every input can losslessly upcast to it — else decline.
591        let target = out_dtype;
592        if !inputs
593            .iter()
594            .all(|&i| lossless_upcast(graph.node(i).dtype, target))
595        {
596            continue;
597        }
598        // Uniform promoted key `[target, …, target, out]` (target == out).
599        let promoted_key: Vec<DType> = inputs
600            .iter()
601            .map(|_| target)
602            .chain(std::iter::once(out_dtype))
603            .collect();
604        if promoted_key == native_key {
605            continue; // inputs already == target; nothing to promote
606        }
607        if !servable(&promoted_key) {
608            continue; // the lossless promotion still isn't servable — genuine gap
609        }
610        for &input_id in &inputs {
611            if graph.node(input_id).dtype != target {
612                casts.push((id, input_id, target));
613            }
614        }
615    }
616
617    if casts.is_empty() {
618        return false;
619    }
620    // Visibility (C-6 "fuel never silently deoptimizes without saying so", applied
621    // to precision rather than fusion): a promoting cast is NOT numerically
622    // identical to a native mixed-precision kernel — it accumulates the upcast in
623    // higher precision, so the same graph can diverge by which arm ran (CPU upcast
624    // vs CUDA native mixed) — and it increases the promoted operand's resident
625    // bytes (e.g. BF16→F32 doubles a weight). A byte-exact-oracle or determinism
626    // consumer must be able to SEE it. Reported via `tracing`; forbidding it under
627    // a C-5 constraint + full C-4 cost accounting are tracked ROADMAP follow-ups.
628    tracing::warn!(
629        promoting_casts = casts.len(),
630        "dtype-reconciliation inserted {} promoting Cast(s): a node's per-operand \
631         dtype key had no native kernel on any backend, so input(s) were upcast to \
632         the output dtype. This CHANGES numerics vs a native mixed-precision kernel \
633         and increases resident bytes for the promoted operand(s).",
634        casts.len(),
635    );
636    fuel_graph::opt::insert_cast_fixups(graph, &casts);
637    true
638}
639
640/// Lossless dtype upcast predicate for [`insert_dtype_fixups`] — `true` ONLY for
641/// conversions that preserve every value exactly (identity + float widenings
642/// where the target's exponent AND mantissa cover the source's). Deliberately
643/// conservative: an unlisted pair returns `false`, so the pass declines rather
644/// than risk a lossy or semantics-changing promotion.
645fn lossless_upcast(from: DType, to: DType) -> bool {
646    use DType::*;
647    if from == to {
648        return true;
649    }
650    matches!(
651        (from, to),
652        (BF16, F32) | (BF16, F64) | (F16, F32) | (F16, F64) | (F32, F64)
653    )
654}
655
656/// Commit the plan's per-node winner backend to the graph's
657/// `target_backend` side-table — the optimizer writing its placement
658/// decision into the graph.
659///
660/// Per kernel-bearing node: stamp `winner.backend` if the plan has an
661/// `AlternativeSet` for it, else the pinned device's backend (structural
662/// ops the planner skips — `Op::Copy`/`Op::Move`/`Op::Alloc`/`Op::ZeroFill`
663/// — plus any op without an `OpKind` mapping). `Op::Const`/`Op::Release`/
664/// `Op::Contiguize`/view ops/`Op::Reshape` inherit or don't need a stamp
665/// and are skipped. Always overwrites, so re-optimizing after a
666/// `TopologyChanged` retry re-stamps consistently from the fresh plan.
667fn stamp_plan_backends(
668    graph: &mut Graph,
669    roots: &[NodeId],
670    plan: &ExecutionPlan,
671    pinned_loc: DeviceLocation,
672) {
673    let pinned_backend = pinned_loc.backend();
674    let order = topo_order_multi(graph, roots);
675    for &id in &order {
676        let node = graph.node(id);
677        if matches!(node.op, Op::Const | Op::Release | Op::Contiguize)
678            || node.op.is_view_op()
679            || matches!(node.op, Op::Reshape(_))
680        {
681            continue;
682        }
683        let stamp = plan
684            .alternatives(id)
685            .and_then(|set| set.winner())
686            .map(|c| c.backend)
687            .unwrap_or(pinned_backend);
688        graph.set_target_backend(id, stamp);
689    }
690}
691
692/// Cleanup Step B (residency): the optimizer-side cross-device copy pass —
693/// insert `Op::Copy { target }` on every edge whose producer's resident
694/// location doesn't share a storage substrate with the consumer's placement,
695/// then stamp each inserted copy's `target_backend` with the SOURCE backend
696/// (the pipelined executor's `Op::Copy` convention: the transfer kernel runs
697/// on the backend the bytes come FROM). Was the bridge's
698/// `insert_resident_input_copies`; moved here so the optimizer — not the
699/// realize-time bridge — owns the residency decision and writes it into the
700/// graph.
701///
702/// Placements come from graph-knowable facts only (no realize-time storage):
703/// residency-declaring ops, explicit `Graph::placement` (the bridge converts
704/// cache residency into placement stamps before optimize — cleanup Step B),
705/// the plan winner's device, the `target_backend` stamp (→ pinned), and view
706/// pass-through. Substrate sharing is queried via the process-global
707/// `SystemTopology` (available pre-realize once backends are registered).
708///
709/// Runs after `stamp_plan_backends` (it reads `target_backend`); the re-stamp
710/// sweep below restores the source-backend stamp on copies/moves that the
711/// stamping pass overwrote with the pinned backend.
712/// Returns the effective-placement map it resolved, so the optimizer can hand
713/// it out via [`OptimizedGraph::placement_of`]. The map is the pass's own input
714/// — surfacing it costs nothing and makes the placement decision observable
715/// instead of inferable.
716///
717/// Note the snapshot is taken BEFORE copy insertion (see the `placements`
718/// comment below), which is the right vantage for "where did this node land":
719/// it reports the placement of the original nodes, with the inserted copies
720/// being the consequence rather than part of the answer.
721pub(crate) fn insert_residency_copies(
722    graph: &mut Graph,
723    roots: &[NodeId],
724    plan: &ExecutionPlan,
725    pinned_loc: DeviceLocation,
726    input_residency: Option<&dyn Fn(NodeId) -> Option<DeviceLocation>>,
727) -> HashMap<NodeId, DeviceLocation> {
728    // Step E Phase C, PR C-0: walk the ARM-INCLUSIVE reachable set, not bare
729    // `roots`. A finalized `Op::Branch` is orphaned (its `reconverge_at` reads
730    // arm-0 directly, per the PR-A1 runnability invariant), so a plain
731    // `topo_order_multi(roots)` never reaches it — and therefore never reaches
732    // its non-arm-0 arms. The residency pass MUST stitch inbound cross-device
733    // copies for EVERY surviving arm so the executor can legally re-pick
734    // arm-1+ at runtime by live load (C2): whichever arm it picks, that arm's
735    // device-inputs are already resident. `effective_roots` (the same seeding
736    // the run extractor + route picker use) pulls every Branch's arms into the
737    // walk. On a branchless graph it returns exactly `roots` ⇒ byte-identical.
738    let eff_roots = fuel_graph::effective_roots(graph, roots);
739    let placements = effective_placements(graph, &eff_roots, plan, pinned_loc, input_residency);
740    let topology = SystemTopology::current();
741    // Identical locations short-circuit to `true` BEFORE the topology lookup
742    // (a location trivially shares bytes with itself; `shares_storage` returns
743    // `false` for unknown backends, so without this an unprobed topology would
744    // wrap every same-device edge in a copy).
745    let shares = |a: DeviceLocation, b: DeviceLocation| -> bool {
746        if a == b {
747            return true;
748        }
749        topology.shares_storage((a.backend(), a), (b.backend(), b))
750    };
751    // Hop-count oracle: an edge whose transfer path is `HostStaging` can't
752    // be done as a single `Op::Copy` (no direct device-to-device copy
753    // kernel between distinct GPU substrates — the cross-VENDOR CUDA↔Vulkan
754    // case), so the residency pass routes it through a CPU intermediate as
755    // TWO hops. `SystemTopology::transfer_path` already returns `HostStaging`
756    // for such pairs and `SameDevice` for `a == b`; CPU↔CUDA / CPU↔Vulkan
757    // resolve to a direct path (or the universal host-staging fallback only
758    // when CPU is NOT one of the endpoints), so any CPU-touching edge stays
759    // single-hop. We additionally guard on neither endpoint being CPU: a CPU
760    // intermediate for a CPU-touching edge would be nonsensical (and the
761    // single-hop CPU↔GPU Copy kernels exist and are byte-identical to
762    // today). Same-vendor GPU pairs that don't share storage (e.g. CUDA gpu0
763    // ↔ gpu1) fall back to `HostStaging` too — correctly two-hop, since
764    // there's no direct cross-gpu_id copy kernel today either.
765    let needs_host_staging = |a: DeviceLocation, b: DeviceLocation| -> bool {
766        if a == DeviceLocation::Cpu || b == DeviceLocation::Cpu {
767            return false;
768        }
769        matches!(
770            topology.transfer_path(a, b),
771            fuel_ir::backend::TransferPath::HostStaging
772        )
773    };
774    let inserted = insert_cross_device_copies(
775        graph,
776        &eff_roots,
777        |id| placements.get(&id).copied(),
778        shares,
779        needs_host_staging,
780    );
781    // Source-location resolver for stamping inserted copies. The
782    // `placements` snapshot was computed BEFORE insertion, so it does NOT
783    // contain the freshly-inserted CPU intermediate of a two-hop edge. That
784    // intermediate's placement was written into the graph by the pass
785    // (`set_placement(cpu_id, Cpu)`), so fall back to `graph.placement(src)`
786    // when the snapshot lacks the node — this is what stamps a two-hop's
787    // consumer-side hop with `Cpu` (its bytes come FROM the CPU intermediate,
788    // so its Copy kernel is the CPU `copy_from_cpu_wrapper`).
789    let src_location = |graph: &Graph, src: NodeId| -> Option<DeviceLocation> {
790        placements
791            .get(&src)
792            .copied()
793            .or_else(|| graph.placement(src))
794    };
795    // Stamp the new copies: target_backend = SOURCE backend. The pass only
796    // inserts a copy when the producer's placement resolved to Some.
797    for &copy_id in &inserted {
798        if let Some(&src) = graph.node(copy_id).inputs.first()
799            && let Some(src_loc) = src_location(graph, src)
800        {
801            graph.set_target_backend(copy_id, src_loc.backend());
802        }
803    }
804    // Re-stamp ALL copies/moves with their SOURCE backend — graph rewrites are
805    // sticky and `stamp_plan_backends` just overwrote pre-existing ones (e.g.
806    // realize-root splices) with the pinned backend; the transfer kernel runs
807    // where the bytes come from. The freshly-inserted copies are visited too,
808    // but their input's placement resolves to the same source location, so the
809    // sweep re-applies the identical stamp (idempotent). Copies whose source
810    // placement is absent keep whatever stamp they already have. The two-hop
811    // CPU intermediate's source is the original GPU producer (stamped to that
812    // GPU); the consumer-side hop's source is the CPU intermediate (stamped
813    // Cpu via the `graph.placement` fallback in `src_location`).
814    // Arm-inclusive (C-0): re-walk from the arm-seeded roots so copies just
815    // inserted inside non-arm-0 arms are re-stamped too. The `eff_roots` seed
816    // set (Branch nodes are unchanged by insertion) reaches the fresh arm
817    // copies via the now-rewired arm-input edges.
818    let order = topo_order_multi(graph, &eff_roots);
819    for &id in &order {
820        if !matches!(graph.node(id).op, Op::Copy { .. } | Op::Move { .. }) {
821            continue;
822        }
823        let Some(&src) = graph.node(id).inputs.first() else {
824            continue;
825        };
826        let Some(src_loc) = src_location(graph, src) else {
827            continue;
828        };
829        graph.set_target_backend(id, src_loc.backend());
830    }
831
832    placements
833}
834
835/// Compute every reachable node's *effective placement* for the residency
836/// pass, mirroring the bridge's old `effective_placements`. Priority per node:
837///
838/// 1. **Residency-declaring ops** — `Op::Copy`/`Op::Move`/`Op::Alloc` carry
839///    their output location in the variant (definitional).
840/// 2. **Explicit `Graph::placement`** — set by inserted copies (and any
841///    caller-provided placement hints).
842/// 3. **Input residency** — where a persistent / const input already lives,
843///    supplied by the realize path via `PlanOptions::input_residency`. This is
844///    the only runtime fact, read through the provider closure — the optimizer
845///    never touches the storage itself.
846/// 4. **Plan winner** — a planned node runs on its winner's device.
847/// 5. **Backend stamp** — a node with `target_backend` but no plan entry
848///    (structural ops) follows the pinned device.
849/// 6. **View pass-throughs** — view ops / `Reshape` / `Contiguize` follow
850///    their data input (already resolved; `order` is topological).
851fn effective_placements(
852    g: &Graph,
853    roots: &[NodeId],
854    plan: &ExecutionPlan,
855    pinned_loc: DeviceLocation,
856    input_residency: Option<&dyn Fn(NodeId) -> Option<DeviceLocation>>,
857) -> HashMap<NodeId, DeviceLocation> {
858    let order = topo_order_multi(g, roots);
859    let mut map: HashMap<NodeId, DeviceLocation> = HashMap::with_capacity(order.len());
860    for &id in &order {
861        let node = g.node(id);
862        match node.op {
863            Op::Copy { target } | Op::Move { target } | Op::Alloc { target } => {
864                map.insert(id, target);
865                continue;
866            }
867            _ => {}
868        }
869        if let Some(loc) = g.placement(id) {
870            map.insert(id, loc);
871            continue;
872        }
873        if let Some(loc) = input_residency.and_then(|f| f(id)) {
874            map.insert(id, loc);
875            continue;
876        }
877        if let Some(winner) = plan.alternatives(id).and_then(|set| set.winner()) {
878            map.insert(id, winner.device);
879            continue;
880        }
881        if g.target_backend(id).is_some() {
882            map.insert(id, pinned_loc);
883            continue;
884        }
885        if (node.op.is_view_op() || matches!(node.op, Op::Reshape(_) | Op::Contiguize))
886            && let Some(&loc) = node.inputs.first().and_then(|i| map.get(i))
887        {
888            map.insert(id, loc);
889        }
890    }
891    map
892}
893
894/// The PR-A4 deliberate-fork pathfinder + the PR-B2 frontier
895/// convergence optimizer now live in [`crate::driver`] as registered
896/// [`crate::driver::Pathfinder`] / [`crate::driver::Optimizer`] impls
897/// ([`crate::driver::PlacementForkPathfinder`] /
898/// [`crate::driver::FrontierConvergenceOptimizer`]). PR-B3 replaced the
899/// hardcoded `seed_placement_fork_branches(...)` call in
900/// [`optimize_graph`] with a lock-step
901/// [`crate::driver::PassRegistry::run_lockstep`] drive over those
902/// registered passes (see the module docs). The pathfinder body is
903/// unchanged — it moved verbatim behind the trait.
904#[cfg(test)]
905mod tests {
906    use super::*;
907    use crate::fused::PrecisionGuarantee;
908    use crate::kernel::{KernelCaps, OpParams, unknown_cost};
909    use fuel_graph::opt::execution_plan;
910    use fuel_graph::{Node, Op};
911    use fuel_ir::dispatch::OpKind;
912    use fuel_ir::probe::BackendId;
913    use fuel_ir::{DType, DeviceLocation, Layout, Result as FuelResult, Shape};
914    use fuel_memory::Storage;
915    use std::sync::{Arc, RwLock};
916
917    fn noop_kernel(
918        _i: &[Arc<RwLock<Storage>>],
919        _o: &mut [Arc<RwLock<Storage>>],
920        _l: &[Layout],
921        _p: &OpParams,
922    ) -> FuelResult<()> {
923        Ok(())
924    }
925
926    fn register_elementwise(table: &mut KernelBindingTable, op: OpKind, n_in: usize) {
927        let mut dtypes = vec![DType::F32; n_in];
928        dtypes.push(DType::F32); // output dtype
929        table.register_full(
930            op,
931            &dtypes,
932            BackendId::Cpu,
933            noop_kernel,
934            KernelCaps::empty(),
935            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
936            unknown_cost,
937        );
938    }
939
940    fn f32_node(g: &mut Graph, op: Op, inputs: Vec<NodeId>) -> NodeId {
941        // No pre-stamp: post-Step-A `optimize_graph` writes `target_backend`
942        // itself, so pre-stamping here is redundant for the tests that run the
943        // optimizer — and it would falsify the `*_stamps_backends_*` tests'
944        // "unstamped before optimize" / "Const leaf not stamped" preconditions.
945        g.push(Node {
946            op,
947            inputs,
948            shape: Shape::from_dims(&[4]),
949            dtype: DType::F32,
950        })
951    }
952
953    /// A representative branchless CPU graph the optimizer can fully
954    /// place: a fan-in (`Add` over two unary chains) feeding a unary
955    /// tail. Every kernel-bearing op has a CPU binding registered. The
956    /// fan-in exercises the run extractor's multi-predecessor boundary,
957    /// so the equivalence holds across more than a single straight
958    /// chain.
959    fn build_branchless_graph(table: &mut KernelBindingTable) -> (Graph, NodeId) {
960        register_elementwise(table, OpKind::ReluElementwise, 1);
961        register_elementwise(table, OpKind::SiluElementwise, 1);
962        register_elementwise(table, OpKind::AddElementwise, 2);
963        register_elementwise(table, OpKind::TanhElementwise, 1);
964
965        let mut g = Graph::new();
966        let a = f32_node(&mut g, Op::Const, vec![]);
967        let a1 = f32_node(&mut g, Op::Relu, vec![a]);
968        let b = f32_node(&mut g, Op::Const, vec![]);
969        let b1 = f32_node(&mut g, Op::Silu, vec![b]);
970        let sum = f32_node(&mut g, Op::Add, vec![a1, b1]);
971        let out = f32_node(&mut g, Op::Tanh, vec![sum]);
972        (g, out)
973    }
974
975    /// ROADMAP row 67 (I1): a graph whose analysed peak exceeds a small budget. `a` is read by `b` early and
976    /// by `c` late, so its longest inactive gap is evictable (the same shape the residency tests use).
977    fn build_over_budget_graph(table: &mut KernelBindingTable) -> (Graph, NodeId) {
978        register_elementwise(table, OpKind::ReluElementwise, 1);
979        register_elementwise(table, OpKind::NegElementwise, 1);
980        register_elementwise(table, OpKind::MulElementwise, 2);
981        register_elementwise(table, OpKind::AddElementwise, 2);
982        let mut g = Graph::new();
983        let a = f32_node(&mut g, Op::Const, vec![]);
984        let b = f32_node(&mut g, Op::Relu, vec![a]);
985        let pad = f32_node(&mut g, Op::Neg, vec![b]);
986        let pad2 = f32_node(&mut g, Op::Neg, vec![pad]);
987        let c = f32_node(&mut g, Op::Mul, vec![pad2, a]);
988        let out = f32_node(&mut g, Op::Add, vec![b, c]);
989        (g, out)
990    }
991
992    fn count_ops(g: &Graph, pred: impl Fn(&Op) -> bool) -> usize {
993        (0..g.len())
994            .filter(|i| pred(&g.node(NodeId(*i)).op))
995            .count()
996    }
997
998    fn peak_bytes(g: &Graph, root: NodeId) -> usize {
999        crate::residency::ResidencyPlanner::analyze(g, &[root]).peak_bytes
1000    }
1001
1002    #[test]
1003    fn a_device_budget_below_the_peak_inserts_evict_reload_chains() {
1004        let mut table = KernelBindingTable::new();
1005        let (mut g, root) = build_over_budget_graph(&mut table);
1006        let before = peak_bytes(&g, root);
1007        let opts = cpu_opts().with_device_budget_bytes(before - 1);
1008        let optimized =
1009            optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph under a budget");
1010        let outcome = optimized
1011            .eviction
1012            .as_ref()
1013            .expect("a budgeted run reports what the eviction pass did");
1014        assert!(
1015            !outcome.chains.is_empty(),
1016            "the outcome lists the inserted chains"
1017        );
1018        assert_eq!(outcome.budget_bytes, before - 1);
1019        assert!(
1020            count_ops(&g, |op| matches!(op, Op::Move { .. })) >= 1,
1021            "a budget below the peak must insert an Op::Move eviction"
1022        );
1023        assert!(
1024            count_ops(&g, |op| matches!(op, Op::Copy { .. })) >= 1,
1025            "and its reload Op::Copy"
1026        );
1027        // Not asserted here: a drop in the analysed peak. This graph is pinned to the CPU, and a
1028        // spill to the CPU cannot lower CPU residency; that property is pinned in
1029        // `residency::tests::today_the_reload_runs_eagerly_so_the_device_peak_does_not_drop`
1030        // (which documents that no round lowers the analysed peak until ROADMAP row 67 I3).
1031    }
1032
1033    #[test]
1034    fn the_plan_report_names_where_the_budget_came_from() {
1035        use crate::device_budget::{BudgetSource, ResolvedBudget};
1036        let run = |opts: PlanOptions<'_>| {
1037            let mut table = KernelBindingTable::new();
1038            let (mut g, root) = build_over_budget_graph(&mut table);
1039            optimize_graph(&mut g, &[root], &table, &opts)
1040                .expect("optimize_graph")
1041                .eviction
1042                .expect("a budgeted run reports an outcome")
1043        };
1044        let mut table = KernelBindingTable::new();
1045        let (g, root) = build_over_budget_graph(&mut table);
1046        let budget = peak_bytes(&g, root) - 1;
1047        let resolved = ResolvedBudget {
1048            bytes: budget,
1049            source: BudgetSource::Probed {
1050                available: (budget as u64) * 10 / 9,
1051                fraction: 0.9,
1052            },
1053        };
1054        let from_policy = run(cpu_opts().with_resolved_device_budget(resolved));
1055        assert_eq!(from_policy.budget_bytes, budget);
1056        assert_eq!(from_policy.budget_source, Some(resolved.source));
1057        // Control: a hand-set number carries no source, so the two paths are told apart.
1058        let by_hand = run(cpu_opts().with_device_budget_bytes(budget));
1059        assert_eq!(by_hand.budget_source, None);
1060    }
1061
1062    #[test]
1063    fn no_budget_a_roomy_budget_or_no_pinned_device_leave_the_graph_alone() {
1064        let nodes_of = |opts: &PlanOptions<'_>| {
1065            let mut table = KernelBindingTable::new();
1066            let (mut g, root) = build_over_budget_graph(&mut table);
1067            if opts.pinned_device.is_none() {
1068                // No pinned device: nodes need explicit placements to plan at all.
1069                for i in 0..g.len() {
1070                    g.set_placement(NodeId(i), DeviceLocation::Cpu);
1071                }
1072            }
1073            let optimized = optimize_graph(&mut g, &[root], &table, opts).expect("optimize_graph");
1074            if opts.device_budget_bytes.is_none() {
1075                assert!(optimized.eviction.is_none(), "no budget: no outcome");
1076            }
1077            (g.len(), count_ops(&g, |op| matches!(op, Op::Move { .. })))
1078        };
1079        // Negative control: no budget at all.
1080        assert_eq!(nodes_of(&cpu_opts()).1, 0, "no budget: no eviction");
1081        // A budget the graph already fits.
1082        assert_eq!(
1083            nodes_of(&cpu_opts().with_device_budget_bytes(usize::MAX)).1,
1084            0,
1085            "roomy budget: no eviction"
1086        );
1087        // The pass is gated on a pinned device, like the residency pass it follows.
1088        let unpinned = PlanOptions::new()
1089            .without_cost_population()
1090            .with_device_budget_bytes(1);
1091        assert_eq!(nodes_of(&unpinned).1, 0, "no pinned device: no eviction");
1092        // Node counts match the no-budget run exactly.
1093        assert_eq!(
1094            nodes_of(&cpu_opts()).0,
1095            nodes_of(&cpu_opts().with_device_budget_bytes(usize::MAX)).0
1096        );
1097    }
1098
1099    /// A pure straight-line CPU graph — the simplest no-competing-route
1100    /// case (exactly one run by construction).
1101    fn build_straight_line_graph(table: &mut KernelBindingTable) -> (Graph, NodeId) {
1102        register_elementwise(table, OpKind::ReluElementwise, 1);
1103        register_elementwise(table, OpKind::SiluElementwise, 1);
1104        register_elementwise(table, OpKind::TanhElementwise, 1);
1105
1106        let mut g = Graph::new();
1107        let a = f32_node(&mut g, Op::Const, vec![]);
1108        let b = f32_node(&mut g, Op::Relu, vec![a]);
1109        let c = f32_node(&mut g, Op::Silu, vec![b]);
1110        let d = f32_node(&mut g, Op::Tanh, vec![c]);
1111        (g, d)
1112    }
1113
1114    fn cpu_opts() -> PlanOptions<'static> {
1115        // No cost machinery: A3a only needs placement/validation, not
1116        // ranking. Pin the realize device so every node resolves.
1117        PlanOptions::new()
1118            .without_cost_population()
1119            .with_pinned_device(DeviceLocation::Cpu)
1120    }
1121
1122    /// Cleanup Step A: `optimize_graph` stamps each computational node's
1123    /// chosen backend onto the graph (the optimizer writes its placement
1124    /// decision INTO the graph). On a pinned-CPU straight-line graph every
1125    /// kernel-bearing node is stamped `Cpu`; the leaf `Op::Const` is
1126    /// skipped (it inherits / needs no stamp). When `pinned_device` is
1127    /// unset, no stamping occurs (the bare-graph test contract).
1128    #[test]
1129    fn optimize_graph_stamps_backends_onto_the_graph() {
1130        let mut table = KernelBindingTable::new();
1131        let (mut g, root) = build_straight_line_graph(&mut table);
1132        // a=Const(0), b=Relu(1), c=Silu(2), d=Tanh(3) by construction.
1133        let (a, b, c, d) = (NodeId(0), NodeId(1), NodeId(2), NodeId(3));
1134        assert!(g.target_backend(b).is_none(), "unstamped before optimize");
1135
1136        let _optimized = optimize_graph(&mut g, &[root], &table, &cpu_opts())
1137            .expect("optimize_graph on a straight-line CPU graph");
1138
1139        assert_eq!(
1140            g.target_backend(b),
1141            Some(BackendId::Cpu),
1142            "Relu stamped Cpu"
1143        );
1144        assert_eq!(
1145            g.target_backend(c),
1146            Some(BackendId::Cpu),
1147            "Silu stamped Cpu"
1148        );
1149        assert_eq!(
1150            g.target_backend(d),
1151            Some(BackendId::Cpu),
1152            "Tanh stamped Cpu"
1153        );
1154        assert!(
1155            g.target_backend(a).is_none(),
1156            "Op::Const leaf is not stamped"
1157        );
1158    }
1159
1160    /// `OptimizedGraph::placement_of` makes the placement DECISION observable,
1161    /// so a consumer can check where work landed instead of inferring it from
1162    /// timing (or from `Graph::placement`, which is only level 2 of the six-way
1163    /// resolution and returns `None` for exactly the compute nodes that matter).
1164    ///
1165    /// Two halves, and the second is the **positive control**: an accessor that
1166    /// silently returned `None` for everything would satisfy any test that only
1167    /// asserted `is_none()` on the unpinned path. So the pinned path asserts
1168    /// concrete `Some(Cpu)` values AND a non-empty map — if placement were never
1169    /// captured, that half fails loudly rather than passing vacuously.
1170    #[test]
1171    fn placement_of_observes_the_decision_and_marks_not_computed() {
1172        // --- pinned: the residency pass runs, placements are captured ---
1173        let mut table = KernelBindingTable::new();
1174        let (mut g, root) = build_straight_line_graph(&mut table);
1175        let (_a, b, c, d) = (NodeId(0), NodeId(1), NodeId(2), NodeId(3));
1176
1177        let optimized = optimize_graph(&mut g, &[root], &table, &cpu_opts())
1178            .expect("optimize_graph on a straight-line CPU graph");
1179
1180        assert!(
1181            optimized.has_placements(),
1182            "a pinned device runs the residency pass, so placements must be computed",
1183        );
1184        // POSITIVE CONTROL: concrete values, not merely "not None". An empty or
1185        // never-populated map would fail here instead of passing quietly.
1186        assert_eq!(
1187            optimized.placement_of(b),
1188            Some(DeviceLocation::Cpu),
1189            "Relu placed Cpu"
1190        );
1191        assert_eq!(
1192            optimized.placement_of(c),
1193            Some(DeviceLocation::Cpu),
1194            "Silu placed Cpu"
1195        );
1196        assert_eq!(
1197            optimized.placement_of(d),
1198            Some(DeviceLocation::Cpu),
1199            "Tanh placed Cpu"
1200        );
1201        assert!(
1202            optimized.placements().count() >= 3,
1203            "the map must actually be populated, got {} entries",
1204            optimized.placements().count(),
1205        );
1206
1207        // --- unpinned: the pass is skipped, and that is DISTINGUISHABLE ---
1208        // This is the property that keeps a `None` from being misread as
1209        // "placed nowhere" — the failure mode this accessor exists to prevent.
1210        //
1211        // Device context has to come from SOMEWHERE or `compile_plan` refuses
1212        // outright ("node has no device context — set PlanOptions::pinned_device,
1213        // a graph placement, or the node's target_backend"). So supply it via
1214        // per-node graph placement instead of a pin: the graph optimizes fine,
1215        // but `pinned_device` is unset so the residency pass never runs — which
1216        // is exactly the "optimized successfully, placement not computed" state
1217        // a caller must be able to tell apart from "placed nowhere".
1218        let mut table2 = KernelBindingTable::new();
1219        let (mut g2, root2) = build_straight_line_graph(&mut table2);
1220        for n in [NodeId(0), NodeId(1), NodeId(2), NodeId(3)] {
1221            g2.set_placement(n, DeviceLocation::Cpu);
1222        }
1223        let bare = PlanOptions::new().without_cost_population();
1224        let unpinned = optimize_graph(&mut g2, &[root2], &table2, &bare)
1225            .expect("optimize_graph with graph placements but no pinned device");
1226
1227        assert!(
1228            !unpinned.has_placements(),
1229            "no pinned device => residency pass skipped => placements NOT computed",
1230        );
1231        assert_eq!(
1232            unpinned.placement_of(b),
1233            None,
1234            "and every lookup is None — which `has_placements()` explains as \
1235             'not computed', never 'placed nowhere'",
1236        );
1237    }
1238
1239    /// Dtype-reconciliation declines on the REAL CPU table: the mixed-precision `[F32, BF16, F32]`
1240    /// and `[F32, F16, F32]` matmuls (f32 activation x half weight) are served natively by the CPU
1241    /// kernels `matmul_f32_bf16` / `matmul_f32_f16` (ROADMAP row 34), so `optimize_graph` plans them
1242    /// as they are and inserts no `Cast`: the weight stays half-width instead of being promoted to a
1243    /// resident f32 copy. Before row 34 this test asserted the opposite (a `Cast(F32)` on the
1244    /// weight, the fallback that the local-table tests below still pin for a backend WITHOUT the
1245    /// native key).
1246    #[test]
1247    fn optimize_graph_keeps_mixed_precision_matmul_native_on_cpu() {
1248        for weight in [DType::BF16, DType::F16] {
1249            let bindings = crate::dispatch::global_bindings(); // real populated CPU table
1250            let mut g = Graph::new();
1251            let lhs = g.push(Node {
1252                op: Op::Const,
1253                inputs: vec![],
1254                shape: Shape::from_dims(&[2, 3]),
1255                dtype: DType::F32,
1256            });
1257            let rhs = g.push(Node {
1258                op: Op::Const,
1259                inputs: vec![],
1260                shape: Shape::from_dims(&[3, 2]),
1261                dtype: weight,
1262            });
1263            let mm = g.push(Node {
1264                op: Op::MatMul,
1265                inputs: vec![lhs, rhs],
1266                shape: Shape::from_dims(&[2, 2]),
1267                dtype: DType::F32,
1268            });
1269
1270            optimize_graph(&mut g, &[mm], &bindings, &cpu_opts())
1271                .expect("mixed-precision matmul plans natively on CPU");
1272
1273            assert_eq!(
1274                g.node(mm).inputs,
1275                vec![lhs, rhs],
1276                "{weight:?}: no Cast, the CPU serves [F32, {weight:?}, F32] natively",
1277            );
1278            assert_eq!(g.node(rhs).dtype, weight, "the weight stays {weight:?}");
1279        }
1280    }
1281
1282    fn register_matmul(table: &mut KernelBindingTable, dtypes: &[DType], backend: BackendId) {
1283        table.register_full(
1284            OpKind::MatMul,
1285            dtypes,
1286            backend,
1287            noop_kernel,
1288            KernelCaps::empty(),
1289            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
1290            unknown_cost,
1291        );
1292    }
1293
1294    /// The reconciling `Op::Cast` the pass inserts needs a binding of its own to
1295    /// plan. The production table has these (`(Cpu, Cast, [BF16, F32])`); a
1296    /// hand-built test table must register them explicitly.
1297    fn register_cast(table: &mut KernelBindingTable, from: DType, to: DType, backend: BackendId) {
1298        table.register_full(
1299            OpKind::Cast,
1300            &[from, to],
1301            backend,
1302            noop_kernel,
1303            KernelCaps::empty(),
1304            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
1305            unknown_cost,
1306        );
1307    }
1308
1309    /// `[F32] @ [BF16] -> [F32]` on a graph pinned to `pinned`.
1310    fn mixed_matmul_graph() -> (Graph, NodeId, NodeId, NodeId) {
1311        let mut g = Graph::new();
1312        let lhs = g.push(Node {
1313            op: Op::Const,
1314            inputs: vec![],
1315            shape: Shape::from_dims(&[2, 3]),
1316            dtype: DType::F32,
1317        });
1318        let rhs = g.push(Node {
1319            op: Op::Const,
1320            inputs: vec![],
1321            shape: Shape::from_dims(&[3, 2]),
1322            dtype: DType::BF16,
1323        });
1324        let mm = g.push(Node {
1325            op: Op::MatMul,
1326            inputs: vec![lhs, rhs],
1327            shape: Shape::from_dims(&[2, 2]),
1328            dtype: DType::F32,
1329        });
1330        (g, lhs, rhs, mm)
1331    }
1332
1333    /// **Born-red regression guard: a backend must never break a graph that
1334    /// isn't running on it.**
1335    ///
1336    /// `insert_dtype_fixups` used to guard on `any_backend_supports` — a
1337    /// predicate over the WHOLE binding table that ignores the key's backend
1338    /// component. `compile_plan` enumerates over the node's *candidate
1339    /// placement set*. So when a non-candidate backend owned the only native
1340    /// mixed-dtype kernel, the pass saw "someone serves it", declined to
1341    /// reconcile, and the planner then dead-ended at `NoBackendForOp`.
1342    ///
1343    /// In-tree that surfaced as `--features vulkan` breaking CPU-pinned
1344    /// mixed-precision matmul, because Vulkan happens to be the only backend
1345    /// registering `MatMul[F32, BF16, F32]`. This test builds that situation
1346    /// from a LOCAL table so it reproduces in **every** build configuration —
1347    /// the feature-gated version is why the defect shipped unnoticed.
1348    #[test]
1349    fn dtype_reconciliation_ignores_kernels_on_non_candidate_backends() {
1350        let mut table = KernelBindingTable::new();
1351        // The pinned backend serves only the uniform key...
1352        register_matmul(
1353            &mut table,
1354            &[DType::F32, DType::F32, DType::F32],
1355            BackendId::Cpu,
1356        );
1357        // ...while a backend this graph will never run on owns the mixed key.
1358        register_matmul(
1359            &mut table,
1360            &[DType::F32, DType::BF16, DType::F32],
1361            BackendId::Vulkan,
1362        );
1363        register_cast(&mut table, DType::BF16, DType::F32, BackendId::Cpu);
1364
1365        let (mut g, lhs, rhs, mm) = mixed_matmul_graph();
1366        optimize_graph(&mut g, &[mm], &table, &cpu_opts()).expect(
1367            "CPU-pinned mixed-precision matmul must reconcile via Cast even though \
1368             a NON-candidate backend owns the native mixed kernel",
1369        );
1370
1371        let mm_inputs = g.node(mm).inputs.clone();
1372        assert_eq!(mm_inputs[0], lhs, "lhs (already F32) untouched");
1373        let cast_id = mm_inputs[1];
1374        assert_ne!(cast_id, rhs, "rhs was rewired to a Cast");
1375        assert!(
1376            matches!(g.node(cast_id).op, Op::Cast(DType::F32)),
1377            "rhs cast to F32"
1378        );
1379        assert_eq!(
1380            g.node(cast_id).inputs,
1381            vec![rhs],
1382            "cast reads the original BF16 weight"
1383        );
1384    }
1385
1386    /// The converse guard — the fix must not over-cast. When the node's own
1387    /// candidate backend serves the mixed key natively, reconciliation must
1388    /// decline, so the native mixed-precision kernel is preserved (casting
1389    /// would change numerics and double the promoted operand's bytes).
1390    #[test]
1391    fn dtype_reconciliation_declines_when_the_candidate_backend_serves_it_natively() {
1392        let mut table = KernelBindingTable::new();
1393        register_matmul(
1394            &mut table,
1395            &[DType::F32, DType::BF16, DType::F32],
1396            BackendId::Cpu,
1397        );
1398
1399        let (mut g, lhs, rhs, mm) = mixed_matmul_graph();
1400        optimize_graph(&mut g, &[mm], &table, &cpu_opts()).expect("native mixed kernel plans");
1401
1402        assert_eq!(
1403            g.node(mm).inputs,
1404            vec![lhs, rhs],
1405            "no Cast: the candidate backend has the native mixed kernel",
1406        );
1407    }
1408
1409    /// Multi-device behavior must be PRESERVED, not sacrificed to fix the bug
1410    /// above. When an off-device fallback is admitted, the foreign backend IS
1411    /// a candidate for this node — so its native mixed kernel is reachable and
1412    /// reconciliation must still decline. This is why the fix mirrors the
1413    /// planner's candidate set rather than narrowing to the pinned device.
1414    #[test]
1415    fn dtype_reconciliation_counts_admitted_off_device_fallback_as_a_candidate() {
1416        let mut table = KernelBindingTable::new();
1417        register_matmul(
1418            &mut table,
1419            &[DType::F32, DType::F32, DType::F32],
1420            BackendId::Cpu,
1421        );
1422        register_matmul(
1423            &mut table,
1424            &[DType::F32, DType::BF16, DType::F32],
1425            BackendId::Vulkan,
1426        );
1427
1428        let fallback = |_from: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
1429            vec![(BackendId::Vulkan, DeviceLocation::Vulkan { gpu_id: 0 })]
1430        };
1431        let opts = PlanOptions::new()
1432            .without_cost_population()
1433            .with_pinned_device(DeviceLocation::Cpu)
1434            .with_fallback_placements_for(&fallback);
1435
1436        let (mut g, lhs, rhs, mm) = mixed_matmul_graph();
1437        optimize_graph(&mut g, &[mm], &table, &opts).expect("off-device native mixed kernel plans");
1438
1439        assert_eq!(
1440            g.node(mm).inputs,
1441            vec![lhs, rhs],
1442            "no Cast: the admitted off-device fallback backend serves the mixed key natively",
1443        );
1444    }
1445
1446    /// The stamping is guarded on a pinned device — an `optimize_graph`
1447    /// with no `pinned_device` leaves the graph unstamped (so the bare
1448    /// optimize.rs test callers below are unaffected by Step A).
1449    #[test]
1450    fn optimize_graph_without_pinned_device_does_not_stamp() {
1451        let mut table = KernelBindingTable::new();
1452        let (mut g, root) = build_straight_line_graph(&mut table);
1453        // Give each node a device context via a graph PLACEMENT (a distinct
1454        // side-table from `target_backend`), so `compile_plan` resolves without
1455        // a pinned device — then assert `optimize_graph` performs no
1456        // `target_backend` stamping (the stamping arm is guarded on
1457        // `pinned_device`, so without a pin nothing is stamped).
1458        for id in [NodeId(0), NodeId(1), NodeId(2), NodeId(3)] {
1459            g.set_placement(id, DeviceLocation::Cpu);
1460        }
1461        let opts = PlanOptions::new().without_cost_population(); // no pinned device
1462        let _ = optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph");
1463        assert!(
1464            g.target_backend(NodeId(1)).is_none(),
1465            "no pinned device ⇒ no target_backend stamping",
1466        );
1467    }
1468
1469    /// Cleanup Step B (layout): `optimize_graph` inserts an `Op::Contiguize`
1470    /// before a kernel whose chosen winner rejects strided inputs
1471    /// (`caps.strided_input == false`, e.g. the `KernelCaps::empty()`
1472    /// elementwise bindings) and whose input layout is non-contiguous — the
1473    /// layout-fixup pass moved from the realize-time bridge into the optimizer.
1474    /// The pass itself is exhaustively tested in `fuel-graph::opt`; this guards
1475    /// the optimizer-side wiring (callback reads the plan winner's caps, runs
1476    /// inside the pinned guard).
1477    #[test]
1478    fn optimize_graph_inserts_layout_fixup_for_strided_input() {
1479        let mut table = KernelBindingTable::new();
1480        register_elementwise(&mut table, OpKind::ReluElementwise, 1); // empty caps ⇒ rejects strided
1481        let mut g = Graph::new();
1482        let a = f32_node(&mut g, Op::Const, vec![]);
1483        let r = f32_node(&mut g, Op::Relu, vec![a]);
1484        // Make `a`'s effective layout non-contiguous (non-zero start_offset),
1485        // so the strided-rejecting Relu needs a Contiguize on its input.
1486        g.set_layout(a, Layout::contiguous_with_offset(Shape::from_dims(&[4]), 1));
1487
1488        let _optimized = optimize_graph(&mut g, &[r], &table, &cpu_opts())
1489            .expect("optimize_graph with a strided input");
1490
1491        // Relu's input was `a`; after the fixup it must read through an inserted
1492        // Op::Contiguize wrapping `a`.
1493        let relu_input = g.node(r).inputs[0];
1494        assert!(
1495            matches!(g.node(relu_input).op, Op::Contiguize),
1496            "strided input to a strided-rejecting kernel must be fixed up via \
1497             Op::Contiguize, got {:?}",
1498            g.node(relu_input).op,
1499        );
1500        assert_eq!(
1501            g.node(relu_input).inputs,
1502            vec![a],
1503            "the inserted Op::Contiguize wraps the original strided input",
1504        );
1505    }
1506
1507    // ---- Cleanup Step B (residency) — insert_residency_copies tests ----
1508    // (migrated from the bridge's insert_resident_input_copies unit tests;
1509    // cache residency is supplied via an `input_residency` closure instead of a
1510    // live StorageCache. Placement metadata only — no GPU needed; the unprobed
1511    // test `SystemTopology` reports Cpu/Cuda as non-sharing, so a crossing is
1512    // detected and a copy inserted.)
1513
1514    /// Co-located graph ⇒ `insert_residency_copies` is a no-op (no crossings).
1515    #[test]
1516    fn residency_noop_when_colocated() {
1517        let mut g = Graph::new();
1518        let c1 = f32_node(&mut g, Op::Const, vec![]);
1519        let c2 = f32_node(&mut g, Op::Const, vec![]);
1520        let add = f32_node(&mut g, Op::Add, vec![c1, c2]);
1521        g.set_target_backend(add, BackendId::Cpu);
1522        let residency = |id: NodeId| (id == c1 || id == c2).then_some(DeviceLocation::Cpu);
1523        let pre = g.len();
1524        insert_residency_copies(
1525            &mut g,
1526            &[add],
1527            &ExecutionPlan::empty(),
1528            DeviceLocation::Cpu,
1529            Some(&residency),
1530        );
1531        assert_eq!(g.len(), pre, "co-located graph must be a no-op");
1532        assert_eq!(g.node(add).inputs, vec![c1, c2], "edges untouched");
1533    }
1534
1535    /// A CPU-resident input feeding two CUDA-pinned consumers ⇒ exactly ONE
1536    /// `Op::Copy` bridges the crossing (CSE-deduped), targeting the consumer
1537    /// device, stamped `target_backend = SOURCE` (Cpu, the H2D wrapper) with
1538    /// its output placed on the consumer device.
1539    #[test]
1540    fn residency_one_copy_per_crossing_deduped() {
1541        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
1542        let mut g = Graph::new();
1543        let c1 = f32_node(&mut g, Op::Const, vec![]);
1544        let neg = f32_node(&mut g, Op::Neg, vec![c1]);
1545        let sqr = f32_node(&mut g, Op::Sqr, vec![c1]);
1546        g.set_target_backend(neg, BackendId::Cuda);
1547        g.set_target_backend(sqr, BackendId::Cuda);
1548        let residency = |id: NodeId| (id == c1).then_some(DeviceLocation::Cpu);
1549
1550        let pre = g.len();
1551        insert_residency_copies(
1552            &mut g,
1553            &[neg, sqr],
1554            &ExecutionPlan::empty(),
1555            cuda0,
1556            Some(&residency),
1557        );
1558
1559        assert_eq!(g.len(), pre + 1, "one crossing → one copy, CSE-deduped");
1560        let neg_in = g.node(neg).inputs[0];
1561        let sqr_in = g.node(sqr).inputs[0];
1562        assert_eq!(neg_in, sqr_in, "both consumers share the one copy");
1563        assert_ne!(neg_in, c1, "consumers rewired off the raw input");
1564        let copy = g.node(neg_in);
1565        assert!(
1566            matches!(copy.op, Op::Copy { target } if target == cuda0),
1567            "copy targets the consumer device; got {:?}",
1568            copy.op,
1569        );
1570        assert_eq!(copy.inputs, vec![c1], "copy reads the resident slot");
1571        assert_eq!(
1572            g.target_backend(neg_in),
1573            Some(BackendId::Cpu),
1574            "stamped with the SOURCE backend (H2D runs on the CPU wrapper)",
1575        );
1576        assert_eq!(
1577            g.placement(neg_in),
1578            Some(cuda0),
1579            "copy output placed on the consumer device",
1580        );
1581    }
1582
1583    /// Idempotence + re-stamp: a second pass on the rewritten graph inserts
1584    /// nothing and restores the source-backend stamp even after a clobber
1585    /// (mimicking `stamp_plan_backends` overwriting it with the pinned backend).
1586    #[test]
1587    fn residency_idempotent_and_restamped_on_second_call() {
1588        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
1589        let mut g = Graph::new();
1590        let c1 = f32_node(&mut g, Op::Const, vec![]);
1591        let neg = f32_node(&mut g, Op::Neg, vec![c1]);
1592        g.set_target_backend(neg, BackendId::Cuda);
1593        let residency = |id: NodeId| (id == c1).then_some(DeviceLocation::Cpu);
1594
1595        insert_residency_copies(
1596            &mut g,
1597            &[neg],
1598            &ExecutionPlan::empty(),
1599            cuda0,
1600            Some(&residency),
1601        );
1602        let copy_id = g.node(neg).inputs[0];
1603        // Simulate stamp_plan_backends clobbering the copy with the pinned backend.
1604        g.set_target_backend(copy_id, BackendId::Cuda);
1605
1606        let pre = g.len();
1607        insert_residency_copies(
1608            &mut g,
1609            &[neg],
1610            &ExecutionPlan::empty(),
1611            cuda0,
1612            Some(&residency),
1613        );
1614        assert_eq!(g.len(), pre, "re-run inserts nothing");
1615        assert_eq!(
1616            g.target_backend(copy_id),
1617            Some(BackendId::Cpu),
1618            "re-stamp sweep restores the source-backend stamp",
1619        );
1620    }
1621
1622    // ---- Step E Phase C, PR C-0: arm residency-copy audit ----
1623    //
1624    // C2 lets the executor re-pick an `Op::Branch` arm at runtime by live
1625    // device load — it may choose arm-1+ instead of the static arm-0 winner.
1626    // That is only legal if the optimizer's residency pass has ALREADY
1627    // stitched the inbound cross-device `Op::Copy` for EVERY surviving arm,
1628    // so whichever arm the executor picks, that arm's device-inputs are
1629    // resident on its device. This test builds a 2-arm diamond whose two arms
1630    // live on DIFFERENT devices (arm-0 CPU, arm-1 CUDA) sharing one CPU
1631    // producer, runs the residency pass, and asserts BOTH arms' cross-device
1632    // inputs got their copy — not just arm-0's.
1633    //
1634    // The finalized `Op::Branch` is orphaned (its `reconverge_at` reads arm-0
1635    // directly, per the PR-A1 runnability invariant), so arm-1 is reachable
1636    // ONLY through the Branch node. `insert_residency_copies` walks
1637    // `topo_order_multi(roots)` directly (NOT `effective_roots`), so it never
1638    // reaches an orphaned Branch — and therefore never reaches arm-1. The
1639    // run/route machinery (`extract_runs_multi`, `branches_in_topo_order`)
1640    // does use `effective_roots`; the residency pass does not. This is the
1641    // C-0 prerequisite gap.
1642
1643    /// Build a 2-arm diamond: a CPU producer `diverge` fans into arm-0 (CPU)
1644    /// and arm-1 (`arm1_loc`); `reconverge` reads arm-0 (the runnability
1645    /// invariant); the Branch merges {arm0, arm1} at `reconverge`. Returns
1646    /// `(graph, branch, diverge, arm0, arm1, post)`. Placements are set via
1647    /// `set_placement` so the residency pass reads them with no plan/winner.
1648    fn residency_diamond(
1649        arm1_loc: DeviceLocation,
1650    ) -> (Graph, NodeId, NodeId, NodeId, NodeId, NodeId) {
1651        let mut g = Graph::new();
1652        let pre = f32_node(&mut g, Op::Const, vec![]);
1653        let diverge = f32_node(&mut g, Op::Relu, vec![pre]);
1654        let arm0 = f32_node(&mut g, Op::Silu, vec![diverge]);
1655        let arm1 = f32_node(&mut g, Op::GeluTanh, vec![diverge]);
1656        let reconverge = f32_node(&mut g, Op::Relu, vec![arm0]);
1657        let mut b = g.open_branch(diverge);
1658        b.add_arm(arm0);
1659        b.add_arm(arm1);
1660        let branch = b
1661            .finalize_branches(&mut g, reconverge)
1662            .expect("well-formed 2-arm branch")
1663            .expect("2 arms survive");
1664        let post = f32_node(&mut g, Op::Tanh, vec![reconverge]);
1665        // Producer + arm-0 + the post-merge region on CPU; arm-1 elsewhere.
1666        g.set_placement(pre, DeviceLocation::Cpu);
1667        g.set_placement(diverge, DeviceLocation::Cpu);
1668        g.set_placement(arm0, DeviceLocation::Cpu);
1669        g.set_placement(reconverge, DeviceLocation::Cpu);
1670        g.set_placement(post, DeviceLocation::Cpu);
1671        g.set_placement(arm1, arm1_loc);
1672        (g, branch, diverge, arm0, arm1, post)
1673    }
1674
1675    /// C-0 PREREQUISITE: the residency pass must insert the inbound
1676    /// cross-device `Op::Copy` for BOTH arms of a 2-device branch — arm-0
1677    /// (CPU, same device as the producer ⇒ no copy needed) AND arm-1 (CUDA,
1678    /// crosses ⇒ MUST get a copy). If only arm-0 were stitched, re-picking
1679    /// arm-1 at runtime (C2) would dispatch a CUDA kernel whose input was
1680    /// never copied to the GPU → the un-bridged-mixed-edge error / a UAF.
1681    #[test]
1682    fn residency_stitches_every_branch_arm_not_just_arm0() {
1683        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
1684        let (mut g, _branch, diverge, arm0, arm1, post) = residency_diamond(cuda0);
1685
1686        insert_residency_copies(
1687            &mut g,
1688            &[post],
1689            &ExecutionPlan::empty(),
1690            DeviceLocation::Cpu,
1691            None,
1692        );
1693
1694        // arm-0 is CPU, same substrate as the CPU producer ⇒ its input edge
1695        // does NOT cross ⇒ no copy (and must stay reading `diverge`).
1696        assert_eq!(
1697            g.node(arm0).inputs,
1698            vec![diverge],
1699            "arm-0 is co-located with its producer ⇒ no copy, edge untouched",
1700        );
1701
1702        // arm-1 is CUDA, its producer `diverge` is CPU ⇒ the edge crosses ⇒
1703        // the residency pass MUST have inserted an Op::Copy targeting CUDA on
1704        // arm-1's input. THIS is the C-0 invariant: every surviving arm's
1705        // device-inputs are made resident, not just arm-0's.
1706        let arm1_in = g.node(arm1).inputs[0];
1707        assert_ne!(
1708            arm1_in, diverge,
1709            "arm-1 (CUDA) reads the CPU producer directly — its inbound \
1710             cross-device Op::Copy was NEVER inserted. Re-picking arm-1 at \
1711             runtime (C2) would dispatch a CUDA kernel over un-copied CPU \
1712             bytes. The residency pass stitched only arm-0's route.",
1713        );
1714        let copy = g.node(arm1_in);
1715        assert!(
1716            matches!(copy.op, Op::Copy { target } if target == cuda0),
1717            "arm-1's inbound copy must target CUDA; got {:?}",
1718            copy.op,
1719        );
1720        assert_eq!(
1721            copy.inputs,
1722            vec![diverge],
1723            "arm-1's copy reads the shared CPU producer",
1724        );
1725    }
1726
1727    // ---- PR-A4 deliberate-fork-seed test substrate ----
1728
1729    fn noop_kernel_b(
1730        _i: &[Arc<RwLock<Storage>>],
1731        _o: &mut [Arc<RwLock<Storage>>],
1732        _l: &[Layout],
1733        _p: &OpParams,
1734    ) -> FuelResult<()> {
1735        Ok(())
1736    }
1737
1738    /// Register a CPU AND a (synthetic) CUDA binding for `op` so a node
1739    /// enumerated against both placements gets two viable
1740    /// `(backend, device)` candidates — the genuine placement fork the
1741    /// A4 pathfinder seeds a branch from.
1742    fn register_two_backend(table: &mut KernelBindingTable, op: OpKind, n_in: usize) {
1743        let mut dtypes = vec![DType::F32; n_in];
1744        dtypes.push(DType::F32);
1745        table.register_full(
1746            op,
1747            &dtypes,
1748            BackendId::Cpu,
1749            noop_kernel,
1750            KernelCaps::empty(),
1751            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
1752            unknown_cost,
1753        );
1754        table.register_full(
1755            op,
1756            &dtypes,
1757            BackendId::Cuda,
1758            noop_kernel_b,
1759            KernelCaps::empty(),
1760            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
1761            unknown_cost,
1762        );
1763    }
1764
1765    fn two_backend_placements(dev: DeviceLocation) -> Vec<BackendId> {
1766        if dev == DeviceLocation::Cpu {
1767            vec![BackendId::Cpu, BackendId::Cuda]
1768        } else {
1769            vec![]
1770        }
1771    }
1772
1773    /// Two backends co-located at the realize device, so every
1774    /// kernel-bearing node enumerates ≥2 placements — the multi-backend
1775    /// build the A4 pathfinder forks on. CPU-only builds (one placement
1776    /// per node) never hit this; the equivalence/idempotence gates above
1777    /// cover that.
1778    fn two_backend_opts() -> PlanOptions<'static> {
1779        PlanOptions::new()
1780            .without_cost_population()
1781            .with_pinned_device(DeviceLocation::Cpu)
1782            .with_placements_for_device(&two_backend_placements)
1783    }
1784
1785    /// A graph with a single kernel-bearing node that has a genuine
1786    /// ≥2-placement choice AND exactly one consumer (so it is a
1787    /// deliberate fork, not plain fan-out). Only `fork`'s op (`Silu`) is
1788    /// registered on two backends, so it is the ONLY node with a real
1789    /// ≥2-placement choice — exactly the "most ops are CPU-only, the
1790    /// matmul has cuBLAS too" shape.
1791    ///
1792    /// A long CPU-only `Relu` body surrounds the fork so the single
1793    /// deliberate branch sits far below the fewness threshold (a tiny
1794    /// graph would be all-branch by node count): `c -> body* -> prod ->
1795    /// fork -> tail -> body*`. `prod` is the diverge; `tail` is the
1796    /// reconverge (it reads `fork`).
1797    fn build_single_fork_graph(
1798        table: &mut KernelBindingTable,
1799    ) -> (Graph, NodeId, NodeId, NodeId, NodeId) {
1800        register_elementwise(table, OpKind::ReluElementwise, 1);
1801        register_two_backend(table, OpKind::SiluElementwise, 1); // the fork
1802        register_elementwise(table, OpKind::TanhElementwise, 1);
1803
1804        let mut g = Graph::new();
1805        let mut prev = f32_node(&mut g, Op::Const, vec![]);
1806        // Straight-line CPU body before the fork.
1807        for _ in 0..20 {
1808            prev = f32_node(&mut g, Op::Relu, vec![prev]);
1809        }
1810        let prod = prev; // the diverge (fork's producer)
1811        let fork = f32_node(&mut g, Op::Silu, vec![prod]);
1812        let tail = f32_node(&mut g, Op::Tanh, vec![fork]); // reconverge
1813        // Straight-line CPU body after the reconverge — the realize root
1814        // is the body's tail, so the whole graph is reachable and the
1815        // single fork sits far below the fewness threshold.
1816        let mut prev = tail;
1817        for _ in 0..20 {
1818            prev = f32_node(&mut g, Op::Relu, vec![prev]);
1819        }
1820        let root = prev;
1821        (g, prod, fork, tail, root)
1822    }
1823
1824    /// THE A4 DELIBERATE-FORK GATE (born-red until the pathfinder
1825    /// emits a Branch).
1826    ///
1827    /// (a) A node with two viable `(backend, device)` placements and a
1828    /// single consumer ⇒ `optimize_graph` emits exactly ONE 2-arm
1829    /// `Op::Branch` whose arm-0 is the DP winner, and the result passes
1830    /// the fewness gate.
1831    #[test]
1832    fn deliberate_fork_emits_one_two_arm_branch() {
1833        use fuel_graph::{branch_density, passes_fewness_gate};
1834        let mut table = KernelBindingTable::new();
1835        let (mut g, _prod, fork, _tail, root) = build_single_fork_graph(&mut table);
1836        let opts = two_backend_opts();
1837
1838        let nodes_before = g.len();
1839        let optimized = optimize_graph(&mut g, &[root], &table, &opts)
1840            .expect("optimize_graph succeeds on a 2-placement graph");
1841
1842        // Exactly one Op::Branch in the arena.
1843        assert_eq!(
1844            optimized.branch_count(&g),
1845            1,
1846            "a single genuine placement fork emits exactly one Op::Branch",
1847        );
1848
1849        // It is a 2-arm branch (arm-0 = the winner = `fork`).
1850        let branch_id = (nodes_before..g.len())
1851            .map(NodeId)
1852            .find(|&id| matches!(g.node(id).op, Op::Branch { .. }))
1853            .expect("a Branch node was appended");
1854        let branch = g.node(branch_id);
1855        assert_eq!(branch.inputs.len(), 2, "the branch has exactly two arms");
1856        assert_eq!(
1857            branch.inputs[0], fork,
1858            "arm-0 is the DP winner node (the route realize uses today)",
1859        );
1860        assert_ne!(
1861            branch.inputs[1], fork,
1862            "arm-1 is a distinct (runner-up placement) node",
1863        );
1864
1865        // The fewness gate holds — one branch among many nodes.
1866        assert!(
1867            passes_fewness_gate(&g, root),
1868            "a single deliberate fork passes the fewness gate; density={}",
1869            branch_density(&g, root),
1870        );
1871    }
1872
1873    /// (b) An ordinary DAG fan-out (one result, two distinct consumers)
1874    /// with the SAME 2-placement freedom is NOT flagged as a branch —
1875    /// fan-out is not a decision point.
1876    #[test]
1877    fn plain_fan_out_is_not_a_branch() {
1878        let mut table = KernelBindingTable::new();
1879        // Only the fan-out node's op (`Relu`) is dual-backend, so it is
1880        // the sole ≥2-placement candidate — and it is excluded purely
1881        // because it fans out (two consumers), not because it lacks a
1882        // placement choice. The consumers are CPU-only.
1883        register_two_backend(&mut table, OpKind::ReluElementwise, 1);
1884        register_elementwise(&mut table, OpKind::SiluElementwise, 1);
1885        register_elementwise(&mut table, OpKind::TanhElementwise, 1);
1886        register_elementwise(&mut table, OpKind::AddElementwise, 2);
1887
1888        // `shared` has two distinct consumers (c0, c1) that join at
1889        // `out` — plain fan-out, not a fork — even though it has a real
1890        // 2-placement choice.
1891        let mut g = Graph::new();
1892        let c = f32_node(&mut g, Op::Const, vec![]);
1893        let shared = f32_node(&mut g, Op::Relu, vec![c]);
1894        let c0 = f32_node(&mut g, Op::Silu, vec![shared]);
1895        let c1 = f32_node(&mut g, Op::Tanh, vec![shared]);
1896        let out = f32_node(&mut g, Op::Add, vec![c0, c1]);
1897        let opts = two_backend_opts();
1898
1899        let optimized =
1900            optimize_graph(&mut g, &[out], &table, &opts).expect("optimize_graph succeeds");
1901        assert_eq!(
1902            optimized.branch_count(&g),
1903            0,
1904            "plain fan-out (multiple consumers) is not a deliberate fork",
1905        );
1906        let _ = shared;
1907    }
1908
1909    /// (c) A branched graph realizes correctly via arm-0: the dispatch
1910    /// order follows {pre, arm-0, post} and SKIPS arm-1's run.
1911    #[test]
1912    fn branched_graph_realizes_via_arm0() {
1913        let mut table = KernelBindingTable::new();
1914        let (mut g, prod, fork, tail, root) = build_single_fork_graph(&mut table);
1915        let opts = two_backend_opts();
1916
1917        // Capture the single-route order BEFORE the branch is emitted —
1918        // this is the order realize must reproduce on arm-0.
1919        let pre_order = execution_plan(&g, &[root]);
1920
1921        let optimized =
1922            optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph succeeds");
1923        assert_eq!(optimized.branch_count(&g), 1, "exactly one branch");
1924
1925        // The arm-1 node is the branch's second input — it must NOT
1926        // appear in the arm-0 dispatch order.
1927        let branch_id = (0..g.len())
1928            .map(NodeId)
1929            .find(|&id| matches!(g.node(id).op, Op::Branch { .. }))
1930            .expect("a Branch node exists");
1931        let arm1 = g.node(branch_id).inputs[1];
1932
1933        let order = optimized.dispatch_order(&g);
1934        assert!(
1935            !order.contains(&arm1),
1936            "arm-0 lowering must skip arm-1's run; order={order:?} arm1={arm1:?}",
1937        );
1938        // arm-0 (fork) and the pre/post nodes ARE executed.
1939        assert!(order.contains(&prod), "pre-run (diverge producer) executes");
1940        assert!(order.contains(&fork), "arm-0 (the winner) executes");
1941        assert!(order.contains(&tail), "post-run (reconverge) executes");
1942        assert!(order.contains(&root), "the realize root executes");
1943
1944        // Behavior preserving: arm-0 lowering reproduces exactly the
1945        // pre-branch single-route order (arm-0 = the DP winner = the
1946        // graph realize used before the branch was recorded).
1947        assert_eq!(
1948            order, pre_order,
1949            "arm-0 dispatch order equals the pre-branch single-route order",
1950        );
1951    }
1952
1953    /// Return type of [`cached_env_test_fixture`] — named purely to dodge
1954    /// `clippy::type_complexity`, not because any caller needs the alias.
1955    type CachedEnvTestFixture = (
1956        Arc<RwLock<Graph>>,
1957        crate::pipelined::StorageCache,
1958        OptimizedGraph,
1959        std::sync::OnceLock<Vec<NodeId>>,
1960        Arc<dyn crate::ranker::RuntimeSelector>,
1961        NodeId,
1962    );
1963
1964    /// Shared setup for the two `cached_env_*` tests below: a single-fork
1965    /// graph, a two-backend `OptimizedGraph`, a seeded `StorageCache`, a
1966    /// fresh `order_cache`, and a real (non-stub) `WinnerSelector`.
1967    /// Factored out purely to keep each test under Codacy's method-length
1968    /// bound — no behavior lives here that either test's own body needs to
1969    /// see inline.
1970    fn cached_env_test_fixture() -> CachedEnvTestFixture {
1971        use crate::pipelined::StorageCache;
1972        use crate::ranker::runtime_selector::WinnerSelector;
1973
1974        let mut table = KernelBindingTable::new();
1975        let (mut g, _prod, _fork, _tail, root) = build_single_fork_graph(&mut table);
1976        let opts = two_backend_opts();
1977        let optimized =
1978            optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph succeeds");
1979        assert_eq!(optimized.branch_count(&g), 1, "exactly one branch");
1980
1981        let graph = Arc::new(RwLock::new(g));
1982        let mut cache = StorageCache::new();
1983        cache.insert(
1984            NodeId(0), // the leaf Const build_single_fork_graph pushes first.
1985            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
1986                1.0_f32, 2.0, 3.0, 4.0,
1987            ]))),
1988        );
1989        let order_cache: std::sync::OnceLock<Vec<NodeId>> = std::sync::OnceLock::new();
1990        let selector: Arc<dyn crate::ranker::RuntimeSelector> = Arc::new(WinnerSelector);
1991        (graph, cache, optimized, order_cache, selector, root)
1992    }
1993
1994    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
1995    /// §5), answering the PM's review question directly: on a graph with a
1996    /// REAL `Op::Branch` and a REAL selector (so the executor's picking
1997    /// entry point resolves a genuine pick, not just "no branches to
1998    /// pick"), `realize_with_optimized_picking_cached_env` must route
1999    /// through `OrderSource::Streaming`, NEVER through `OrderSource::Cached`
2000    /// — proven here by checking `order_cache` stays EMPTY across two
2001    /// separate picking realizes, not merely by reading the routing code.
2002    /// This is the stronger property PR review asked for: the fix doesn't
2003    /// need a cache key that "covers the pick" because picked graphs never
2004    /// reach the cache in the first place — `realize_with_optimized_picking_env`'s
2005    /// OWN routing (`streaming_pick_for` returning `Some` whenever a
2006    /// selector is given over a branched graph) already excludes them, and
2007    /// this test is what proves that exclusion actually holds for the
2008    /// cached sibling too, not just the uncached original.
2009    ///
2010    /// `result`/`result2` tolerate `Error::TopologyChanged` as a passing
2011    /// outcome, not just `Ok`: `optimized.generation` is stamped once, from
2012    /// the process-wide `topology_generation()` counter, at `optimize_graph`
2013    /// time above — and that counter is shared by every test in this binary
2014    /// (`register_runtime_kernel`/`extend_global_bindings`'s own doc admits
2015    /// this; see `register_runtime_kernel_into`'s test-only escape hatch).
2016    /// A sibling test registering a runtime-fused kernel between here and
2017    /// either realize call bumps it, and `realize_inner`'s chunk-boundary
2018    /// check (pipelined.rs) deliberately does NOT retry at this layer —
2019    /// only `pipelined_bridge`'s wrapper does (by design, so a low-level
2020    /// `PipelinedExecutor` caller sees the typed error, not a silent stall).
2021    /// A real retry would need a fresh `optimize_graph` call, which would
2022    /// defeat this test's actual subject (whether the same `OptimizedGraph`
2023    /// and `order_cache` stay consistent across repeat calls), so instead
2024    /// of retrying we just don't fail on the one outcome this test was
2025    /// never about. The `order_cache`-emptiness assertions stay
2026    /// unconditional: the `Streaming` path never touches `order_cache`
2027    /// regardless of whether the realize that invoked it succeeded or hit
2028    /// this race.
2029    #[test]
2030    fn cached_env_never_caches_a_branched_graph_with_a_real_selector() {
2031        use crate::PipelinedExecutor;
2032        use fuel_ir::{Error, SymEnv};
2033
2034        let (graph, cache, optimized, order_cache, selector, root) = cached_env_test_fixture();
2035
2036        let result = PipelinedExecutor::realize_with_optimized_picking_cached_env(
2037            graph.clone(),
2038            root,
2039            cache.clone(),
2040            &optimized,
2041            &order_cache,
2042            Some(selector.clone()),
2043            None,
2044            SymEnv::default(),
2045        );
2046        assert!(
2047            result.is_ok() || matches!(result, Err(Error::TopologyChanged { .. })),
2048            "a picked realize over a branched graph must either succeed or hit the \
2049             (unrelated, expected-under-concurrency) TopologyChanged race: {:?}",
2050            result.err()
2051        );
2052        assert!(
2053            order_cache.get().is_none(),
2054            "a branched graph with a real selector pick must NEVER populate order_cache — \
2055             it must route through OrderSource::Streaming, not OrderSource::Cached",
2056        );
2057
2058        // A second call, same cache slot: still must not populate it.
2059        let result2 = PipelinedExecutor::realize_with_optimized_picking_cached_env(
2060            graph,
2061            root,
2062            cache,
2063            &optimized,
2064            &order_cache,
2065            Some(selector),
2066            None,
2067            SymEnv::default(),
2068        );
2069        assert!(
2070            result2.is_ok() || matches!(result2, Err(Error::TopologyChanged { .. })),
2071            "second picked realize must either succeed or hit the same expected-under- \
2072             concurrency TopologyChanged race: {:?}",
2073            result2.err()
2074        );
2075        assert!(
2076            order_cache.get().is_none(),
2077            "order_cache must still be empty after a second picked realize",
2078        );
2079    }
2080
2081    /// Deterministic sibling of the test above: forces the EXACT race
2082    /// `Error::TopologyChanged` tolerance was added for, instead of relying
2083    /// on another test in the binary to collide by chance. Proves two
2084    /// things the flaky-under-`-j4` observation alone couldn't: (1) that a
2085    /// stale `optimized.generation` is SUFFICIENT to reproduce the exact
2086    /// failure this test's sibling hit (confirming the root cause, not
2087    /// just a plausible story), and (2) that `order_cache` stays empty
2088    /// even on the `Err` branch (the property this test file is actually
2089    /// about, independent of the race).
2090    ///
2091    /// Deliberately does NOT call the real, process-wide
2092    /// `bump_topology_generation()` to force this — that would inflict the
2093    /// exact `-j4` cross-test hazard this test documents onto every OTHER
2094    /// concurrently-running test in the binary that assumes a stable
2095    /// generation (an earlier draft of this test did exactly that, and
2096    /// broke `realize_with_optimized_picking_cached_env_matches_arm0_cold_and_warm`
2097    /// under `-j4`). `OptimizedGraph::generation` is `pub`, so mutating
2098    /// this test's own LOCAL copy to a value that can't match the live
2099    /// counter reproduces the identical code path with zero blast radius.
2100    #[test]
2101    fn cached_env_tolerates_a_concurrent_topology_generation_bump() {
2102        use crate::PipelinedExecutor;
2103        use fuel_ir::{Error, SymEnv};
2104
2105        let (graph, cache, mut optimized, order_cache, selector, root) = cached_env_test_fixture();
2106
2107        // Simulate a sibling test's legitimate `register_runtime_kernel`/
2108        // `extend_global_bindings` call landing between `optimize_graph`
2109        // (which stamped `optimized.generation` above) and this realize —
2110        // exactly the collision `cached_env_never_caches_a_branched_graph_with_a_real_selector`
2111        // hit under `-j4` — by staling THIS test's own copy of the stamp,
2112        // not the shared live counter every other test also reads.
2113        optimized.generation = optimized.generation.wrapping_add(1);
2114
2115        let result = PipelinedExecutor::realize_with_optimized_picking_cached_env(
2116            graph,
2117            root,
2118            cache,
2119            &optimized,
2120            &order_cache,
2121            Some(selector),
2122            None,
2123            SymEnv::default(),
2124        );
2125        assert!(
2126            matches!(result, Err(Error::TopologyChanged { .. })),
2127            "a forced generation bump before realize must surface as TopologyChanged, \
2128             not silently succeed or fail some other way: {:?}",
2129            result
2130        );
2131        assert!(
2132            order_cache.get().is_none(),
2133            "order_cache must stay empty even when the realize that would have \
2134             populated it (if it were ever going to) failed with TopologyChanged",
2135        );
2136    }
2137
2138    /// (d) No `DEFAULT_MAX_N` truncation: the fork records the winner +
2139    /// a runner-up without a fixed top-N cap stranding placements. Both
2140    /// arms survive; the per-device frontier — not a fixed N — bounds
2141    /// the arms.
2142    #[test]
2143    fn no_default_max_n_truncation() {
2144        let mut table = KernelBindingTable::new();
2145        let (mut g, _prod, fork, _tail, root) = build_single_fork_graph(&mut table);
2146        let opts = two_backend_opts();
2147
2148        let optimized =
2149            optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph succeeds");
2150        assert_eq!(optimized.branch_count(&g), 1);
2151        let branch_id = (0..g.len())
2152            .map(NodeId)
2153            .find(|&id| matches!(g.node(id).op, Op::Branch { .. }))
2154            .expect("a Branch node exists");
2155        // Two distinct placements ⇒ two arms survive; the runner-up was
2156        // not dropped by any top-N cap.
2157        assert_eq!(g.node(branch_id).inputs.len(), 2);
2158        assert_eq!(g.node(branch_id).inputs[0], fork);
2159    }
2160
2161    /// THE EQUIVALENCE GATE (born-red until `optimize_graph` exists and
2162    /// its lowered order matches `compile_plan`).
2163    ///
2164    /// On representative no-competing-route graphs, assert:
2165    ///   (a) `optimize_graph` leaves ZERO `Op::Branch` nodes, and
2166    ///   (b) the concatenated `extract_runs`/`lower_run` dispatch order
2167    ///       EQUALS today's `compile_plan(...).order` exactly (same
2168    ///       NodeIds, same order).
2169    #[test]
2170    fn equivalence_gate_branchless_order_matches_compile_plan() {
2171        for build in [
2172            build_straight_line_graph as fn(&mut KernelBindingTable) -> (Graph, NodeId),
2173            build_branchless_graph as fn(&mut KernelBindingTable) -> (Graph, NodeId),
2174        ] {
2175            let mut table = KernelBindingTable::new();
2176            let (mut g, root) = build(&mut table);
2177            let opts = cpu_opts();
2178
2179            // Today's path: the exact order the executor walks.
2180            let order = execution_plan(&g, &[root]);
2181            let plan = compile_plan(&g, &order, &table, &opts)
2182                .expect("today's compile_plan succeeds on a placeable graph");
2183
2184            // New path.
2185            let optimized = optimize_graph(&mut g, &[root], &table, &opts)
2186                .expect("optimize_graph succeeds on the same graph");
2187
2188            // (a) zero competing routes => zero Branch nodes.
2189            assert_eq!(
2190                optimized.branch_count(&g),
2191                0,
2192                "a no-competing-route graph optimizes to zero Op::Branch nodes",
2193            );
2194
2195            // (b) EXACT order equality against compile_plan(...).order.
2196            let lowered = optimized.dispatch_order(&g);
2197            assert_eq!(
2198                lowered, plan.order,
2199                "the extract_runs/lower_run dispatch order must equal \
2200                 compile_plan(...).order exactly (same NodeIds, same order)",
2201            );
2202            // And it covers every reachable node — the executor walks
2203            // the whole graph, runs partition it with no gaps/dupes.
2204            assert_eq!(
2205                lowered.len(),
2206                order.len(),
2207                "the lowered order covers every node compile_plan ordered",
2208            );
2209        }
2210    }
2211
2212    /// `optimize_graph` on a branchless graph is idempotent and adds no
2213    /// nodes: the node count is unchanged across repeated calls, the
2214    /// branch count stays zero, and the lowered order is stable.
2215    #[test]
2216    fn optimize_graph_branchless_is_idempotent_and_adds_no_nodes() {
2217        let mut table = KernelBindingTable::new();
2218        let (mut g, root) = build_branchless_graph(&mut table);
2219        let opts = cpu_opts();
2220
2221        let nodes_before = g.len();
2222        let first =
2223            optimize_graph(&mut g, &[root], &table, &opts).expect("first optimize succeeds");
2224        let order_first = first.dispatch_order(&g);
2225        let nodes_after_first = g.len();
2226
2227        let second =
2228            optimize_graph(&mut g, &[root], &table, &opts).expect("second optimize succeeds");
2229        let order_second = second.dispatch_order(&g);
2230        let nodes_after_second = g.len();
2231
2232        assert_eq!(
2233            nodes_before, nodes_after_first,
2234            "optimize_graph adds no nodes (A3a is single-route-only)",
2235        );
2236        assert_eq!(
2237            nodes_after_first, nodes_after_second,
2238            "a second optimize_graph adds no further nodes — idempotent",
2239        );
2240        assert_eq!(first.branch_count(&g), 0, "no branches after first");
2241        assert_eq!(second.branch_count(&g), 0, "no branches after second");
2242        assert_eq!(
2243            order_first, order_second,
2244            "the lowered dispatch order is stable across repeated optimize",
2245        );
2246    }
2247
2248    /// Identity proof for `docs/design/incremental-consumer-index.md` §5's
2249    /// `order_for` fix track: that fix proposes memoizing `dispatch_order`'s
2250    /// output WHOLESALE once per plan-once session, instead of recomputing
2251    /// it (via `extract_runs_multi` + `non_chosen_arm_nodes`, measured
2252    /// ~56ms/step, the single largest named sub-cost in a live decode step)
2253    /// on every `realize_inner` call. That's only valid if calling
2254    /// `dispatch_order` repeatedly on the SAME `OptimizedGraph` view with NO
2255    /// intervening graph mutation — exactly the plan-once decode shape,
2256    /// where only leaf values are rebound between tokens, never the graph's
2257    /// structure — yields a byte-identical `Vec<NodeId>` every time. Proven
2258    /// here, not assumed: five repeated calls, two structurally different
2259    /// branchless graphs (a fan-in boundary and a plain chain), zero
2260    /// mutation between calls (deliberately — this is NOT the existing
2261    /// `optimize_graph_branchless_is_idempotent_and_adds_no_nodes` test
2262    /// above, which re-runs `optimize_graph` itself between its two
2263    /// `dispatch_order` calls; this one proves `dispatch_order` is pure on
2264    /// its own, independent of re-optimizing).
2265    #[test]
2266    fn dispatch_order_is_stable_across_repeated_calls_with_no_mutation() {
2267        for build in [
2268            build_branchless_graph as fn(&mut KernelBindingTable) -> (Graph, NodeId),
2269            build_straight_line_graph,
2270        ] {
2271            let mut table = KernelBindingTable::new();
2272            let (mut g, root) = build(&mut table);
2273            let opts = cpu_opts();
2274            let optimized = optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph");
2275
2276            let orders: Vec<Vec<NodeId>> = (0..5).map(|_| optimized.dispatch_order(&g)).collect();
2277            for (i, order) in orders.iter().enumerate().skip(1) {
2278                assert_eq!(
2279                    &orders[0], order,
2280                    "dispatch_order call {i} diverged from call 0 with no intervening \
2281                     mutation — the order_for memoization fix would be UNSAFE if this failed",
2282                );
2283            }
2284        }
2285    }
2286
2287    /// Build-time validation: optimize_graph fails fast (Result, never
2288    /// panic) when a kernel-bearing node has no registered binding —
2289    /// reusing compile_plan's missing-binding diagnostic.
2290    #[test]
2291    fn optimize_graph_fails_fast_on_missing_binding() {
2292        let table = KernelBindingTable::new(); // empty — no bindings.
2293        let mut g = Graph::new();
2294        let a = f32_node(&mut g, Op::Const, vec![]);
2295        let relu = f32_node(&mut g, Op::Relu, vec![a]);
2296        let opts = cpu_opts();
2297
2298        let err = optimize_graph(&mut g, &[relu], &table, &opts)
2299            .map(|_| ())
2300            .unwrap_err();
2301        match err {
2302            fuel_ir::Error::NoBackendForOp { op, .. } => {
2303                assert_eq!(op, OpKind::ReluElementwise);
2304            }
2305            other => panic!("expected NoBackendForOp, got {other:?}"),
2306        }
2307    }
2308
2309    // ===== Phase B PR-B3: the lock-step pathfinder/ranker/optimizer
2310    //        driver. =====
2311
2312    use crate::driver::{
2313        FrontierConvergenceOptimizer, OptimizationContext, Optimizer, PassRegistry, Pathfinder,
2314        PlacementForkPathfinder,
2315    };
2316    use std::collections::HashSet;
2317
2318    /// Snapshot of a graph's `Op::Branch` decision points, keyed by
2319    /// arena order: `(branch_id, reconverge_at, arm NodeIds)`. Two
2320    /// optimization paths that produce the same snapshot produced the
2321    /// same multi-path graph (behavior-preservation).
2322    fn branch_snapshot(g: &Graph) -> Vec<(NodeId, NodeId, Vec<NodeId>)> {
2323        (0..g.len())
2324            .map(NodeId)
2325            .filter_map(|id| match g.node(id).op {
2326                Op::Branch { reconverge_at } => {
2327                    Some((id, reconverge_at, g.node(id).inputs.clone()))
2328                }
2329                _ => None,
2330            })
2331            .collect()
2332    }
2333
2334    /// THE LOAD-BEARING BEHAVIOR-PRESERVATION GATE (born-red until
2335    /// `optimize_graph` routes through the lock-step driver).
2336    ///
2337    /// On a representative multi-placement graph, the driver
2338    /// (`PassRegistry::default_passes().run_lockstep`) produces the
2339    /// **identical** multi-path graph as the old hardcoded sequence
2340    /// (pathfinder then optimizer, in that order): same branch count,
2341    /// same arm-0 winner, same arms, same reconverge points, and the
2342    /// same arm-0 dispatch order. B3 is a structural refactor — the
2343    /// optimized result must not change.
2344    #[test]
2345    fn driver_matches_legacy_sequence() {
2346        // (A) The reference: drive the registered passes BY HAND in the
2347        //     legacy order (propose, then prune) onto a freshly compiled
2348        //     plan — exactly what the pre-B3 hardcoded sequence did.
2349        let mut ref_table = KernelBindingTable::new();
2350        let (mut ref_g, _prod, ref_fork, _tail, ref_root) = build_single_fork_graph(&mut ref_table);
2351        let opts = two_backend_opts();
2352        let ref_order = execution_plan(&ref_g, &[ref_root]);
2353        let ref_plan = compile_plan(&ref_g, &ref_order, &ref_table, &opts)
2354            .expect("reference compile_plan succeeds");
2355        {
2356            let guard: HashSet<NodeId> = HashSet::new();
2357            let ctx = OptimizationContext {
2358                order: &ref_order,
2359                plan: &ref_plan,
2360                cycle_guard: &guard,
2361                bindings: &ref_table,
2362            };
2363            // Legacy order: the pathfinder ADDs, then the optimizer
2364            // prunes — the same two operations the hardcoded sequence ran.
2365            PlacementForkPathfinder
2366                .propose(&mut ref_g, &ctx)
2367                .expect("pathfinder proposes");
2368            FrontierConvergenceOptimizer
2369                .prune(&mut ref_g, &ctx)
2370                .expect("optimizer prunes");
2371        }
2372        let ref_snapshot = branch_snapshot(&ref_g);
2373        let ref_dispatch = fuel_graph::lower_runs_arm0(&ref_g, &[ref_root]);
2374
2375        // (B) The driver path: optimize_graph routes through
2376        //     PassRegistry::default_passes().run_lockstep.
2377        let mut table = KernelBindingTable::new();
2378        let (mut g, _p, fork, _t, root) = build_single_fork_graph(&mut table);
2379        let optimized =
2380            optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph succeeds");
2381        let got_snapshot = branch_snapshot(&g);
2382        let got_dispatch = optimized.dispatch_order(&g);
2383
2384        // Identical multi-path graph: same branches, arms, reconverge.
2385        assert_eq!(
2386            got_snapshot, ref_snapshot,
2387            "driver produces the identical Op::Branch structure as the legacy \
2388             pathfinder→optimizer sequence",
2389        );
2390        assert_eq!(
2391            got_snapshot.len(),
2392            1,
2393            "the representative multi-placement graph produces exactly one branch",
2394        );
2395        assert_eq!(
2396            got_snapshot[0].2[0], fork,
2397            "arm-0 is the DP winner (the route realize uses)",
2398        );
2399        // Identical dispatch order (arm-0 single-route lowering).
2400        assert_eq!(
2401            got_dispatch, ref_dispatch,
2402            "driver yields the identical arm-0 dispatch order as the legacy sequence",
2403        );
2404        let _ = ref_fork;
2405    }
2406
2407    /// A no-op registry (no registered pathfinders) leaves a branchless
2408    /// graph unchanged: no nodes added, zero branches, identical
2409    /// dispatch order. Proves the driver itself introduces no structure.
2410    #[test]
2411    fn noop_registry_leaves_branchless_graph_unchanged() {
2412        let mut table = KernelBindingTable::new();
2413        let (mut g, root) = build_branchless_graph(&mut table);
2414        let opts = cpu_opts();
2415
2416        let order = execution_plan(&g, &[root]);
2417        let plan = compile_plan(&g, &order, &table, &opts).expect("compile_plan succeeds");
2418
2419        let dispatch_before = fuel_graph::lower_runs_arm0(&g, &[root]);
2420        let nodes_before = g.len();
2421
2422        let registry = PassRegistry::new(); // empty — no passes.
2423        assert_eq!(registry.pathfinder_count(), 0);
2424        assert_eq!(registry.optimizer_count(), 0);
2425
2426        let guard: HashSet<NodeId> = HashSet::new();
2427        let ctx = OptimizationContext {
2428            order: &order,
2429            plan: &plan,
2430            cycle_guard: &guard,
2431            bindings: &table,
2432        };
2433        registry
2434            .run_lockstep(&mut g, &ctx)
2435            .expect("empty registry runs cleanly");
2436
2437        assert_eq!(g.len(), nodes_before, "no-op registry adds no nodes");
2438        let branches = (0..g.len())
2439            .map(NodeId)
2440            .filter(|&id| matches!(g.node(id).op, Op::Branch { .. }))
2441            .count();
2442        assert_eq!(branches, 0, "no-op registry adds no branches");
2443        let dispatch_after = fuel_graph::lower_runs_arm0(&g, &[root]);
2444        assert_eq!(
2445            dispatch_before, dispatch_after,
2446            "no-op registry leaves the dispatch order unchanged",
2447        );
2448    }
2449
2450    /// Lock-step ordering: a pathfinder ADDs before its dependent
2451    /// optimizer PRUNEs. We register a recording pathfinder and a
2452    /// recording optimizer that each stamp a shared log when invoked;
2453    /// `run_lockstep` must invoke the pathfinder strictly before the
2454    /// optimizer (prune-as-you-go, never optimizer-first).
2455    #[test]
2456    fn lockstep_runs_pathfinder_before_dependent_optimizer() {
2457        use std::sync::{Arc, Mutex};
2458
2459        #[derive(Clone)]
2460        struct RecordPathfinder(Arc<Mutex<Vec<&'static str>>>);
2461        impl Pathfinder for RecordPathfinder {
2462            fn name(&self) -> &'static str {
2463                "RecordPathfinder"
2464            }
2465            fn propose(
2466                &self,
2467                _g: &mut Graph,
2468                _ctx: &OptimizationContext<'_>,
2469            ) -> fuel_ir::Result<()> {
2470                self.0.lock().unwrap().push("propose");
2471                Ok(())
2472            }
2473        }
2474        #[derive(Clone)]
2475        struct RecordOptimizer(Arc<Mutex<Vec<&'static str>>>);
2476        impl Optimizer for RecordOptimizer {
2477            fn name(&self) -> &'static str {
2478                "RecordOptimizer"
2479            }
2480            fn prune(&self, _g: &mut Graph, _ctx: &OptimizationContext<'_>) -> fuel_ir::Result<()> {
2481                self.0.lock().unwrap().push("prune");
2482                Ok(())
2483            }
2484        }
2485
2486        let log = Arc::new(Mutex::new(Vec::new()));
2487        let registry = PassRegistry::new()
2488            .with_pathfinder(Box::new(RecordPathfinder(log.clone())))
2489            .with_optimizer(Box::new(RecordOptimizer(log.clone())));
2490
2491        let mut g = Graph::new();
2492        let _a = f32_node(&mut g, Op::Const, vec![]);
2493        let plan = ExecutionPlan::empty();
2494        let order: Vec<NodeId> = Vec::new();
2495        let guard: HashSet<NodeId> = HashSet::new();
2496        let table = KernelBindingTable::new();
2497        let ctx = OptimizationContext {
2498            order: &order,
2499            plan: &plan,
2500            cycle_guard: &guard,
2501            bindings: &table,
2502        };
2503        registry.run_lockstep(&mut g, &ctx).expect("drive runs");
2504
2505        let seq = log.lock().unwrap().clone();
2506        assert_eq!(
2507            seq,
2508            vec!["propose", "prune"],
2509            "lock-step drive runs the pathfinder ADD strictly before its \
2510             dependent optimizer PRUNE (prune-as-you-go)",
2511        );
2512    }
2513
2514    /// **Where does `PagedAttn`'s DECOMPOSED form land on CUDA?** — the
2515    /// measurement that gates whether offering a decomposed arm is worth
2516    /// building, and what to ask Baracuda for.
2517    ///
2518    /// Established already: the FUSED `Op::PagedAttn` node executes on the CPU
2519    /// under CUDA decode (`paged_decode_node_placement_report_cuda`), because
2520    /// no CUDA backend advertises it — so "runs on host" is not a decision the
2521    /// planner made, it is the only move it had. `decompose` exists and is
2522    /// closed-basis, but the planner is never offered it.
2523    ///
2524    /// This asks the question that decides the next build, and it is a
2525    /// GPU-vs-GPU question that the 186× host-ward figure cannot answer —
2526    /// **any** on-device path removes that round-trip equally, so its magnitude
2527    /// says something must be built without saying what:
2528    ///
2529    /// - **every recipe node CUDA-placed** → the round-trip is removable with
2530    ///   NO kernel work at all; the ask to Baracuda may be nothing.
2531    /// - **some primitive falls back to host** → *that primitive* is the ask,
2532    ///   far smaller and better-specified than "paged attention".
2533    ///
2534    /// A grep cannot answer this. I tried: it reported `Permute` in zero
2535    /// CUDA-backend files while the measured placement dump showed
2536    /// `Permute Cuda×6` — it undercounts ops served by generic dispatch. Only
2537    /// the planner's own resolved map settles it.
2538    ///
2539    /// REPORTS rather than asserting a verdict, for the same reason as the
2540    /// fused-node report: pre-committing to an answer is the error being
2541    /// corrected. What it DOES assert is that the instrument ran
2542    /// (`has_placements()`) and that decomposition actually happened (the root
2543    /// moved off the fused node) — an all-`None` dump would read as "nothing
2544    /// is on CUDA", a wrong answer wearing a null answer's clothes.
2545    #[test]
2546    #[ignore = "live GPU (CUDA); run via scripts/gpu-run.ps1"]
2547    #[cfg(feature = "cuda")]
2548    fn paged_attn_decomposed_arm_placement_report_cuda() {
2549        use fuel_graph::registry::{FusedOpParams, FusedOps};
2550        use std::collections::BTreeMap;
2551
2552        const B: usize = 1;
2553        const HQ: usize = 4;
2554        const HKV: usize = 4;
2555        const SQ: usize = 1;
2556        const D: usize = 4;
2557        const NUM_BLOCKS: usize = 32;
2558        const BLOCK_SIZE: usize = 4;
2559        const MAX_BLK: usize = 8;
2560
2561        let mut g = Graph::new();
2562        let leaf = |g: &mut Graph, dims: &[usize], dtype: DType| {
2563            g.push(Node {
2564                op: Op::Const,
2565                inputs: vec![],
2566                shape: Shape::from_dims(dims),
2567                dtype,
2568            })
2569        };
2570        let q = leaf(&mut g, &[B, HQ, SQ, D], DType::F32);
2571        let kc = leaf(&mut g, &[NUM_BLOCKS, BLOCK_SIZE, HKV, D], DType::F32);
2572        let vc = leaf(&mut g, &[NUM_BLOCKS, BLOCK_SIZE, HKV, D], DType::F32);
2573        let bt = leaf(&mut g, &[B, MAX_BLK], DType::U32);
2574        let cl = leaf(&mut g, &[B], DType::U32);
2575
2576        let params = FusedOpParams::PagedAttn {
2577            softmax_scale: 1.0 / (D as f32).sqrt(),
2578            block_size: BLOCK_SIZE,
2579            softcap: None,
2580        };
2581        let fused = g.push(Node {
2582            op: Op::Fused(FusedOps::PAGED_ATTN, params.clone()),
2583            inputs: vec![q, kc, vc, bt, cl],
2584            shape: Shape::from_dims(&[B, HQ, SQ, D]),
2585            dtype: DType::F32,
2586        });
2587
2588        // Lower the fused node to its primitive recipe — the arm the planner is
2589        // never currently offered.
2590        let root = fuel_graph::registry::paged_attn::decompose(&mut g, fused, &params);
2591        assert_ne!(
2592            root, fused,
2593            "PRECONDITION: decompose must actually lower. A self-return is the \
2594             G2 fixpoint signal (malformed node / declined recipe), and every \
2595             placement below would then describe the FUSED node, silently \
2596             answering a different question than the one asked.",
2597        );
2598
2599        // THE PRODUCTION TABLE, not a hand-assembled one. An earlier version of
2600        // this test built the table with `register_cuda_kernels` alone and got
2601        // "no backend supports index_select" — which was an artifact of the
2602        // HARNESS, not a fact about Fuel: that function makes ~5 registrations
2603        // and the bulk of CUDA lives in `register_baracuda_cuda_kernels`, which
2604        // the real path (`register_optional_backends`) also calls, on top of
2605        // `register_cpu_kernels` and a cost fill. Reproducing that assembly by
2606        // hand is precisely the kind of thing that silently drifts, so ask for
2607        // the table the realize path actually uses.
2608        let table = crate::dispatch::global_bindings();
2609
2610        // POSITIVE CONTROL — the instrument must be able to see a CUDA binding
2611        // at all. Without this, an under-populated table reports "no CUDA
2612        // support" for EVERY op, which reads exactly like a real finding: it is
2613        // specific, it names a primitive, and it is completely wrong. That is
2614        // how the first run of this test nearly shipped a false Baracuda ask.
2615        // MatMul is the control because the fuel-core placement report measured
2616        // `MatMul Cuda×15` on a real decode graph — an independently observed
2617        // fact this table must reproduce.
2618        assert!(
2619            table
2620                .lookup(
2621                    OpKind::MatMul,
2622                    &[DType::F32, DType::F32, DType::F32],
2623                    BackendId::Cuda
2624                )
2625                .is_ok(),
2626            "INSTRUMENT BROKEN: the binding table has no CUDA MatMul, so every \
2627             'no CUDA support' conclusion below would be an artifact of the \
2628             harness. Fix the table before reading any verdict from this test.",
2629        );
2630
2631        // ---- THE COMPLETE MISSING-BINDING SET, asked directly ----
2632        //
2633        // `optimize_graph` fails at the FIRST unplaceable node, so driving this
2634        // off its error yields one op per run — a trickle, and each run costs a
2635        // CUDA rebuild. Worse, it conflates two different things: "CUDA has no
2636        // kernel for this op" and "the planner could not place it under THIS
2637        // pin". Asking the binding table per node separates them and returns the
2638        // whole set at once.
2639        let mut missing_cuda: Vec<String> = Vec::new();
2640        let mut present_cuda: Vec<String> = Vec::new();
2641        for i in 0..g.len() {
2642            let id = NodeId(i);
2643            let node = g.node(id);
2644            let Some(kind) = crate::pipelined::op_to_op_kind(&node.op) else {
2645                continue; // Const / view / fused — not a binding-table lookup
2646            };
2647            let mut dtypes: Vec<DType> = node.inputs.iter().map(|&i| g.node(i).dtype).collect();
2648            dtypes.push(node.dtype); // binding key is [inputs.., output]
2649            let sig = format!(
2650                "{kind:?}{:?}",
2651                dtypes.iter().map(|d| format!("{d:?}")).collect::<Vec<_>>()
2652            );
2653            if table.lookup(kind, &dtypes, BackendId::Cuda).is_ok() {
2654                present_cuda.push(sig);
2655            } else {
2656                missing_cuda.push(sig);
2657            }
2658        }
2659        missing_cuda.sort();
2660        missing_cuda.dedup();
2661        present_cuda.sort();
2662        present_cuda.dedup();
2663
2664        println!("\n=== PagedAttn recipe: CUDA binding coverage (asked per node) ===");
2665        println!("PRESENT on CUDA ({}):", present_cuda.len());
2666        for s in &present_cuda {
2667            println!("    {s}");
2668        }
2669        println!("MISSING on CUDA ({}):", missing_cuda.len());
2670        for s in &missing_cuda {
2671            println!("    {s}");
2672        }
2673        // A run where NOTHING resolves would mean the table is empty again — the
2674        // MatMul control above already guards that, but state the invariant that
2675        // makes the "missing" list meaningful rather than vacuous.
2676        assert!(
2677            !present_cuda.is_empty(),
2678            "INSTRUMENT BROKEN: not one recipe node resolved on CUDA, so the \
2679             MISSING list is a property of the lookup, not of the backend",
2680        );
2681        println!(
2682            "\n>>> THE ASK: the {} signature(s) above are what CUDA lacks for the \
2683             §1 dense recipe. Each is a small, named primitive — not \"paged \
2684             attention\".\n",
2685            missing_cuda.len()
2686        );
2687
2688        let opts = PlanOptions::new().with_pinned_device(DeviceLocation::Cuda { gpu_id: 0 });
2689        let optimized = match optimize_graph(&mut g, &[root], &table, &opts) {
2690            Ok(o) => o,
2691            Err(e) => {
2692                println!("\n=== DECOMPOSED ARM DOES NOT PLAN ON CUDA ===");
2693                println!("optimize_graph error: {e:?}");
2694                println!("That is itself the answer: some recipe primitive has no CUDA");
2695                println!("binding, and the error names it. THAT is the Baracuda ask.");
2696                return;
2697            }
2698        };
2699
2700        assert!(
2701            optimized.has_placements(),
2702            "placement NOT COMPUTED — every placement_of would be None and the \
2703             report below would describe the missing instrument, not the graph",
2704        );
2705
2706        let mut by_op: BTreeMap<String, BTreeMap<String, usize>> = BTreeMap::new();
2707        let mut host_ops: Vec<String> = Vec::new();
2708        for i in 0..g.len() {
2709            let id = NodeId(i);
2710            let op_name = match &g.node(id).op {
2711                Op::Fused(fid, _) => format!("Fused({fid:?})"),
2712                other => format!("{other:?}")
2713                    .split(' ')
2714                    .next()
2715                    .unwrap_or("?")
2716                    .to_string(),
2717            };
2718            let place = match optimized.placement_of(id) {
2719                Some(d) => format!("{d:?}"),
2720                None => "None".to_string(),
2721            };
2722            if place.starts_with("Cpu") {
2723                host_ops.push(op_name.clone());
2724            }
2725            *by_op.entry(op_name).or_default().entry(place).or_insert(0) += 1;
2726        }
2727
2728        println!("\n=== PagedAttn DECOMPOSED arm: node placement (CUDA-pinned) ===");
2729        println!(
2730            "total nodes: {} (fused node #{} lowered to root #{})",
2731            g.len(),
2732            fused.0,
2733            root.0
2734        );
2735        for (op, places) in &by_op {
2736            let rendered: Vec<String> = places.iter().map(|(d, n)| format!("{d}×{n}")).collect();
2737            println!("  {op:<40} {}", rendered.join("  "));
2738        }
2739
2740        println!("\n--- VERDICT ---");
2741        if host_ops.is_empty() {
2742            println!(
2743                "EVERY recipe node is off-host. The decomposed paged attention runs \
2744                 ON DEVICE, so the 186x round-trip is removable by OFFERING THIS ARM \
2745                 — no Baracuda kernel required to eliminate it. A kernel would then \
2746                 be a throughput question (the recipe materialises padded capacity, \
2747                 not live context_len), not a round-trip one."
2748            );
2749        } else {
2750            host_ops.sort();
2751            host_ops.dedup();
2752            println!(
2753                "HOST-PLACED recipe primitives: {host_ops:?}\n\
2754                 These are the ask — each is a far smaller and better-specified \
2755                 request than \"paged attention\", and until they exist on device \
2756                 the decomposed arm cannot win."
2757            );
2758        }
2759        println!("--- END VERDICT ---\n");
2760    }
2761
2762    // ---- GAP-380 (a1): lower a fused op with no kernel on the pinned device -------------------
2763
2764    /// `[q, k_cache, v_cache, block_table, context_lens]` consts, a fused PAGED_ATTN, and a
2765    /// `Contiguize` consumer. Returns `(graph, consumer)`.
2766    fn paged_attn_graph() -> (Graph, NodeId) {
2767        use fuel_graph::registry::{FusedOpParams, FusedOps};
2768        let mut g = Graph::new();
2769        let mut leaf = |dims: &[usize], dtype: DType| {
2770            g.push(Node {
2771                op: Op::Const,
2772                inputs: vec![],
2773                shape: Shape::from_dims(dims),
2774                dtype,
2775            })
2776        };
2777        let q = leaf(&[1, 2, 1, 4], DType::F32);
2778        let kc = leaf(&[3, 2, 2, 4], DType::F32);
2779        let vc = leaf(&[3, 2, 2, 4], DType::F32);
2780        let bt = leaf(&[1, 2], DType::U32);
2781        let cl = leaf(&[1], DType::U32);
2782        let fused = g.push(Node {
2783            op: Op::Fused(
2784                FusedOps::PAGED_ATTN,
2785                FusedOpParams::PagedAttn {
2786                    softmax_scale: 0.5,
2787                    block_size: 2,
2788                    softcap: None,
2789                },
2790            ),
2791            inputs: vec![q, kc, vc, bt, cl],
2792            shape: Shape::from_dims(&[1, 2, 1, 4]),
2793            dtype: DType::F32,
2794        });
2795        let consumer = g.push(Node {
2796            op: Op::Contiguize,
2797            inputs: vec![fused],
2798            shape: Shape::from_dims(&[1, 2, 1, 4]),
2799            dtype: DType::F32,
2800        });
2801        (g, consumer)
2802    }
2803
2804    fn paged_attn_nodes(g: &Graph, root: NodeId) -> usize {
2805        topo_order_multi(g, &[root])
2806            .into_iter()
2807            .filter(|&n| {
2808                matches!(
2809                    g.node(n).op,
2810                    Op::Fused(fuel_graph::registry::FusedOps::PAGED_ATTN, _)
2811                )
2812            })
2813            .count()
2814    }
2815
2816    #[test]
2817    fn a_cuda_pin_with_no_cuda_paged_attn_kernel_lowers_the_fused_node() {
2818        let (mut g, root) = paged_attn_graph();
2819        let opts = PlanOptions::new().with_pinned_device(DeviceLocation::Cuda { gpu_id: 0 });
2820        assert_eq!(
2821            paged_attn_nodes(&g, root),
2822            1,
2823            "PRECONDITION: one fused node"
2824        );
2825        let n = lower_fused_unbound_on_pinned_device(&mut g, &[root], &opts, &|_, _| false);
2826        assert_eq!(n, 1);
2827        assert_eq!(
2828            paged_attn_nodes(&g, root),
2829            0,
2830            "no fused PAGED_ATTN stays reachable"
2831        );
2832    }
2833
2834    /// Sabotage siblings: each condition of the gate, taken away alone, leaves the node fused.
2835    #[test]
2836    fn the_gate_needs_a_cuda_pin_no_bound_kernel_and_a_listed_op() {
2837        // A bound CUDA kernel: keep the fused node (the fast path wins when it exists).
2838        let (mut g, root) = paged_attn_graph();
2839        let cuda = PlanOptions::new().with_pinned_device(DeviceLocation::Cuda { gpu_id: 0 });
2840        assert_eq!(
2841            lower_fused_unbound_on_pinned_device(&mut g, &[root], &cuda, &|_, _| true),
2842            0
2843        );
2844        assert_eq!(paged_attn_nodes(&g, root), 1);
2845        // A CPU pin: the host kernel IS the right place, so nothing lowers.
2846        let (mut g, root) = paged_attn_graph();
2847        let cpu = PlanOptions::new().with_pinned_device(DeviceLocation::Cpu);
2848        assert_eq!(
2849            lower_fused_unbound_on_pinned_device(&mut g, &[root], &cpu, &|_, _| false),
2850            0
2851        );
2852        assert_eq!(paged_attn_nodes(&g, root), 1);
2853        // No pin at all (bare-graph callers): untouched.
2854        let (mut g, root) = paged_attn_graph();
2855        let bare = PlanOptions::new();
2856        assert_eq!(
2857            lower_fused_unbound_on_pinned_device(&mut g, &[root], &bare, &|_, _| false),
2858            0
2859        );
2860        assert_eq!(paged_attn_nodes(&g, root), 1);
2861    }
2862
2863    /// The production predicate is the real registry: CUDA has no PAGED_ATTN kernel today, CPU does.
2864    /// Red the day a CUDA kernel is bound (then the recipe is the slower path and this list must be
2865    /// revisited, which is the point).
2866    #[test]
2867    fn the_registry_has_a_cpu_paged_attn_kernel_and_no_cuda_one() {
2868        let impls = crate::fused::default_kernel_registry()
2869            .impls_for(fuel_graph::registry::FusedOps::PAGED_ATTN);
2870        assert!(
2871            impls
2872                .iter()
2873                .any(|(b, _)| *b == fuel_ir::probe::BackendId::Cpu),
2874            "CONTROL: the registry lookup sees the CPU PAGED_ATTN kernels"
2875        );
2876        assert!(
2877            !impls
2878                .iter()
2879                .any(|(b, _)| *b == fuel_ir::probe::BackendId::Cuda),
2880            "a CUDA PAGED_ATTN kernel is bound: revisit LOWER_WHEN_NO_DEVICE_KERNEL (the fused kernel may now beat the recipe)"
2881        );
2882    }
2883    /// Helper for the row-157 region tests: every kernel op registered on two placements.
2884    fn two_placement_table() -> KernelBindingTable {
2885        let mut table = KernelBindingTable::new();
2886        register_two_backend(&mut table, OpKind::ReluElementwise, 1);
2887        register_two_backend(&mut table, OpKind::SiluElementwise, 1);
2888        register_two_backend(&mut table, OpKind::TanhElementwise, 1);
2889        register_two_backend(&mut table, OpKind::AddElementwise, 2);
2890        table
2891    }
2892
2893    /// `(branch_id, arm-0 exit, reconverge)` of every `Op::Branch` added after `from`.
2894    fn branches_after(g: &Graph, from: usize) -> Vec<(NodeId, NodeId, NodeId)> {
2895        (from..g.len())
2896            .map(NodeId)
2897            .filter_map(|id| match g.node(id).op {
2898                Op::Branch { reconverge_at } => Some((id, g.node(id).inputs[0], reconverge_at)),
2899                _ => None,
2900            })
2901            .collect()
2902    }
2903
2904    /// ROW 157 / GAP-385, RESIDUAL JOIN AND FAN-OUT (born red against the one-node fork, which made
2905    /// 8 one-node forks here and none at `n1` or `res`).
2906    ///
2907    /// A transformer-block-shaped graph, every op on two placements: a residual block whose body fans
2908    /// out (`n1` feeds q, k and v which rejoin through `a` and `b`), then a second residual block.
2909    /// Expect one multi-node region per residual block: block 1 has diverge `x`, a seven-node arm
2910    /// (`n1 q k v a b o`) and reconverge `res`, which reads `x` directly (the residual edge); block 2
2911    /// has diverge `res`, a two-node arm (`n2 m`) and reconverge `res2`.
2912    #[test]
2913    fn transformer_shaped_graph_forks_residual_blocks_as_multi_node_regions() {
2914        let table = two_placement_table();
2915        let mut g = Graph::new();
2916        let x = f32_node(&mut g, Op::Const, vec![]);
2917        let n1 = f32_node(&mut g, Op::Relu, vec![x]); // fan-out: q, k, v
2918        let q = f32_node(&mut g, Op::Silu, vec![n1]);
2919        let k = f32_node(&mut g, Op::Tanh, vec![n1]);
2920        let v = f32_node(&mut g, Op::Relu, vec![n1]);
2921        let a = f32_node(&mut g, Op::Add, vec![q, k]);
2922        let b = f32_node(&mut g, Op::Add, vec![a, v]);
2923        let o = f32_node(&mut g, Op::Silu, vec![b]);
2924        let res = f32_node(&mut g, Op::Add, vec![x, o]); // residual join
2925        let n2 = f32_node(&mut g, Op::Relu, vec![res]);
2926        let m = f32_node(&mut g, Op::Silu, vec![n2]);
2927        let res2 = f32_node(&mut g, Op::Add, vec![res, m]);
2928
2929        let before = g.len();
2930        let optimized = optimize_graph(&mut g, &[res2], &table, &two_backend_opts())
2931            .expect("optimize_graph succeeds on a transformer-shaped two-placement graph");
2932
2933        let mut branches = branches_after(&g, before);
2934        branches.sort_by_key(|(_, exit, _)| exit.0);
2935        assert_eq!(
2936            optimized.branch_count(&g),
2937            2,
2938            "one region per residual block"
2939        );
2940        assert_eq!(
2941            branches.iter().map(|&(_, e, r)| (e, r)).collect::<Vec<_>>(),
2942            vec![(o, res), (m, res2)],
2943            "arm-0 exits and reconverge nodes: (o, res) and (m, res2)"
2944        );
2945        // Arm 1 clones the whole stretch: 7 + 2 clone nodes beside the 2 branch nodes.
2946        assert_eq!(
2947            g.len() - before,
2948            7 + 2 + 2,
2949            "clones of both stretches plus two branch nodes"
2950        );
2951        // Block 1's arm-1 head reads the shared diverge node x (not a clone), and res reads x directly.
2952        assert!(
2953            g.node(res).inputs.contains(&x),
2954            "the residual edge x -> res is untouched"
2955        );
2956    }
2957
2958    /// ROW 158: a region's arm 1 on ANOTHER device must read every value from outside its arm through an
2959    /// `Op::Copy`, and hand its result back to arm 0's device through one. The first run of arm 1 on a GPU
2960    /// (a CPU arm in a Vulkan realize) failed with `cpu kernel wrapper called with non-CPU input` on a clone
2961    /// `Add` reading two Vulkan `Mul` nodes directly: the pathfinder's clones carried a `target_backend`
2962    /// but no placement, so the residency pass placed them on the pinned device and saw no crossing.
2963    ///
2964    /// The stretch `a, t` has TWO external inputs (the diverge `d` and the earlier `e`) and its exit feeds
2965    /// a reconverge on the host. The alternative runs on `Cuda { gpu_id: 0 }`. Built through
2966    /// `try_record_branch` with explicit devices because the synthetic two-backend fixture of
2967    /// `optimize_graph` puts its "Cuda" placement at the CPU location and so cannot show a crossing.
2968    #[test]
2969    fn a_cross_device_arm_one_gets_inbound_copies_for_every_external_input_and_an_exit_copy() {
2970        use crate::region_pathfinder::try_record_branch;
2971        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
2972        let mut g = Graph::new();
2973        let x = f32_node(&mut g, Op::Const, vec![]);
2974        let e = f32_node(&mut g, Op::Relu, vec![x]);
2975        let d = f32_node(&mut g, Op::Silu, vec![e]); // the diverge
2976        let a = f32_node(&mut g, Op::Add, vec![d, e]); // entry: reads d AND e, both outside the stretch
2977        let t = f32_node(&mut g, Op::Tanh, vec![a]);
2978        let res = f32_node(&mut g, Op::Add, vec![d, t]); // reconverge: reads the exit t (and d)
2979        for n in [x, e, d, a, t, res] {
2980            g.set_placement(n, DeviceLocation::Cpu);
2981            if n != x {
2982                g.set_target_backend(n, BackendId::Cpu);
2983            }
2984        }
2985        let branch = try_record_branch(
2986            &mut g,
2987            d,
2988            res,
2989            &[a, t],
2990            t,
2991            BackendId::Cuda,
2992            cuda0,
2993            DeviceLocation::Cpu,
2994        )
2995        .expect("well-formed branch")
2996        .expect("two arms");
2997        insert_residency_copies(
2998            &mut g,
2999            &[res],
3000            &ExecutionPlan::empty(),
3001            DeviceLocation::Cpu,
3002            None,
3003        );
3004
3005        let arm1_exit = g.node(branch).inputs[1];
3006        // The arm's result comes back to the host through a copy, so both exits live on one device.
3007        assert!(
3008            matches!(g.node(arm1_exit).op, Op::Copy { target } if target == DeviceLocation::Cpu),
3009            "arm 1's exit must be a copy back to the host; got {:?}",
3010            g.node(arm1_exit).op
3011        );
3012        let clone_t = g.node(arm1_exit).inputs[0];
3013        let clone_a = g.node(clone_t).inputs[0];
3014        assert_eq!(g.node(clone_a).op, Op::Add, "the clone of the entry node");
3015        // Both external inputs of the clone entry node go through a copy onto the alternative device.
3016        assert_eq!(g.node(clone_a).inputs.len(), 2);
3017        for &input in &g.node(clone_a).inputs {
3018            assert!(
3019                matches!(g.node(input).op, Op::Copy { target } if target == cuda0),
3020                "clone entry node reads {:?} ({:?}) from outside its arm with no copy onto {cuda0:?}",
3021                input,
3022                g.node(input).op,
3023            );
3024        }
3025        // The copies read the original host values (the shared diverge and the earlier node).
3026        let sources: Vec<NodeId> = g
3027            .node(clone_a)
3028            .inputs
3029            .iter()
3030            .map(|&c| g.node(c).inputs[0])
3031            .collect();
3032        assert_eq!(sources, vec![d, e]);
3033        // Arm 0 is untouched: still host to host, no copies.
3034        assert_eq!(g.node(a).inputs, vec![d, e]);
3035    }
3036
3037    /// ROW 157 / GAP-385, PURE FAN-OUT (no residual edge): `x -> n1 -> {q, k} -> a -> t`. The region is
3038    /// the fan-out and everything up to its join: diverge `x`, a four-node arm (`n1 q k a`), reconverge
3039    /// `t`. Born red: the one-node fork never forked `n1` (two consumers) and made one-node forks of
3040    /// `q`, `k` (sole consumer `a`) and `a`.
3041    #[test]
3042    fn fan_out_that_rejoins_is_one_multi_node_region() {
3043        let table = two_placement_table();
3044        let mut g = Graph::new();
3045        let x = f32_node(&mut g, Op::Const, vec![]);
3046        let n1 = f32_node(&mut g, Op::Relu, vec![x]);
3047        let q = f32_node(&mut g, Op::Silu, vec![n1]);
3048        let k = f32_node(&mut g, Op::Tanh, vec![n1]);
3049        let a = f32_node(&mut g, Op::Add, vec![q, k]);
3050        let t = f32_node(&mut g, Op::Relu, vec![a]);
3051
3052        let before = g.len();
3053        optimize_graph(&mut g, &[t], &table, &two_backend_opts()).expect("optimize_graph");
3054        let branches = branches_after(&g, before);
3055        assert_eq!(
3056            branches.iter().map(|&(_, e, r)| (e, r)).collect::<Vec<_>>(),
3057            vec![(a, t)],
3058            "one region: arm-0 exit a, reconverge t"
3059        );
3060        assert_eq!(
3061            g.len() - before,
3062            4 + 1,
3063            "four cloned nodes (n1 q k a) plus the branch node"
3064        );
3065    }
3066    /// Cross-device, production-shaped options: the realize device is a GPU (`Cuda { gpu_id: 0 }`), CPU is
3067    /// the always-feasible fallback device, and a transfer estimator is present, so the placement DP
3068    /// runs and prunes every node's alternative set to its committed device (the single-device-set
3069    /// invariant). This is the shape `build_optimized_graph` builds on a Vulkan/CUDA realize; the
3070    /// co-located `two_backend_opts` above never opens a DP row and so never reaches this pruning.
3071    struct FlatTransfer;
3072    impl crate::ranker::cost::TransferEstimator for FlatTransfer {
3073        fn estimate_transfer_ns(
3074            &self,
3075            src: DeviceLocation,
3076            dst: DeviceLocation,
3077            _bytes: u64,
3078        ) -> u64 {
3079            if src == dst { 0 } else { 1_000 }
3080        }
3081    }
3082    /// A kernel cost of 10_000 flops (10 us at the caps' 1 flop/ns) on every node: a transfer of 1_000 ns
3083    /// is then a small fraction of a node, as on a real model, rather than infinitely worse than a
3084    /// zero-cost kernel (which `unknown_cost` would give).
3085    fn ten_us_cost(
3086        _: &[Shape],
3087        _: &[DType],
3088        _: &crate::kernel::OpParams,
3089        _: &fuel_ir::backend::BackendCapabilities,
3090    ) -> crate::fused::CostEstimate {
3091        crate::fused::CostEstimate {
3092            flops: 10_000,
3093            bytes_moved: 0,
3094            kernel_overhead_ns: 0,
3095        }
3096    }
3097    /// The same node on the GPU prior (`default_backend_rates`: 30 flops/ns) at 300_000 flops, i.e. also
3098    /// 10 us: the CPU arm is then within the competitive factor. Without this the CPU arm would be ~30x
3099    /// slower and correctly NOT competitive, which is itself what a real GPU model looks like.
3100    fn ten_us_cost_gpu(
3101        _: &[Shape],
3102        _: &[DType],
3103        _: &crate::kernel::OpParams,
3104        _: &fuel_ir::backend::BackendCapabilities,
3105    ) -> crate::fused::CostEstimate {
3106        crate::fused::CostEstimate {
3107            flops: 300_000,
3108            bytes_moved: 0,
3109            kernel_overhead_ns: 0,
3110        }
3111    }
3112    fn costed_two_placement_table() -> KernelBindingTable {
3113        let mut table = KernelBindingTable::new();
3114        for (op, n_in) in [
3115            (OpKind::ReluElementwise, 1),
3116            (OpKind::SiluElementwise, 1),
3117            (OpKind::TanhElementwise, 1),
3118            (OpKind::AddElementwise, 2),
3119        ] {
3120            let mut dtypes = vec![DType::F32; n_in];
3121            dtypes.push(DType::F32);
3122            for (backend, kernel, cost) in [
3123                (
3124                    BackendId::Cpu,
3125                    noop_kernel as crate::kernel::KernelRef,
3126                    ten_us_cost as crate::kernel::CostFn,
3127                ),
3128                (
3129                    BackendId::Cuda,
3130                    noop_kernel_b as crate::kernel::KernelRef,
3131                    ten_us_cost_gpu as crate::kernel::CostFn,
3132                ),
3133            ] {
3134                table.register_full(
3135                    op,
3136                    &dtypes,
3137                    backend,
3138                    kernel,
3139                    KernelCaps::empty(),
3140                    PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3141                    cost,
3142                );
3143            }
3144        }
3145        table
3146    }
3147    fn gpu_placements(dev: DeviceLocation) -> Vec<BackendId> {
3148        match dev {
3149            DeviceLocation::Cuda { .. } => vec![BackendId::Cuda],
3150            DeviceLocation::Cpu => vec![BackendId::Cpu],
3151            _ => vec![],
3152        }
3153    }
3154    fn cpu_fallback(dev: DeviceLocation) -> Vec<(BackendId, DeviceLocation)> {
3155        if dev == DeviceLocation::Cpu {
3156            vec![]
3157        } else {
3158            vec![(BackendId::Cpu, DeviceLocation::Cpu)]
3159        }
3160    }
3161
3162    /// ROW 157 / GAP-385, PRODUCTION ENTRY (born red). Live run, Vulkan tiny-Llama, ref `db0c1f7a2`: every
3163    /// optimize reported 0 live `Op::Branch`; the pathfinder saw 0 nodes with two placements because
3164    /// `compile_plan` pruned each set to the DP-committed device. Here the same options shape
3165    /// (GPU realize device + CPU fallback + transfer estimator) over a residual block must still yield
3166    /// one multi-node region.
3167    #[test]
3168    fn cross_device_residual_block_forks_through_the_production_options_shape() {
3169        let table = costed_two_placement_table();
3170        let mut g = Graph::new();
3171        let x = f32_node(&mut g, Op::Const, vec![]);
3172        let n1 = f32_node(&mut g, Op::Relu, vec![x]);
3173        let q = f32_node(&mut g, Op::Silu, vec![n1]);
3174        let o = f32_node(&mut g, Op::Tanh, vec![q]);
3175        let res = f32_node(&mut g, Op::Add, vec![x, o]);
3176
3177        let est = FlatTransfer;
3178        let gpu = DeviceLocation::Cuda { gpu_id: 0 };
3179        let caps = fuel_ir::backend::BackendCapabilities {
3180            backend_id: BackendId::Cuda,
3181            device_location: gpu,
3182            op_dtype_support: std::collections::HashSet::new(),
3183            required_alignment: 64,
3184            access_granularity_bits: 8,
3185            transfer_paths: vec![(gpu, fuel_ir::backend::TransferPath::SameDevice)],
3186            storage_substrate: fuel_ir::backend::SubstrateClass::HostBytes,
3187            compute_throughput_flops_per_ns: 1.0,
3188            mem_bandwidth_bytes_per_ns: 4.0,
3189        };
3190        let caps_for = |_: BackendId| Some(&caps);
3191        let residency = |_: NodeId| Some(gpu);
3192        // Cost population stays ON (the default): `relaxed` merged enumeration, and with it the
3193        // placement DP, only runs when pricing is active, exactly as `build_optimized_graph` sets it.
3194        let opts = PlanOptions::new()
3195            .with_pinned_device(gpu)
3196            .with_placements_for_device(&gpu_placements)
3197            .with_fallback_placements_for(&cpu_fallback)
3198            .with_capabilities_for(&caps_for)
3199            .with_transfer_estimator(&est)
3200            .with_input_residency(&residency);
3201        let before = g.len();
3202        let optimized = optimize_graph(&mut g, &[res], &table, &opts).expect("optimize_graph");
3203        assert!(
3204            optimized.branch_count(&g) >= 1,
3205            "a GPU realize with a CPU fallback must expose a cross-device region; branches={:?}",
3206            branches_after(&g, before)
3207        );
3208    }
3209
3210    /// SIBLING of the test above: the same cross-device shape, but the GPU kernel is 30x cheaper than the
3211    /// CPU one (both at 10_000 flops, GPU prior 30 flops/ns). The CPU arm is not within the competitive
3212    /// factor, so NO region is recorded. This is what a real GPU model looks like; the test keeps the
3213    /// first one from passing by recording a region unconditionally.
3214    #[test]
3215    fn cross_device_cpu_arm_far_slower_than_the_gpu_is_not_competitive() {
3216        let mut table = KernelBindingTable::new();
3217        for (op, n_in) in [
3218            (OpKind::ReluElementwise, 1),
3219            (OpKind::SiluElementwise, 1),
3220            (OpKind::TanhElementwise, 1),
3221            (OpKind::AddElementwise, 2),
3222        ] {
3223            let mut dtypes = vec![DType::F32; n_in];
3224            dtypes.push(DType::F32);
3225            for (backend, kernel) in [
3226                (BackendId::Cpu, noop_kernel as crate::kernel::KernelRef),
3227                (BackendId::Cuda, noop_kernel_b as crate::kernel::KernelRef),
3228            ] {
3229                table.register_full(
3230                    op,
3231                    &dtypes,
3232                    backend,
3233                    kernel,
3234                    KernelCaps::empty(),
3235                    PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
3236                    ten_us_cost,
3237                );
3238            }
3239        }
3240        let mut g = Graph::new();
3241        let x = f32_node(&mut g, Op::Const, vec![]);
3242        let n1 = f32_node(&mut g, Op::Relu, vec![x]);
3243        let q = f32_node(&mut g, Op::Silu, vec![n1]);
3244        let o = f32_node(&mut g, Op::Tanh, vec![q]);
3245        let res = f32_node(&mut g, Op::Add, vec![x, o]);
3246        let est = FlatTransfer;
3247        let gpu = DeviceLocation::Cuda { gpu_id: 0 };
3248        let caps = fuel_ir::backend::BackendCapabilities {
3249            backend_id: BackendId::Cuda,
3250            device_location: gpu,
3251            op_dtype_support: std::collections::HashSet::new(),
3252            required_alignment: 64,
3253            access_granularity_bits: 8,
3254            transfer_paths: vec![(gpu, fuel_ir::backend::TransferPath::SameDevice)],
3255            storage_substrate: fuel_ir::backend::SubstrateClass::HostBytes,
3256            compute_throughput_flops_per_ns: 1.0,
3257            mem_bandwidth_bytes_per_ns: 4.0,
3258        };
3259        let caps_for = |_: BackendId| Some(&caps);
3260        let residency = |_: NodeId| Some(gpu);
3261        let opts = PlanOptions::new()
3262            .with_pinned_device(gpu)
3263            .with_placements_for_device(&gpu_placements)
3264            .with_fallback_placements_for(&cpu_fallback)
3265            .with_capabilities_for(&caps_for)
3266            .with_transfer_estimator(&est)
3267            .with_input_residency(&residency);
3268        let optimized = optimize_graph(&mut g, &[res], &table, &opts).expect("optimize_graph");
3269        assert_eq!(
3270            optimized.branch_count(&g),
3271            0,
3272            "a CPU arm ~30x slower than the GPU is not competitive within the factor of 2"
3273        );
3274    }
3275
3276    /// SABOTAGE SIBLING (row 157): a node read from outside the stretch must not sit inside a region.
3277    /// `n1` is read by `m` and by a second realize root `side`, so no region may contain it; `m` alone
3278    /// (diverge `n1`, reconverge `t`) is still a valid one-node region.
3279    #[test]
3280    fn a_node_read_from_outside_the_stretch_is_not_inside_a_region() {
3281        let table = two_placement_table();
3282        let mut g = Graph::new();
3283        let x = f32_node(&mut g, Op::Const, vec![]);
3284        let n1 = f32_node(&mut g, Op::Relu, vec![x]);
3285        let m = f32_node(&mut g, Op::Silu, vec![n1]);
3286        let t = f32_node(&mut g, Op::Relu, vec![m]);
3287        let side = f32_node(&mut g, Op::Tanh, vec![n1]);
3288        let before = g.len();
3289        optimize_graph(&mut g, &[t, side], &table, &two_backend_opts()).expect("optimize_graph");
3290        let exits: Vec<NodeId> = branches_after(&g, before).iter().map(|b| b.1).collect();
3291        assert!(
3292            !exits.contains(&n1),
3293            "n1 is read by a second root and cannot be an arm exit"
3294        );
3295    }
3296
3297    /// SABOTAGE SIBLING (row 157): a stretch is only as long as the nodes that have the alternative.
3298    /// `s` is CPU-only, so no region may span it; the two Relu nodes each fork alone.
3299    #[test]
3300    fn a_node_without_the_alternative_kernel_splits_the_region() {
3301        let mut table = KernelBindingTable::new();
3302        register_two_backend(&mut table, OpKind::ReluElementwise, 1);
3303        register_elementwise(&mut table, OpKind::SiluElementwise, 1); // CPU only
3304        let mut g = Graph::new();
3305        let x = f32_node(&mut g, Op::Const, vec![]);
3306        let r1 = f32_node(&mut g, Op::Relu, vec![x]);
3307        let s = f32_node(&mut g, Op::Silu, vec![r1]);
3308        let r2 = f32_node(&mut g, Op::Relu, vec![s]);
3309        let t = f32_node(&mut g, Op::Relu, vec![r2]);
3310        let before = g.len();
3311        optimize_graph(&mut g, &[t], &table, &two_backend_opts()).expect("optimize_graph");
3312        let mut exits: Vec<NodeId> = branches_after(&g, before).iter().map(|b| b.1).collect();
3313        exits.sort_by_key(|n| n.0);
3314        assert!(
3315            !exits.contains(&s),
3316            "the CPU-only node is never an arm exit"
3317        );
3318        // r2 and t form one two-node stretch? t is the root, so only r1 and r2 can be interior.
3319        assert_eq!(
3320            exits,
3321            vec![r1, r2],
3322            "r1 forks alone, r2 forks alone, nothing spans s"
3323        );
3324    }
3325
3326    /// SABOTAGE SIBLING (row 157): one placement per node means no region at all.
3327    #[test]
3328    fn a_single_placement_graph_gets_no_regions() {
3329        let mut table = KernelBindingTable::new();
3330        register_elementwise(&mut table, OpKind::ReluElementwise, 1);
3331        register_elementwise(&mut table, OpKind::SiluElementwise, 1);
3332        let mut g = Graph::new();
3333        let x = f32_node(&mut g, Op::Const, vec![]);
3334        let a = f32_node(&mut g, Op::Relu, vec![x]);
3335        let b = f32_node(&mut g, Op::Silu, vec![a]);
3336        let c = f32_node(&mut g, Op::Relu, vec![b]);
3337        let before = g.len();
3338        let optimized = optimize_graph(&mut g, &[c], &table, &cpu_opts()).expect("optimize_graph");
3339        assert_eq!(optimized.branch_count(&g), 0);
3340        assert_eq!(g.len(), before, "no clones are left behind");
3341    }
3342
3343    // ===== Load-aware arm pick through the PRODUCTION realize entry
3344    //        (row 158 slice 2: estimated-completion, not queue-depth) =====
3345
3346    /// Records the backend of every candidate the wrapped selector picks, so
3347    /// a test can read WHICH arm the production picking entry chose.
3348    #[derive(Debug)]
3349    struct RecordingSelector {
3350        inner: crate::ranker::ChainedSelector,
3351        picked: std::sync::Mutex<Vec<BackendId>>,
3352    }
3353
3354    impl crate::ranker::RuntimeSelector for RecordingSelector {
3355        fn select<'a>(
3356            &self,
3357            set: &'a crate::ranker::AlternativeSet,
3358        ) -> Option<&'a crate::ranker::Candidate> {
3359            let picked = self.inner.select(set);
3360            if let Some(c) = picked {
3361                self.picked.lock().unwrap().push(c.backend);
3362            }
3363            picked
3364        }
3365    }
3366
3367    /// Judge answering per BACKEND only. The pick enumerates candidates from
3368    /// the process-wide binding table (real `portable-cpu` kernel with a
3369    /// revision hash; a synthetic CUDA stand-in), so a cell-keyed judge would
3370    /// couple the test to those tags.
3371    struct BackendJudge {
3372        cuda_ns: u64,
3373        cpu_ns: u64,
3374    }
3375
3376    impl crate::ranker::JudgeOracle for BackendJudge {
3377        fn measured_latency_ns(
3378            &self,
3379            _op: OpKind,
3380            _dtype: DType,
3381            _size_class: fuel_ir::dispatch::SizeClass,
3382            backend: BackendId,
3383            _kernel_source: &str,
3384            _kernel_revision_hash: u64,
3385        ) -> Option<u64> {
3386            match backend {
3387                BackendId::Cuda => Some(self.cuda_ns),
3388                BackendId::Cpu => Some(self.cpu_ns),
3389                _ => None,
3390            }
3391        }
3392    }
3393
3394    /// Realize the single-fork graph through
3395    /// `PipelinedExecutor::realize_with_optimized_picking_env` (the entry the
3396    /// bridge calls) with a `ChainedSelector` over `lookup` and a Judge that
3397    /// measures the fork op at `cuda_ns` on CUDA and `cpu_ns` on CPU. Returns
3398    /// the backends the streaming pick chose for the (one) branch.
3399    ///
3400    /// Also returns the realize result (`"Ok"` or `Err(..)` as text), so a
3401    /// run with no pick names its cause instead of reading as "no pick".
3402    ///
3403    /// Holds `TOPOLOGY_TEST_GATE` for writing from before `optimize_graph`
3404    /// until the realize returns: the executor returns the typed
3405    /// `Error::TopologyChanged` when another test in this binary bumps the
3406    /// process-wide topology generation in between, and then the streaming
3407    /// walk never reaches the branch (ROADMAP row 165). The gate stops a
3408    /// sibling's bump from landing in that window; there is no retry.
3409    fn picked_backends_through_realize(
3410        lookup: crate::ranker::BackendRuntimeLookup,
3411        cuda_ns: u64,
3412        cpu_ns: u64,
3413    ) -> (Vec<BackendId>, String) {
3414        use crate::PipelinedExecutor;
3415        use crate::pipelined::StorageCache;
3416        use crate::ranker::ChainedSelector;
3417        use fuel_ir::SymEnv;
3418
3419        // Build the lazily initialised process-wide tables BEFORE taking the
3420        // gate: their initialisation bumps the generation, and a bump under
3421        // our own write guard would wait on ourselves.
3422        drop(crate::dispatch::global_bindings());
3423        let _crate_gate = crate::dispatch::TOPOLOGY_TEST_GATE
3424            .write()
3425            .unwrap_or_else(|poisoned| poisoned.into_inner());
3426
3427        let mut table = KernelBindingTable::new();
3428        let (mut g, _prod, _fork, _tail, root) = build_single_fork_graph(&mut table);
3429        let optimized = optimize_graph(&mut g, &[root], &table, &two_backend_opts())
3430            .expect("optimize_graph succeeds");
3431        assert_eq!(optimized.branch_count(&g), 1, "exactly one branch");
3432
3433        let selector = Arc::new(RecordingSelector {
3434            inner: ChainedSelector::with_default_estimator(
3435                Some(Arc::new(BackendJudge { cuda_ns, cpu_ns })),
3436                Some(lookup.clone()),
3437            ),
3438            picked: std::sync::Mutex::new(Vec::new()),
3439        });
3440
3441        let graph = Arc::new(RwLock::new(g));
3442        let mut cache = StorageCache::new();
3443        cache.insert(
3444            NodeId(0),
3445            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
3446                1.0_f32, 2.0, 3.0, 4.0,
3447            ]))),
3448        );
3449        // The CUDA arm has no device behind it in a CPU test, so a realize
3450        // that picked CUDA ends in a device error at the reconverge node; a
3451        // realize that picked CPU runs end to end. The result is returned, not
3452        // ignored, so the caller pins which.
3453        let result = PipelinedExecutor::realize_with_optimized_picking_env(
3454            graph,
3455            root,
3456            cache,
3457            &optimized,
3458            Some(selector.clone() as Arc<dyn crate::ranker::RuntimeSelector>),
3459            Some(lookup),
3460            SymEnv::default(),
3461        );
3462        let outcome = match result {
3463            Ok(_) => "Ok".to_string(),
3464            Err(e) => format!("Err({e:?})"),
3465        };
3466        let picks = selector.picked.lock().unwrap().clone();
3467        (picks, outcome)
3468    }
3469
3470    /// Row 158 slice 2. CUDA measures 100 ns on the fork op, CPU 100 us.
3471    /// The device load must be read as estimated BACKLOG TIME, not as a
3472    /// queue-depth bucket:
3473    ///  - idle CUDA                      -> CUDA arm;
3474    ///  - CUDA with ONE op queued (the count bucket says "saturated") but
3475    ///    only 1 us of estimated backlog -> STILL the CUDA arm (1.1 us beats
3476    ///    CPU's 100 us); the count tier wrongly sends this to CPU;
3477    ///  - CUDA with a 1 hour backlog     -> the CPU arm.
3478    ///
3479    /// SHOWS: the streaming pick, reached through the production picking
3480    /// realize entry, ranks arms by backlog + measured latency.
3481    /// DOES NOT SHOW: that the executor's submit sites feed the backlog
3482    /// (the lookup here injects it), nor that kernels ran on either arm.
3483    #[test]
3484    fn load_aware_pick_ranks_by_estimated_completion_through_realize() {
3485        use crate::ranker::mock_backlog_lookup;
3486        const HOUR_NS: u64 = 3_600_000_000_000;
3487
3488        let (idle, idle_r) = picked_backends_through_realize(
3489            mock_backlog_lookup(vec![(BackendId::Cuda, 0, 0)]),
3490            100,
3491            100_000,
3492        );
3493        assert_eq!(
3494            idle,
3495            vec![BackendId::Cuda],
3496            "idle GPU -> GPU arm; realize={idle_r}"
3497        );
3498
3499        let (one_op, one_op_r) = picked_backends_through_realize(
3500            mock_backlog_lookup(vec![(BackendId::Cuda, 1, 1_000)]),
3501            100,
3502            100_000,
3503        );
3504        assert_eq!(
3505            one_op,
3506            vec![BackendId::Cuda],
3507            "1 op / 1 us backlog: GPU still finishes first (1.1 us vs 100 us); realize={one_op_r}",
3508        );
3509
3510        let (hour, hour_r) = picked_backends_through_realize(
3511            mock_backlog_lookup(vec![(BackendId::Cuda, 1, HOUR_NS)]),
3512            100,
3513            100_000,
3514        );
3515        assert_eq!(
3516            hour,
3517            vec![BackendId::Cpu],
3518            "1 h GPU backlog -> CPU arm; realize={hour_r}"
3519        );
3520        assert_eq!(hour_r, "Ok", "the CPU arm realizes end to end");
3521    }
3522}