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()
2048                || matches!(
2049                    result.as_ref().map_err(Error::root_cause),
2050                    Err(Error::TopologyChanged { .. })
2051                ),
2052            "a picked realize over a branched graph must either succeed or hit the \
2053             (unrelated, expected-under-concurrency) TopologyChanged race: {:?}",
2054            result.err()
2055        );
2056        assert!(
2057            order_cache.get().is_none(),
2058            "a branched graph with a real selector pick must NEVER populate order_cache — \
2059             it must route through OrderSource::Streaming, not OrderSource::Cached",
2060        );
2061
2062        // A second call, same cache slot: still must not populate it.
2063        let result2 = PipelinedExecutor::realize_with_optimized_picking_cached_env(
2064            graph,
2065            root,
2066            cache,
2067            &optimized,
2068            &order_cache,
2069            Some(selector),
2070            None,
2071            SymEnv::default(),
2072        );
2073        assert!(
2074            result2.is_ok()
2075                || matches!(
2076                    result2.as_ref().map_err(Error::root_cause),
2077                    Err(Error::TopologyChanged { .. })
2078                ),
2079            "second picked realize must either succeed or hit the same expected-under- \
2080             concurrency TopologyChanged race: {:?}",
2081            result2.err()
2082        );
2083        assert!(
2084            order_cache.get().is_none(),
2085            "order_cache must still be empty after a second picked realize",
2086        );
2087    }
2088
2089    /// Deterministic sibling of the test above: forces the EXACT race
2090    /// `Error::TopologyChanged` tolerance was added for, instead of relying
2091    /// on another test in the binary to collide by chance. Proves two
2092    /// things the flaky-under-`-j4` observation alone couldn't: (1) that a
2093    /// stale `optimized.generation` is SUFFICIENT to reproduce the exact
2094    /// failure this test's sibling hit (confirming the root cause, not
2095    /// just a plausible story), and (2) that `order_cache` stays empty
2096    /// even on the `Err` branch (the property this test file is actually
2097    /// about, independent of the race).
2098    ///
2099    /// Deliberately does NOT call the real, process-wide
2100    /// `bump_topology_generation()` to force this — that would inflict the
2101    /// exact `-j4` cross-test hazard this test documents onto every OTHER
2102    /// concurrently-running test in the binary that assumes a stable
2103    /// generation (an earlier draft of this test did exactly that, and
2104    /// broke `realize_with_optimized_picking_cached_env_matches_arm0_cold_and_warm`
2105    /// under `-j4`). `OptimizedGraph::generation` is `pub`, so mutating
2106    /// this test's own LOCAL copy to a value that can't match the live
2107    /// counter reproduces the identical code path with zero blast radius.
2108    #[test]
2109    fn cached_env_tolerates_a_concurrent_topology_generation_bump() {
2110        use crate::PipelinedExecutor;
2111        use fuel_ir::{Error, SymEnv};
2112
2113        let (graph, cache, mut optimized, order_cache, selector, root) = cached_env_test_fixture();
2114
2115        // Simulate a sibling test's legitimate `register_runtime_kernel`/
2116        // `extend_global_bindings` call landing between `optimize_graph`
2117        // (which stamped `optimized.generation` above) and this realize —
2118        // exactly the collision `cached_env_never_caches_a_branched_graph_with_a_real_selector`
2119        // hit under `-j4` — by staling THIS test's own copy of the stamp,
2120        // not the shared live counter every other test also reads.
2121        optimized.generation = optimized.generation.wrapping_add(1);
2122
2123        let result = PipelinedExecutor::realize_with_optimized_picking_cached_env(
2124            graph,
2125            root,
2126            cache,
2127            &optimized,
2128            &order_cache,
2129            Some(selector),
2130            None,
2131            SymEnv::default(),
2132        );
2133        assert!(
2134            matches!(
2135                result.as_ref().map_err(Error::root_cause),
2136                Err(Error::TopologyChanged { .. })
2137            ),
2138            "a forced generation bump before realize must surface as TopologyChanged, \
2139             not silently succeed or fail some other way: {:?}",
2140            result
2141        );
2142        assert!(
2143            order_cache.get().is_none(),
2144            "order_cache must stay empty even when the realize that would have \
2145             populated it (if it were ever going to) failed with TopologyChanged",
2146        );
2147    }
2148
2149    /// (d) No `DEFAULT_MAX_N` truncation: the fork records the winner +
2150    /// a runner-up without a fixed top-N cap stranding placements. Both
2151    /// arms survive; the per-device frontier — not a fixed N — bounds
2152    /// the arms.
2153    #[test]
2154    fn no_default_max_n_truncation() {
2155        let mut table = KernelBindingTable::new();
2156        let (mut g, _prod, fork, _tail, root) = build_single_fork_graph(&mut table);
2157        let opts = two_backend_opts();
2158
2159        let optimized =
2160            optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph succeeds");
2161        assert_eq!(optimized.branch_count(&g), 1);
2162        let branch_id = (0..g.len())
2163            .map(NodeId)
2164            .find(|&id| matches!(g.node(id).op, Op::Branch { .. }))
2165            .expect("a Branch node exists");
2166        // Two distinct placements ⇒ two arms survive; the runner-up was
2167        // not dropped by any top-N cap.
2168        assert_eq!(g.node(branch_id).inputs.len(), 2);
2169        assert_eq!(g.node(branch_id).inputs[0], fork);
2170    }
2171
2172    /// THE EQUIVALENCE GATE (born-red until `optimize_graph` exists and
2173    /// its lowered order matches `compile_plan`).
2174    ///
2175    /// On representative no-competing-route graphs, assert:
2176    ///   (a) `optimize_graph` leaves ZERO `Op::Branch` nodes, and
2177    ///   (b) the concatenated `extract_runs`/`lower_run` dispatch order
2178    ///       EQUALS today's `compile_plan(...).order` exactly (same
2179    ///       NodeIds, same order).
2180    #[test]
2181    fn equivalence_gate_branchless_order_matches_compile_plan() {
2182        for build in [
2183            build_straight_line_graph as fn(&mut KernelBindingTable) -> (Graph, NodeId),
2184            build_branchless_graph as fn(&mut KernelBindingTable) -> (Graph, NodeId),
2185        ] {
2186            let mut table = KernelBindingTable::new();
2187            let (mut g, root) = build(&mut table);
2188            let opts = cpu_opts();
2189
2190            // Today's path: the exact order the executor walks.
2191            let order = execution_plan(&g, &[root]);
2192            let plan = compile_plan(&g, &order, &table, &opts)
2193                .expect("today's compile_plan succeeds on a placeable graph");
2194
2195            // New path.
2196            let optimized = optimize_graph(&mut g, &[root], &table, &opts)
2197                .expect("optimize_graph succeeds on the same graph");
2198
2199            // (a) zero competing routes => zero Branch nodes.
2200            assert_eq!(
2201                optimized.branch_count(&g),
2202                0,
2203                "a no-competing-route graph optimizes to zero Op::Branch nodes",
2204            );
2205
2206            // (b) EXACT order equality against compile_plan(...).order.
2207            let lowered = optimized.dispatch_order(&g);
2208            assert_eq!(
2209                lowered, plan.order,
2210                "the extract_runs/lower_run dispatch order must equal \
2211                 compile_plan(...).order exactly (same NodeIds, same order)",
2212            );
2213            // And it covers every reachable node — the executor walks
2214            // the whole graph, runs partition it with no gaps/dupes.
2215            assert_eq!(
2216                lowered.len(),
2217                order.len(),
2218                "the lowered order covers every node compile_plan ordered",
2219            );
2220        }
2221    }
2222
2223    /// `optimize_graph` on a branchless graph is idempotent and adds no
2224    /// nodes: the node count is unchanged across repeated calls, the
2225    /// branch count stays zero, and the lowered order is stable.
2226    #[test]
2227    fn optimize_graph_branchless_is_idempotent_and_adds_no_nodes() {
2228        let mut table = KernelBindingTable::new();
2229        let (mut g, root) = build_branchless_graph(&mut table);
2230        let opts = cpu_opts();
2231
2232        let nodes_before = g.len();
2233        let first =
2234            optimize_graph(&mut g, &[root], &table, &opts).expect("first optimize succeeds");
2235        let order_first = first.dispatch_order(&g);
2236        let nodes_after_first = g.len();
2237
2238        let second =
2239            optimize_graph(&mut g, &[root], &table, &opts).expect("second optimize succeeds");
2240        let order_second = second.dispatch_order(&g);
2241        let nodes_after_second = g.len();
2242
2243        assert_eq!(
2244            nodes_before, nodes_after_first,
2245            "optimize_graph adds no nodes (A3a is single-route-only)",
2246        );
2247        assert_eq!(
2248            nodes_after_first, nodes_after_second,
2249            "a second optimize_graph adds no further nodes — idempotent",
2250        );
2251        assert_eq!(first.branch_count(&g), 0, "no branches after first");
2252        assert_eq!(second.branch_count(&g), 0, "no branches after second");
2253        assert_eq!(
2254            order_first, order_second,
2255            "the lowered dispatch order is stable across repeated optimize",
2256        );
2257    }
2258
2259    /// Identity proof for `docs/design/incremental-consumer-index.md` §5's
2260    /// `order_for` fix track: that fix proposes memoizing `dispatch_order`'s
2261    /// output WHOLESALE once per plan-once session, instead of recomputing
2262    /// it (via `extract_runs_multi` + `non_chosen_arm_nodes`, measured
2263    /// ~56ms/step, the single largest named sub-cost in a live decode step)
2264    /// on every `realize_inner` call. That's only valid if calling
2265    /// `dispatch_order` repeatedly on the SAME `OptimizedGraph` view with NO
2266    /// intervening graph mutation — exactly the plan-once decode shape,
2267    /// where only leaf values are rebound between tokens, never the graph's
2268    /// structure — yields a byte-identical `Vec<NodeId>` every time. Proven
2269    /// here, not assumed: five repeated calls, two structurally different
2270    /// branchless graphs (a fan-in boundary and a plain chain), zero
2271    /// mutation between calls (deliberately — this is NOT the existing
2272    /// `optimize_graph_branchless_is_idempotent_and_adds_no_nodes` test
2273    /// above, which re-runs `optimize_graph` itself between its two
2274    /// `dispatch_order` calls; this one proves `dispatch_order` is pure on
2275    /// its own, independent of re-optimizing).
2276    #[test]
2277    fn dispatch_order_is_stable_across_repeated_calls_with_no_mutation() {
2278        for build in [
2279            build_branchless_graph as fn(&mut KernelBindingTable) -> (Graph, NodeId),
2280            build_straight_line_graph,
2281        ] {
2282            let mut table = KernelBindingTable::new();
2283            let (mut g, root) = build(&mut table);
2284            let opts = cpu_opts();
2285            let optimized = optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph");
2286
2287            let orders: Vec<Vec<NodeId>> = (0..5).map(|_| optimized.dispatch_order(&g)).collect();
2288            for (i, order) in orders.iter().enumerate().skip(1) {
2289                assert_eq!(
2290                    &orders[0], order,
2291                    "dispatch_order call {i} diverged from call 0 with no intervening \
2292                     mutation — the order_for memoization fix would be UNSAFE if this failed",
2293                );
2294            }
2295        }
2296    }
2297
2298    /// Build-time validation: optimize_graph fails fast (Result, never
2299    /// panic) when a kernel-bearing node has no registered binding —
2300    /// reusing compile_plan's missing-binding diagnostic.
2301    #[test]
2302    fn optimize_graph_fails_fast_on_missing_binding() {
2303        let table = KernelBindingTable::new(); // empty — no bindings.
2304        let mut g = Graph::new();
2305        let a = f32_node(&mut g, Op::Const, vec![]);
2306        let relu = f32_node(&mut g, Op::Relu, vec![a]);
2307        let opts = cpu_opts();
2308
2309        let err = optimize_graph(&mut g, &[relu], &table, &opts)
2310            .map(|_| ())
2311            .unwrap_err();
2312        match err {
2313            fuel_ir::Error::NoBackendForOp { op, .. } => {
2314                assert_eq!(op, OpKind::ReluElementwise);
2315            }
2316            other => panic!("expected NoBackendForOp, got {other:?}"),
2317        }
2318    }
2319
2320    // ===== Phase B PR-B3: the lock-step pathfinder/ranker/optimizer
2321    //        driver. =====
2322
2323    use crate::driver::{
2324        FrontierConvergenceOptimizer, OptimizationContext, Optimizer, PassRegistry, Pathfinder,
2325        PlacementForkPathfinder,
2326    };
2327    use std::collections::HashSet;
2328
2329    /// Snapshot of a graph's `Op::Branch` decision points, keyed by
2330    /// arena order: `(branch_id, reconverge_at, arm NodeIds)`. Two
2331    /// optimization paths that produce the same snapshot produced the
2332    /// same multi-path graph (behavior-preservation).
2333    fn branch_snapshot(g: &Graph) -> Vec<(NodeId, NodeId, Vec<NodeId>)> {
2334        (0..g.len())
2335            .map(NodeId)
2336            .filter_map(|id| match g.node(id).op {
2337                Op::Branch { reconverge_at } => {
2338                    Some((id, reconverge_at, g.node(id).inputs.clone()))
2339                }
2340                _ => None,
2341            })
2342            .collect()
2343    }
2344
2345    /// THE LOAD-BEARING BEHAVIOR-PRESERVATION GATE (born-red until
2346    /// `optimize_graph` routes through the lock-step driver).
2347    ///
2348    /// On a representative multi-placement graph, the driver
2349    /// (`PassRegistry::default_passes().run_lockstep`) produces the
2350    /// **identical** multi-path graph as the old hardcoded sequence
2351    /// (pathfinder then optimizer, in that order): same branch count,
2352    /// same arm-0 winner, same arms, same reconverge points, and the
2353    /// same arm-0 dispatch order. B3 is a structural refactor — the
2354    /// optimized result must not change.
2355    #[test]
2356    fn driver_matches_legacy_sequence() {
2357        // (A) The reference: drive the registered passes BY HAND in the
2358        //     legacy order (propose, then prune) onto a freshly compiled
2359        //     plan — exactly what the pre-B3 hardcoded sequence did.
2360        let mut ref_table = KernelBindingTable::new();
2361        let (mut ref_g, _prod, ref_fork, _tail, ref_root) = build_single_fork_graph(&mut ref_table);
2362        let opts = two_backend_opts();
2363        let ref_order = execution_plan(&ref_g, &[ref_root]);
2364        let ref_plan = compile_plan(&ref_g, &ref_order, &ref_table, &opts)
2365            .expect("reference compile_plan succeeds");
2366        {
2367            let guard: HashSet<NodeId> = HashSet::new();
2368            let ctx = OptimizationContext {
2369                order: &ref_order,
2370                plan: &ref_plan,
2371                cycle_guard: &guard,
2372                bindings: &ref_table,
2373            };
2374            // Legacy order: the pathfinder ADDs, then the optimizer
2375            // prunes — the same two operations the hardcoded sequence ran.
2376            PlacementForkPathfinder
2377                .propose(&mut ref_g, &ctx)
2378                .expect("pathfinder proposes");
2379            FrontierConvergenceOptimizer
2380                .prune(&mut ref_g, &ctx)
2381                .expect("optimizer prunes");
2382        }
2383        let ref_snapshot = branch_snapshot(&ref_g);
2384        let ref_dispatch = fuel_graph::lower_runs_arm0(&ref_g, &[ref_root]);
2385
2386        // (B) The driver path: optimize_graph routes through
2387        //     PassRegistry::default_passes().run_lockstep.
2388        let mut table = KernelBindingTable::new();
2389        let (mut g, _p, fork, _t, root) = build_single_fork_graph(&mut table);
2390        let optimized =
2391            optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph succeeds");
2392        let got_snapshot = branch_snapshot(&g);
2393        let got_dispatch = optimized.dispatch_order(&g);
2394
2395        // Identical multi-path graph: same branches, arms, reconverge.
2396        assert_eq!(
2397            got_snapshot, ref_snapshot,
2398            "driver produces the identical Op::Branch structure as the legacy \
2399             pathfinder→optimizer sequence",
2400        );
2401        assert_eq!(
2402            got_snapshot.len(),
2403            1,
2404            "the representative multi-placement graph produces exactly one branch",
2405        );
2406        assert_eq!(
2407            got_snapshot[0].2[0], fork,
2408            "arm-0 is the DP winner (the route realize uses)",
2409        );
2410        // Identical dispatch order (arm-0 single-route lowering).
2411        assert_eq!(
2412            got_dispatch, ref_dispatch,
2413            "driver yields the identical arm-0 dispatch order as the legacy sequence",
2414        );
2415        let _ = ref_fork;
2416    }
2417
2418    /// A no-op registry (no registered pathfinders) leaves a branchless
2419    /// graph unchanged: no nodes added, zero branches, identical
2420    /// dispatch order. Proves the driver itself introduces no structure.
2421    #[test]
2422    fn noop_registry_leaves_branchless_graph_unchanged() {
2423        let mut table = KernelBindingTable::new();
2424        let (mut g, root) = build_branchless_graph(&mut table);
2425        let opts = cpu_opts();
2426
2427        let order = execution_plan(&g, &[root]);
2428        let plan = compile_plan(&g, &order, &table, &opts).expect("compile_plan succeeds");
2429
2430        let dispatch_before = fuel_graph::lower_runs_arm0(&g, &[root]);
2431        let nodes_before = g.len();
2432
2433        let registry = PassRegistry::new(); // empty — no passes.
2434        assert_eq!(registry.pathfinder_count(), 0);
2435        assert_eq!(registry.optimizer_count(), 0);
2436
2437        let guard: HashSet<NodeId> = HashSet::new();
2438        let ctx = OptimizationContext {
2439            order: &order,
2440            plan: &plan,
2441            cycle_guard: &guard,
2442            bindings: &table,
2443        };
2444        registry
2445            .run_lockstep(&mut g, &ctx)
2446            .expect("empty registry runs cleanly");
2447
2448        assert_eq!(g.len(), nodes_before, "no-op registry adds no nodes");
2449        let branches = (0..g.len())
2450            .map(NodeId)
2451            .filter(|&id| matches!(g.node(id).op, Op::Branch { .. }))
2452            .count();
2453        assert_eq!(branches, 0, "no-op registry adds no branches");
2454        let dispatch_after = fuel_graph::lower_runs_arm0(&g, &[root]);
2455        assert_eq!(
2456            dispatch_before, dispatch_after,
2457            "no-op registry leaves the dispatch order unchanged",
2458        );
2459    }
2460
2461    /// Lock-step ordering: a pathfinder ADDs before its dependent
2462    /// optimizer PRUNEs. We register a recording pathfinder and a
2463    /// recording optimizer that each stamp a shared log when invoked;
2464    /// `run_lockstep` must invoke the pathfinder strictly before the
2465    /// optimizer (prune-as-you-go, never optimizer-first).
2466    #[test]
2467    fn lockstep_runs_pathfinder_before_dependent_optimizer() {
2468        use std::sync::{Arc, Mutex};
2469
2470        #[derive(Clone)]
2471        struct RecordPathfinder(Arc<Mutex<Vec<&'static str>>>);
2472        impl Pathfinder for RecordPathfinder {
2473            fn name(&self) -> &'static str {
2474                "RecordPathfinder"
2475            }
2476            fn propose(
2477                &self,
2478                _g: &mut Graph,
2479                _ctx: &OptimizationContext<'_>,
2480            ) -> fuel_ir::Result<()> {
2481                self.0.lock().unwrap().push("propose");
2482                Ok(())
2483            }
2484        }
2485        #[derive(Clone)]
2486        struct RecordOptimizer(Arc<Mutex<Vec<&'static str>>>);
2487        impl Optimizer for RecordOptimizer {
2488            fn name(&self) -> &'static str {
2489                "RecordOptimizer"
2490            }
2491            fn prune(&self, _g: &mut Graph, _ctx: &OptimizationContext<'_>) -> fuel_ir::Result<()> {
2492                self.0.lock().unwrap().push("prune");
2493                Ok(())
2494            }
2495        }
2496
2497        let log = Arc::new(Mutex::new(Vec::new()));
2498        let registry = PassRegistry::new()
2499            .with_pathfinder(Box::new(RecordPathfinder(log.clone())))
2500            .with_optimizer(Box::new(RecordOptimizer(log.clone())));
2501
2502        let mut g = Graph::new();
2503        let _a = f32_node(&mut g, Op::Const, vec![]);
2504        let plan = ExecutionPlan::empty();
2505        let order: Vec<NodeId> = Vec::new();
2506        let guard: HashSet<NodeId> = HashSet::new();
2507        let table = KernelBindingTable::new();
2508        let ctx = OptimizationContext {
2509            order: &order,
2510            plan: &plan,
2511            cycle_guard: &guard,
2512            bindings: &table,
2513        };
2514        registry.run_lockstep(&mut g, &ctx).expect("drive runs");
2515
2516        let seq = log.lock().unwrap().clone();
2517        assert_eq!(
2518            seq,
2519            vec!["propose", "prune"],
2520            "lock-step drive runs the pathfinder ADD strictly before its \
2521             dependent optimizer PRUNE (prune-as-you-go)",
2522        );
2523    }
2524
2525    // ---- GAP-380 (a1): lower a fused op with no kernel on the pinned device -------------------
2526
2527    /// `[q, k_cache, v_cache, block_table, context_lens]` consts, a fused PAGED_ATTN, and a
2528    /// `Contiguize` consumer. Returns `(graph, consumer)`.
2529    fn paged_attn_graph() -> (Graph, NodeId) {
2530        use fuel_graph::registry::{FusedOpParams, FusedOps};
2531        let mut g = Graph::new();
2532        let mut leaf = |dims: &[usize], dtype: DType| {
2533            g.push(Node {
2534                op: Op::Const,
2535                inputs: vec![],
2536                shape: Shape::from_dims(dims),
2537                dtype,
2538            })
2539        };
2540        let q = leaf(&[1, 2, 1, 4], DType::F32);
2541        let kc = leaf(&[3, 2, 2, 4], DType::F32);
2542        let vc = leaf(&[3, 2, 2, 4], DType::F32);
2543        let bt = leaf(&[1, 2], DType::U32);
2544        let cl = leaf(&[1], DType::U32);
2545        let fused = g.push(Node {
2546            op: Op::Fused(
2547                FusedOps::PAGED_ATTN,
2548                FusedOpParams::PagedAttn {
2549                    softmax_scale: 0.5,
2550                    block_size: 2,
2551                    softcap: None,
2552                },
2553            ),
2554            inputs: vec![q, kc, vc, bt, cl],
2555            shape: Shape::from_dims(&[1, 2, 1, 4]),
2556            dtype: DType::F32,
2557        });
2558        let consumer = g.push(Node {
2559            op: Op::Contiguize,
2560            inputs: vec![fused],
2561            shape: Shape::from_dims(&[1, 2, 1, 4]),
2562            dtype: DType::F32,
2563        });
2564        (g, consumer)
2565    }
2566
2567    fn paged_attn_nodes(g: &Graph, root: NodeId) -> usize {
2568        topo_order_multi(g, &[root])
2569            .into_iter()
2570            .filter(|&n| {
2571                matches!(
2572                    g.node(n).op,
2573                    Op::Fused(fuel_graph::registry::FusedOps::PAGED_ATTN, _)
2574                )
2575            })
2576            .count()
2577    }
2578
2579    #[test]
2580    fn a_cuda_pin_with_no_cuda_paged_attn_kernel_lowers_the_fused_node() {
2581        let (mut g, root) = paged_attn_graph();
2582        let opts = PlanOptions::new().with_pinned_device(DeviceLocation::Cuda { gpu_id: 0 });
2583        assert_eq!(
2584            paged_attn_nodes(&g, root),
2585            1,
2586            "PRECONDITION: one fused node"
2587        );
2588        let n = lower_fused_unbound_on_pinned_device(&mut g, &[root], &opts, &|_, _| false);
2589        assert_eq!(n, 1);
2590        assert_eq!(
2591            paged_attn_nodes(&g, root),
2592            0,
2593            "no fused PAGED_ATTN stays reachable"
2594        );
2595    }
2596
2597    /// Sabotage siblings: each condition of the gate, taken away alone, leaves the node fused.
2598    #[test]
2599    fn the_gate_needs_a_cuda_pin_no_bound_kernel_and_a_listed_op() {
2600        // A bound CUDA kernel: keep the fused node (the fast path wins when it exists).
2601        let (mut g, root) = paged_attn_graph();
2602        let cuda = PlanOptions::new().with_pinned_device(DeviceLocation::Cuda { gpu_id: 0 });
2603        assert_eq!(
2604            lower_fused_unbound_on_pinned_device(&mut g, &[root], &cuda, &|_, _| true),
2605            0
2606        );
2607        assert_eq!(paged_attn_nodes(&g, root), 1);
2608        // A CPU pin: the host kernel IS the right place, so nothing lowers.
2609        let (mut g, root) = paged_attn_graph();
2610        let cpu = PlanOptions::new().with_pinned_device(DeviceLocation::Cpu);
2611        assert_eq!(
2612            lower_fused_unbound_on_pinned_device(&mut g, &[root], &cpu, &|_, _| false),
2613            0
2614        );
2615        assert_eq!(paged_attn_nodes(&g, root), 1);
2616        // No pin at all (bare-graph callers): untouched.
2617        let (mut g, root) = paged_attn_graph();
2618        let bare = PlanOptions::new();
2619        assert_eq!(
2620            lower_fused_unbound_on_pinned_device(&mut g, &[root], &bare, &|_, _| false),
2621            0
2622        );
2623        assert_eq!(paged_attn_nodes(&g, root), 1);
2624    }
2625
2626    /// The production predicate is the real registry: CUDA has no PAGED_ATTN kernel today, CPU does.
2627    /// Red the day a CUDA kernel is bound (then the recipe is the slower path and this list must be
2628    /// revisited, which is the point).
2629    #[test]
2630    fn the_registry_has_a_cpu_paged_attn_kernel_and_no_cuda_one() {
2631        let impls = crate::fused::default_kernel_registry()
2632            .impls_for(fuel_graph::registry::FusedOps::PAGED_ATTN);
2633        assert!(
2634            impls
2635                .iter()
2636                .any(|(b, _)| *b == fuel_ir::probe::BackendId::Cpu),
2637            "CONTROL: the registry lookup sees the CPU PAGED_ATTN kernels"
2638        );
2639        assert!(
2640            !impls
2641                .iter()
2642                .any(|(b, _)| *b == fuel_ir::probe::BackendId::Cuda),
2643            "a CUDA PAGED_ATTN kernel is bound: revisit LOWER_WHEN_NO_DEVICE_KERNEL (the fused kernel may now beat the recipe)"
2644        );
2645    }
2646    /// Helper for the row-157 region tests: every kernel op registered on two placements.
2647    fn two_placement_table() -> KernelBindingTable {
2648        let mut table = KernelBindingTable::new();
2649        register_two_backend(&mut table, OpKind::ReluElementwise, 1);
2650        register_two_backend(&mut table, OpKind::SiluElementwise, 1);
2651        register_two_backend(&mut table, OpKind::TanhElementwise, 1);
2652        register_two_backend(&mut table, OpKind::AddElementwise, 2);
2653        table
2654    }
2655
2656    /// `(branch_id, arm-0 exit, reconverge)` of every `Op::Branch` added after `from`.
2657    fn branches_after(g: &Graph, from: usize) -> Vec<(NodeId, NodeId, NodeId)> {
2658        (from..g.len())
2659            .map(NodeId)
2660            .filter_map(|id| match g.node(id).op {
2661                Op::Branch { reconverge_at } => Some((id, g.node(id).inputs[0], reconverge_at)),
2662                _ => None,
2663            })
2664            .collect()
2665    }
2666
2667    /// ROW 157 / GAP-385, RESIDUAL JOIN AND FAN-OUT (born red against the one-node fork, which made
2668    /// 8 one-node forks here and none at `n1` or `res`).
2669    ///
2670    /// A transformer-block-shaped graph, every op on two placements: a residual block whose body fans
2671    /// out (`n1` feeds q, k and v which rejoin through `a` and `b`), then a second residual block.
2672    /// Expect one multi-node region per residual block: block 1 has diverge `x`, a seven-node arm
2673    /// (`n1 q k v a b o`) and reconverge `res`, which reads `x` directly (the residual edge); block 2
2674    /// has diverge `res`, a two-node arm (`n2 m`) and reconverge `res2`.
2675    #[test]
2676    fn transformer_shaped_graph_forks_residual_blocks_as_multi_node_regions() {
2677        let table = two_placement_table();
2678        let mut g = Graph::new();
2679        let x = f32_node(&mut g, Op::Const, vec![]);
2680        let n1 = f32_node(&mut g, Op::Relu, vec![x]); // fan-out: q, k, v
2681        let q = f32_node(&mut g, Op::Silu, vec![n1]);
2682        let k = f32_node(&mut g, Op::Tanh, vec![n1]);
2683        let v = f32_node(&mut g, Op::Relu, vec![n1]);
2684        let a = f32_node(&mut g, Op::Add, vec![q, k]);
2685        let b = f32_node(&mut g, Op::Add, vec![a, v]);
2686        let o = f32_node(&mut g, Op::Silu, vec![b]);
2687        let res = f32_node(&mut g, Op::Add, vec![x, o]); // residual join
2688        let n2 = f32_node(&mut g, Op::Relu, vec![res]);
2689        let m = f32_node(&mut g, Op::Silu, vec![n2]);
2690        let res2 = f32_node(&mut g, Op::Add, vec![res, m]);
2691
2692        let before = g.len();
2693        let optimized = optimize_graph(&mut g, &[res2], &table, &two_backend_opts())
2694            .expect("optimize_graph succeeds on a transformer-shaped two-placement graph");
2695
2696        let mut branches = branches_after(&g, before);
2697        branches.sort_by_key(|(_, exit, _)| exit.0);
2698        assert_eq!(
2699            optimized.branch_count(&g),
2700            2,
2701            "one region per residual block"
2702        );
2703        assert_eq!(
2704            branches.iter().map(|&(_, e, r)| (e, r)).collect::<Vec<_>>(),
2705            vec![(o, res), (m, res2)],
2706            "arm-0 exits and reconverge nodes: (o, res) and (m, res2)"
2707        );
2708        // Arm 1 clones the whole stretch: 7 + 2 clone nodes beside the 2 branch nodes.
2709        assert_eq!(
2710            g.len() - before,
2711            7 + 2 + 2,
2712            "clones of both stretches plus two branch nodes"
2713        );
2714        // Block 1's arm-1 head reads the shared diverge node x (not a clone), and res reads x directly.
2715        assert!(
2716            g.node(res).inputs.contains(&x),
2717            "the residual edge x -> res is untouched"
2718        );
2719    }
2720
2721    /// ROW 158: a region's arm 1 on ANOTHER device must read every value from outside its arm through an
2722    /// `Op::Copy`, and hand its result back to arm 0's device through one. The first run of arm 1 on a GPU
2723    /// (a CPU arm in a Vulkan realize) failed with `cpu kernel wrapper called with non-CPU input` on a clone
2724    /// `Add` reading two Vulkan `Mul` nodes directly: the pathfinder's clones carried a `target_backend`
2725    /// but no placement, so the residency pass placed them on the pinned device and saw no crossing.
2726    ///
2727    /// The stretch `a, t` has TWO external inputs (the diverge `d` and the earlier `e`) and its exit feeds
2728    /// a reconverge on the host. The alternative runs on `Cuda { gpu_id: 0 }`. Built through
2729    /// `try_record_branch` with explicit devices because the synthetic two-backend fixture of
2730    /// `optimize_graph` puts its "Cuda" placement at the CPU location and so cannot show a crossing.
2731    #[test]
2732    fn a_cross_device_arm_one_gets_inbound_copies_for_every_external_input_and_an_exit_copy() {
2733        use crate::region_pathfinder::try_record_branch;
2734        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
2735        let mut g = Graph::new();
2736        let x = f32_node(&mut g, Op::Const, vec![]);
2737        let e = f32_node(&mut g, Op::Relu, vec![x]);
2738        let d = f32_node(&mut g, Op::Silu, vec![e]); // the diverge
2739        let a = f32_node(&mut g, Op::Add, vec![d, e]); // entry: reads d AND e, both outside the stretch
2740        let t = f32_node(&mut g, Op::Tanh, vec![a]);
2741        let res = f32_node(&mut g, Op::Add, vec![d, t]); // reconverge: reads the exit t (and d)
2742        for n in [x, e, d, a, t, res] {
2743            g.set_placement(n, DeviceLocation::Cpu);
2744            if n != x {
2745                g.set_target_backend(n, BackendId::Cpu);
2746            }
2747        }
2748        let branch = try_record_branch(
2749            &mut g,
2750            d,
2751            res,
2752            &[a, t],
2753            t,
2754            BackendId::Cuda,
2755            cuda0,
2756            DeviceLocation::Cpu,
2757        )
2758        .expect("well-formed branch")
2759        .expect("two arms");
2760        insert_residency_copies(
2761            &mut g,
2762            &[res],
2763            &ExecutionPlan::empty(),
2764            DeviceLocation::Cpu,
2765            None,
2766        );
2767
2768        let arm1_exit = g.node(branch).inputs[1];
2769        // The arm's result comes back to the host through a copy, so both exits live on one device.
2770        assert!(
2771            matches!(g.node(arm1_exit).op, Op::Copy { target } if target == DeviceLocation::Cpu),
2772            "arm 1's exit must be a copy back to the host; got {:?}",
2773            g.node(arm1_exit).op
2774        );
2775        let clone_t = g.node(arm1_exit).inputs[0];
2776        let clone_a = g.node(clone_t).inputs[0];
2777        assert_eq!(g.node(clone_a).op, Op::Add, "the clone of the entry node");
2778        // Both external inputs of the clone entry node go through a copy onto the alternative device.
2779        assert_eq!(g.node(clone_a).inputs.len(), 2);
2780        for &input in &g.node(clone_a).inputs {
2781            assert!(
2782                matches!(g.node(input).op, Op::Copy { target } if target == cuda0),
2783                "clone entry node reads {:?} ({:?}) from outside its arm with no copy onto {cuda0:?}",
2784                input,
2785                g.node(input).op,
2786            );
2787        }
2788        // The copies read the original host values (the shared diverge and the earlier node).
2789        let sources: Vec<NodeId> = g
2790            .node(clone_a)
2791            .inputs
2792            .iter()
2793            .map(|&c| g.node(c).inputs[0])
2794            .collect();
2795        assert_eq!(sources, vec![d, e]);
2796        // Arm 0 is untouched: still host to host, no copies.
2797        assert_eq!(g.node(a).inputs, vec![d, e]);
2798    }
2799
2800    /// ROW 157 / GAP-385, PURE FAN-OUT (no residual edge): `x -> n1 -> {q, k} -> a -> t`. The region is
2801    /// the fan-out and everything up to its join: diverge `x`, a four-node arm (`n1 q k a`), reconverge
2802    /// `t`. Born red: the one-node fork never forked `n1` (two consumers) and made one-node forks of
2803    /// `q`, `k` (sole consumer `a`) and `a`.
2804    #[test]
2805    fn fan_out_that_rejoins_is_one_multi_node_region() {
2806        let table = two_placement_table();
2807        let mut g = Graph::new();
2808        let x = f32_node(&mut g, Op::Const, vec![]);
2809        let n1 = f32_node(&mut g, Op::Relu, vec![x]);
2810        let q = f32_node(&mut g, Op::Silu, vec![n1]);
2811        let k = f32_node(&mut g, Op::Tanh, vec![n1]);
2812        let a = f32_node(&mut g, Op::Add, vec![q, k]);
2813        let t = f32_node(&mut g, Op::Relu, vec![a]);
2814
2815        let before = g.len();
2816        optimize_graph(&mut g, &[t], &table, &two_backend_opts()).expect("optimize_graph");
2817        let branches = branches_after(&g, before);
2818        assert_eq!(
2819            branches.iter().map(|&(_, e, r)| (e, r)).collect::<Vec<_>>(),
2820            vec![(a, t)],
2821            "one region: arm-0 exit a, reconverge t"
2822        );
2823        assert_eq!(
2824            g.len() - before,
2825            4 + 1,
2826            "four cloned nodes (n1 q k a) plus the branch node"
2827        );
2828    }
2829    /// Cross-device, production-shaped options: the realize device is a GPU (`Cuda { gpu_id: 0 }`), CPU is
2830    /// the always-feasible fallback device, and a transfer estimator is present, so the placement DP
2831    /// runs and prunes every node's alternative set to its committed device (the single-device-set
2832    /// invariant). This is the shape `build_optimized_graph` builds on a Vulkan/CUDA realize; the
2833    /// co-located `two_backend_opts` above never opens a DP row and so never reaches this pruning.
2834    struct FlatTransfer;
2835    impl crate::ranker::cost::TransferEstimator for FlatTransfer {
2836        fn estimate_transfer_ns(
2837            &self,
2838            src: DeviceLocation,
2839            dst: DeviceLocation,
2840            _bytes: u64,
2841        ) -> u64 {
2842            if src == dst { 0 } else { 1_000 }
2843        }
2844    }
2845    /// A kernel cost of 10_000 flops (10 us at the caps' 1 flop/ns) on every node: a transfer of 1_000 ns
2846    /// is then a small fraction of a node, as on a real model, rather than infinitely worse than a
2847    /// zero-cost kernel (which `unknown_cost` would give).
2848    fn ten_us_cost(
2849        _: &[Shape],
2850        _: &[DType],
2851        _: &crate::kernel::OpParams,
2852        _: &fuel_ir::backend::BackendCapabilities,
2853    ) -> crate::fused::CostEstimate {
2854        crate::fused::CostEstimate {
2855            flops: 10_000,
2856            bytes_moved: 0,
2857            kernel_overhead_ns: 0,
2858        }
2859    }
2860    /// The same node on the GPU prior (`default_backend_rates`: 30 flops/ns) at 300_000 flops, i.e. also
2861    /// 10 us: the CPU arm is then within the competitive factor. Without this the CPU arm would be ~30x
2862    /// slower and correctly NOT competitive, which is itself what a real GPU model looks like.
2863    fn ten_us_cost_gpu(
2864        _: &[Shape],
2865        _: &[DType],
2866        _: &crate::kernel::OpParams,
2867        _: &fuel_ir::backend::BackendCapabilities,
2868    ) -> crate::fused::CostEstimate {
2869        crate::fused::CostEstimate {
2870            flops: 300_000,
2871            bytes_moved: 0,
2872            kernel_overhead_ns: 0,
2873        }
2874    }
2875    fn costed_two_placement_table() -> KernelBindingTable {
2876        let mut table = KernelBindingTable::new();
2877        for (op, n_in) in [
2878            (OpKind::ReluElementwise, 1),
2879            (OpKind::SiluElementwise, 1),
2880            (OpKind::TanhElementwise, 1),
2881            (OpKind::AddElementwise, 2),
2882        ] {
2883            let mut dtypes = vec![DType::F32; n_in];
2884            dtypes.push(DType::F32);
2885            for (backend, kernel, cost) in [
2886                (
2887                    BackendId::Cpu,
2888                    noop_kernel as crate::kernel::KernelRef,
2889                    ten_us_cost as crate::kernel::CostFn,
2890                ),
2891                (
2892                    BackendId::Cuda,
2893                    noop_kernel_b as crate::kernel::KernelRef,
2894                    ten_us_cost_gpu as crate::kernel::CostFn,
2895                ),
2896            ] {
2897                table.register_full(
2898                    op,
2899                    &dtypes,
2900                    backend,
2901                    kernel,
2902                    KernelCaps::empty(),
2903                    PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2904                    cost,
2905                );
2906            }
2907        }
2908        table
2909    }
2910    fn gpu_placements(dev: DeviceLocation) -> Vec<BackendId> {
2911        match dev {
2912            DeviceLocation::Cuda { .. } => vec![BackendId::Cuda],
2913            DeviceLocation::Cpu => vec![BackendId::Cpu],
2914            _ => vec![],
2915        }
2916    }
2917    fn cpu_fallback(dev: DeviceLocation) -> Vec<(BackendId, DeviceLocation)> {
2918        if dev == DeviceLocation::Cpu {
2919            vec![]
2920        } else {
2921            vec![(BackendId::Cpu, DeviceLocation::Cpu)]
2922        }
2923    }
2924
2925    /// ROW 157 / GAP-385, PRODUCTION ENTRY (born red). Live run, Vulkan tiny-Llama, ref `db0c1f7a2`: every
2926    /// optimize reported 0 live `Op::Branch`; the pathfinder saw 0 nodes with two placements because
2927    /// `compile_plan` pruned each set to the DP-committed device. Here the same options shape
2928    /// (GPU realize device + CPU fallback + transfer estimator) over a residual block must still yield
2929    /// one multi-node region.
2930    #[test]
2931    fn cross_device_residual_block_forks_through_the_production_options_shape() {
2932        let table = costed_two_placement_table();
2933        let mut g = Graph::new();
2934        let x = f32_node(&mut g, Op::Const, vec![]);
2935        let n1 = f32_node(&mut g, Op::Relu, vec![x]);
2936        let q = f32_node(&mut g, Op::Silu, vec![n1]);
2937        let o = f32_node(&mut g, Op::Tanh, vec![q]);
2938        let res = f32_node(&mut g, Op::Add, vec![x, o]);
2939
2940        let est = FlatTransfer;
2941        let gpu = DeviceLocation::Cuda { gpu_id: 0 };
2942        let caps = fuel_ir::backend::BackendCapabilities {
2943            backend_id: BackendId::Cuda,
2944            device_location: gpu,
2945            op_dtype_support: std::collections::HashSet::new(),
2946            required_alignment: 64,
2947            access_granularity_bits: 8,
2948            transfer_paths: vec![(gpu, fuel_ir::backend::TransferPath::SameDevice)],
2949            storage_substrate: fuel_ir::backend::SubstrateClass::HostBytes,
2950            compute_throughput_flops_per_ns: 1.0,
2951            mem_bandwidth_bytes_per_ns: 4.0,
2952        };
2953        let caps_for = |_: BackendId| Some(&caps);
2954        let residency = |_: NodeId| Some(gpu);
2955        // Cost population stays ON (the default): `relaxed` merged enumeration, and with it the
2956        // placement DP, only runs when pricing is active, exactly as `build_optimized_graph` sets it.
2957        let opts = PlanOptions::new()
2958            .with_pinned_device(gpu)
2959            .with_placements_for_device(&gpu_placements)
2960            .with_fallback_placements_for(&cpu_fallback)
2961            .with_capabilities_for(&caps_for)
2962            .with_transfer_estimator(&est)
2963            .with_input_residency(&residency);
2964        let before = g.len();
2965        let optimized = optimize_graph(&mut g, &[res], &table, &opts).expect("optimize_graph");
2966        assert!(
2967            optimized.branch_count(&g) >= 1,
2968            "a GPU realize with a CPU fallback must expose a cross-device region; branches={:?}",
2969            branches_after(&g, before)
2970        );
2971    }
2972
2973    /// SIBLING of the test above: the same cross-device shape, but the GPU kernel is 30x cheaper than the
2974    /// CPU one (both at 10_000 flops, GPU prior 30 flops/ns). The CPU arm is not within the competitive
2975    /// factor, so NO region is recorded. This is what a real GPU model looks like; the test keeps the
2976    /// first one from passing by recording a region unconditionally.
2977    #[test]
2978    fn cross_device_cpu_arm_far_slower_than_the_gpu_is_not_competitive() {
2979        let mut table = KernelBindingTable::new();
2980        for (op, n_in) in [
2981            (OpKind::ReluElementwise, 1),
2982            (OpKind::SiluElementwise, 1),
2983            (OpKind::TanhElementwise, 1),
2984            (OpKind::AddElementwise, 2),
2985        ] {
2986            let mut dtypes = vec![DType::F32; n_in];
2987            dtypes.push(DType::F32);
2988            for (backend, kernel) in [
2989                (BackendId::Cpu, noop_kernel as crate::kernel::KernelRef),
2990                (BackendId::Cuda, noop_kernel_b as crate::kernel::KernelRef),
2991            ] {
2992                table.register_full(
2993                    op,
2994                    &dtypes,
2995                    backend,
2996                    kernel,
2997                    KernelCaps::empty(),
2998                    PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
2999                    ten_us_cost,
3000                );
3001            }
3002        }
3003        let mut g = Graph::new();
3004        let x = f32_node(&mut g, Op::Const, vec![]);
3005        let n1 = f32_node(&mut g, Op::Relu, vec![x]);
3006        let q = f32_node(&mut g, Op::Silu, vec![n1]);
3007        let o = f32_node(&mut g, Op::Tanh, vec![q]);
3008        let res = f32_node(&mut g, Op::Add, vec![x, o]);
3009        let est = FlatTransfer;
3010        let gpu = DeviceLocation::Cuda { gpu_id: 0 };
3011        let caps = fuel_ir::backend::BackendCapabilities {
3012            backend_id: BackendId::Cuda,
3013            device_location: gpu,
3014            op_dtype_support: std::collections::HashSet::new(),
3015            required_alignment: 64,
3016            access_granularity_bits: 8,
3017            transfer_paths: vec![(gpu, fuel_ir::backend::TransferPath::SameDevice)],
3018            storage_substrate: fuel_ir::backend::SubstrateClass::HostBytes,
3019            compute_throughput_flops_per_ns: 1.0,
3020            mem_bandwidth_bytes_per_ns: 4.0,
3021        };
3022        let caps_for = |_: BackendId| Some(&caps);
3023        let residency = |_: NodeId| Some(gpu);
3024        let opts = PlanOptions::new()
3025            .with_pinned_device(gpu)
3026            .with_placements_for_device(&gpu_placements)
3027            .with_fallback_placements_for(&cpu_fallback)
3028            .with_capabilities_for(&caps_for)
3029            .with_transfer_estimator(&est)
3030            .with_input_residency(&residency);
3031        let optimized = optimize_graph(&mut g, &[res], &table, &opts).expect("optimize_graph");
3032        assert_eq!(
3033            optimized.branch_count(&g),
3034            0,
3035            "a CPU arm ~30x slower than the GPU is not competitive within the factor of 2"
3036        );
3037    }
3038
3039    /// SABOTAGE SIBLING (row 157): a node read from outside the stretch must not sit inside a region.
3040    /// `n1` is read by `m` and by a second realize root `side`, so no region may contain it; `m` alone
3041    /// (diverge `n1`, reconverge `t`) is still a valid one-node region.
3042    #[test]
3043    fn a_node_read_from_outside_the_stretch_is_not_inside_a_region() {
3044        let table = two_placement_table();
3045        let mut g = Graph::new();
3046        let x = f32_node(&mut g, Op::Const, vec![]);
3047        let n1 = f32_node(&mut g, Op::Relu, vec![x]);
3048        let m = f32_node(&mut g, Op::Silu, vec![n1]);
3049        let t = f32_node(&mut g, Op::Relu, vec![m]);
3050        let side = f32_node(&mut g, Op::Tanh, vec![n1]);
3051        let before = g.len();
3052        optimize_graph(&mut g, &[t, side], &table, &two_backend_opts()).expect("optimize_graph");
3053        let exits: Vec<NodeId> = branches_after(&g, before).iter().map(|b| b.1).collect();
3054        assert!(
3055            !exits.contains(&n1),
3056            "n1 is read by a second root and cannot be an arm exit"
3057        );
3058    }
3059
3060    /// SABOTAGE SIBLING (row 157): a stretch is only as long as the nodes that have the alternative.
3061    /// `s` is CPU-only, so no region may span it; the two Relu nodes each fork alone.
3062    #[test]
3063    fn a_node_without_the_alternative_kernel_splits_the_region() {
3064        let mut table = KernelBindingTable::new();
3065        register_two_backend(&mut table, OpKind::ReluElementwise, 1);
3066        register_elementwise(&mut table, OpKind::SiluElementwise, 1); // CPU only
3067        let mut g = Graph::new();
3068        let x = f32_node(&mut g, Op::Const, vec![]);
3069        let r1 = f32_node(&mut g, Op::Relu, vec![x]);
3070        let s = f32_node(&mut g, Op::Silu, vec![r1]);
3071        let r2 = f32_node(&mut g, Op::Relu, vec![s]);
3072        let t = f32_node(&mut g, Op::Relu, vec![r2]);
3073        let before = g.len();
3074        optimize_graph(&mut g, &[t], &table, &two_backend_opts()).expect("optimize_graph");
3075        let mut exits: Vec<NodeId> = branches_after(&g, before).iter().map(|b| b.1).collect();
3076        exits.sort_by_key(|n| n.0);
3077        assert!(
3078            !exits.contains(&s),
3079            "the CPU-only node is never an arm exit"
3080        );
3081        // r2 and t form one two-node stretch? t is the root, so only r1 and r2 can be interior.
3082        assert_eq!(
3083            exits,
3084            vec![r1, r2],
3085            "r1 forks alone, r2 forks alone, nothing spans s"
3086        );
3087    }
3088
3089    /// SABOTAGE SIBLING (row 157): one placement per node means no region at all.
3090    #[test]
3091    fn a_single_placement_graph_gets_no_regions() {
3092        let mut table = KernelBindingTable::new();
3093        register_elementwise(&mut table, OpKind::ReluElementwise, 1);
3094        register_elementwise(&mut table, OpKind::SiluElementwise, 1);
3095        let mut g = Graph::new();
3096        let x = f32_node(&mut g, Op::Const, vec![]);
3097        let a = f32_node(&mut g, Op::Relu, vec![x]);
3098        let b = f32_node(&mut g, Op::Silu, vec![a]);
3099        let c = f32_node(&mut g, Op::Relu, vec![b]);
3100        let before = g.len();
3101        let optimized = optimize_graph(&mut g, &[c], &table, &cpu_opts()).expect("optimize_graph");
3102        assert_eq!(optimized.branch_count(&g), 0);
3103        assert_eq!(g.len(), before, "no clones are left behind");
3104    }
3105
3106    // ===== Load-aware arm pick through the PRODUCTION realize entry
3107    //        (row 158 slice 2: estimated-completion, not queue-depth) =====
3108
3109    /// Records the backend of every candidate the wrapped selector picks, so
3110    /// a test can read WHICH arm the production picking entry chose.
3111    #[derive(Debug)]
3112    struct RecordingSelector {
3113        inner: crate::ranker::ChainedSelector,
3114        picked: std::sync::Mutex<Vec<BackendId>>,
3115    }
3116
3117    impl crate::ranker::RuntimeSelector for RecordingSelector {
3118        fn select<'a>(
3119            &self,
3120            set: &'a crate::ranker::AlternativeSet,
3121        ) -> Option<&'a crate::ranker::Candidate> {
3122            let picked = self.inner.select(set);
3123            if let Some(c) = picked {
3124                self.picked.lock().unwrap().push(c.backend);
3125            }
3126            picked
3127        }
3128    }
3129
3130    /// Judge answering per BACKEND only. The pick enumerates candidates from
3131    /// the process-wide binding table (real `portable-cpu` kernel with a
3132    /// revision hash; a synthetic CUDA stand-in), so a cell-keyed judge would
3133    /// couple the test to those tags.
3134    struct BackendJudge {
3135        cuda_ns: u64,
3136        cpu_ns: u64,
3137    }
3138
3139    impl crate::ranker::JudgeOracle for BackendJudge {
3140        fn measured_latency_ns(
3141            &self,
3142            _op: OpKind,
3143            _dtype: DType,
3144            _size_class: fuel_ir::dispatch::SizeClass,
3145            backend: BackendId,
3146            _kernel_source: &str,
3147            _kernel_revision_hash: u64,
3148        ) -> Option<u64> {
3149            match backend {
3150                BackendId::Cuda => Some(self.cuda_ns),
3151                BackendId::Cpu => Some(self.cpu_ns),
3152                _ => None,
3153            }
3154        }
3155    }
3156
3157    /// Realize the single-fork graph through
3158    /// `PipelinedExecutor::realize_with_optimized_picking_env` (the entry the
3159    /// bridge calls) with a `ChainedSelector` over `lookup` and a Judge that
3160    /// measures the fork op at `cuda_ns` on CUDA and `cpu_ns` on CPU. Returns
3161    /// the backends the streaming pick chose for the (one) branch.
3162    ///
3163    /// Also returns the realize result (`"Ok"` or `Err(..)` as text), so a
3164    /// run with no pick names its cause instead of reading as "no pick".
3165    ///
3166    /// Holds `TOPOLOGY_TEST_GATE` for writing from before `optimize_graph`
3167    /// until the realize returns: the executor returns the typed
3168    /// `Error::TopologyChanged` when another test in this binary bumps the
3169    /// process-wide topology generation in between, and then the streaming
3170    /// walk never reaches the branch (ROADMAP row 165). The gate stops a
3171    /// sibling's bump from landing in that window; there is no retry.
3172    fn picked_backends_through_realize(
3173        lookup: crate::ranker::BackendRuntimeLookup,
3174        cuda_ns: u64,
3175        cpu_ns: u64,
3176    ) -> (Vec<BackendId>, String) {
3177        use crate::PipelinedExecutor;
3178        use crate::pipelined::StorageCache;
3179        use crate::ranker::ChainedSelector;
3180        use fuel_ir::SymEnv;
3181
3182        // Build the lazily initialised process-wide tables BEFORE taking the
3183        // gate: their initialisation bumps the generation, and a bump under
3184        // our own write guard would wait on ourselves.
3185        drop(crate::dispatch::global_bindings());
3186        let _crate_gate = crate::dispatch::TOPOLOGY_TEST_GATE
3187            .write()
3188            .unwrap_or_else(|poisoned| poisoned.into_inner());
3189
3190        let mut table = KernelBindingTable::new();
3191        let (mut g, _prod, _fork, _tail, root) = build_single_fork_graph(&mut table);
3192        let optimized = optimize_graph(&mut g, &[root], &table, &two_backend_opts())
3193            .expect("optimize_graph succeeds");
3194        assert_eq!(optimized.branch_count(&g), 1, "exactly one branch");
3195
3196        let selector = Arc::new(RecordingSelector {
3197            inner: ChainedSelector::with_default_estimator(
3198                Some(Arc::new(BackendJudge { cuda_ns, cpu_ns })),
3199                Some(lookup.clone()),
3200            ),
3201            picked: std::sync::Mutex::new(Vec::new()),
3202        });
3203
3204        let graph = Arc::new(RwLock::new(g));
3205        let mut cache = StorageCache::new();
3206        cache.insert(
3207            NodeId(0),
3208            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
3209                1.0_f32, 2.0, 3.0, 4.0,
3210            ]))),
3211        );
3212        // The CUDA arm has no device behind it in a CPU test, so a realize
3213        // that picked CUDA ends in a device error at the reconverge node; a
3214        // realize that picked CPU runs end to end. The result is returned, not
3215        // ignored, so the caller pins which.
3216        let result = PipelinedExecutor::realize_with_optimized_picking_env(
3217            graph,
3218            root,
3219            cache,
3220            &optimized,
3221            Some(selector.clone() as Arc<dyn crate::ranker::RuntimeSelector>),
3222            Some(lookup),
3223            SymEnv::default(),
3224        );
3225        let outcome = match result {
3226            Ok(_) => "Ok".to_string(),
3227            Err(e) => format!("Err({e:?})"),
3228        };
3229        let picks = selector.picked.lock().unwrap().clone();
3230        (picks, outcome)
3231    }
3232
3233    /// Row 158 slice 2. CUDA measures 100 ns on the fork op, CPU 100 us.
3234    /// The device load must be read as estimated BACKLOG TIME, not as a
3235    /// queue-depth bucket:
3236    ///  - idle CUDA                      -> CUDA arm;
3237    ///  - CUDA with ONE op queued (the count bucket says "saturated") but
3238    ///    only 1 us of estimated backlog -> STILL the CUDA arm (1.1 us beats
3239    ///    CPU's 100 us); the count tier wrongly sends this to CPU;
3240    ///  - CUDA with a 1 hour backlog     -> the CPU arm.
3241    ///
3242    /// SHOWS: the streaming pick, reached through the production picking
3243    /// realize entry, ranks arms by backlog + measured latency.
3244    /// DOES NOT SHOW: that the executor's submit sites feed the backlog
3245    /// (the lookup here injects it), nor that kernels ran on either arm.
3246    #[test]
3247    fn load_aware_pick_ranks_by_estimated_completion_through_realize() {
3248        use crate::ranker::mock_backlog_lookup;
3249        const HOUR_NS: u64 = 3_600_000_000_000;
3250
3251        let (idle, idle_r) = picked_backends_through_realize(
3252            mock_backlog_lookup(vec![(BackendId::Cuda, 0, 0)]),
3253            100,
3254            100_000,
3255        );
3256        assert_eq!(
3257            idle,
3258            vec![BackendId::Cuda],
3259            "idle GPU -> GPU arm; realize={idle_r}"
3260        );
3261
3262        let (one_op, one_op_r) = picked_backends_through_realize(
3263            mock_backlog_lookup(vec![(BackendId::Cuda, 1, 1_000)]),
3264            100,
3265            100_000,
3266        );
3267        assert_eq!(
3268            one_op,
3269            vec![BackendId::Cuda],
3270            "1 op / 1 us backlog: GPU still finishes first (1.1 us vs 100 us); realize={one_op_r}",
3271        );
3272
3273        let (hour, hour_r) = picked_backends_through_realize(
3274            mock_backlog_lookup(vec![(BackendId::Cuda, 1, HOUR_NS)]),
3275            100,
3276            100_000,
3277        );
3278        assert_eq!(
3279            hour,
3280            vec![BackendId::Cpu],
3281            "1 h GPU backlog -> CPU arm; realize={hour_r}"
3282        );
3283        assert_eq!(hour_r, "Ok", "the CPU arm realizes end to end");
3284    }
3285}