Skip to main content

fuel_dispatch/
pipelined.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Pipelined compile + execute. Phase 7.5 B4.
3//!
4//! [`PipelinedExecutor::realize`] runs compilation and execution on
5//! separate threads connected by a channel: a compiler thread walks
6//! the graph in topological order and emits work items; the
7//! executor (this thread) consumes them, allocates output Storage,
8//! calls the kernel, and stores the result in an internal cache.
9//! Both threads run concurrently so execution can begin while
10//! compilation is still resolving later nodes.
11//!
12//! Today's "compile" step is a single binding-table lookup —
13//! roughly nanoseconds per node. The threading delivers no
14//! measurable speedup in this regime. The pipelining infrastructure
15//! exists *now* — built on the [`compile_node`] / [`crate::compiled::execute_compiled`]
16//! interface from B5 — so future work that grows the compile step
17//! (residency-aware planning, transfer-cost minimization, kernel
18//! auto-tuning) plugs in without revisiting call sites.
19//!
20//! ## Storage during the migration
21//!
22//! `fuel_graph::Graph::storage_map` uses the legacy
23//! `fuel_backend_contract::Storage` (the `Box<dyn DynBackendStorage>`
24//! newtype). The pipelined executor uses the new
25//! `fuel_memory::Storage` (BackendStorage enum + dtype). During
26//! the migration the two coexist — neither is converted on the fly.
27//! The pipelined executor takes pre-realized inputs as a
28//! `HashMap<NodeId, Arc<RwLock<fuel_memory::Storage>>>` rather
29//! than reading from the graph's storage_map. Phase D unifies the
30//! two paths once kernel migration completes.
31//!
32//! ## Op coverage
33//!
34//! B4 supports `Op::Const` (input-cache adoption — no kernel call)
35//! and `Op::Add` on f32 (mapped to `OpKind::AddElementwise`).
36//! Phase C adds the rest as more (op, dtype) bindings register.
37
38use std::collections::{HashMap, HashSet};
39use std::sync::mpsc::{Sender, channel};
40use std::sync::{Arc, RwLock};
41use std::thread;
42
43use fuel_graph::opt::{execution_plan, insert_safety_copies};
44use fuel_graph::registry::FusedOpParams;
45use fuel_graph::{Graph, Node, NodeId, Op, PickedRoute};
46use fuel_ir::dispatch::OpKind;
47use fuel_ir::probe::BackendId;
48use fuel_ir::{DType, DeviceLocation, Error, Layout, Result, SymEnv};
49
50use crate::compiled::{
51    CompiledNode, CompletionHandle, compile_node, execute_compiled_with_wait_hint,
52};
53use crate::dispatch::global_bindings;
54use crate::kernel::{KernelBindingTable, KernelDTypes, MatmulM, OpParams};
55use crate::optimize::OptimizedGraph;
56use crate::ranker::{BackendRuntimeLookup, RuntimeSelector, resolve_branch};
57// `pick_route` is called only by the streamed-vs-one-shot equivalence test
58// below; the executor itself resolves branch-by-branch via `resolve_branch`.
59#[cfg(test)]
60use crate::ranker::pick_route;
61use fuel_memory::Storage;
62
63/// How the executor derives its dispatch order + topology-generation
64/// stamp for the `TopologyChanged` chunk-boundary check.
65///
66/// PR-A3b-1 of the "plan IS the graph" rebuild: the realize bridge can
67/// now drive the executor from `optimize_graph`'s in-place form via
68/// [`OptimizedGraph::dispatch_order`] (`extract_runs`/`lower_run`)
69/// instead of the legacy `ExecutionPlan`-supplied order. Both arms
70/// compute the *same* `NodeId` sequence on a branchless graph (the
71/// A3a equivalence gate proved `dispatch_order == compile_plan(...).order`);
72/// the only difference is the source of truth.
73///
74/// - [`OrderSource::Default`] — recompute via `execution_plan` inside
75///   the executor (the pre-A3b-1 behavior; the legacy `ExecutionPlan`
76///   path and the plain `realize`/`realize_many` entries use this).
77/// - [`OrderSource::Optimized`] — derive from the `OptimizedGraph`'s
78///   run lowering, computed AFTER `insert_safety_copies` so the order
79///   covers any safety-copy nodes the executor just inserted. Carries
80///   the optimize-time `generation` so the chunk-boundary
81///   `TopologyChanged` check still fires (the new path dispatches with
82///   `plan: None`, so the generation must come from here instead).
83///
84///   PR-C1: it also carries an optional **route** ([`PickedRoute`]) — the
85///   runtime route picker (Picker 2) chose one arm per `Op::Branch`. When
86///   `Some`, the order is the route-aware lowering
87///   ([`fuel_graph::lower_picked_route`]); when `None` (or empty) it is
88///   the arm-0 lowering (`lower_runs_arm0`), byte-identical to Phase B.
89enum OrderSource<'a> {
90    Default,
91    Optimized {
92        optimized: &'a OptimizedGraph,
93        /// The route the picker resolved (one arm per branch). `None` ⇒
94        /// arm-0 everywhere (no picker / no pressure ⇒ Phase B behavior).
95        route: Option<&'a PickedRoute>,
96    },
97    /// Step E Phase C, PR C1 — the **streaming run-walk**. Instead of a
98    /// route resolved up front, the compiler thread resolves each branch
99    /// **lazily, as the topo walk reaches its arm-entry**, via
100    /// [`resolve_branch`] over the threaded [`StreamingPick`]. The order is
101    /// never pre-flattened: the compiler thread interleaves arm resolution,
102    /// node compilation, and dispatch (so C2 can later read live device
103    /// load at the moment a branch resolves). Still VRAM-only selection in
104    /// C1, so the streamed order equals the one-shot
105    /// [`OrderSource::Optimized`]`{route: Some(pick_route(..))}` order
106    /// byte-for-byte.
107    Streaming {
108        optimized: &'a OptimizedGraph,
109        pick: &'a StreamingPick,
110    },
111    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
112    /// §5): memoizes the `Optimized { route: None }` arm's dispatch order
113    /// WHOLESALE in `order_cache`, computed once and reused by the caller
114    /// across repeated calls over an unchanged graph/roots — the plan-once
115    /// persistent-decode shape, where only leaf values are rebound between
116    /// tokens, never the graph's structure. Safe because that recompute is
117    /// a pure function of (graph structure, roots, generation) when none of
118    /// those change — proven, not assumed, by
119    /// `dispatch_order_is_stable_across_repeated_calls_with_no_mutation`
120    /// (`fuel-dispatch/src/optimize.rs`). A cache miss falls back to the
121    /// exact `Optimized { route: None }` computation and populates the
122    /// cache for next time; `generation_for` still reports `optimized`'s
123    /// generation, so the existing `TopologyChanged` chunk-boundary check
124    /// fires exactly as it would for `Optimized` — if the topology changes
125    /// underneath a cached session, realize fails loudly (the existing
126    /// contract), it does not silently serve a stale order.
127    Cached {
128        optimized: &'a OptimizedGraph,
129        order_cache: &'a std::sync::OnceLock<Vec<NodeId>>,
130    },
131}
132
133/// Owned arm-resolution config threaded into the compiler thread for the
134/// [`OrderSource::Streaming`] walk (Step E Phase C, PR C1). The selector +
135/// lookup are owned `Arc`s (not borrows) so they can be `move`d into the
136/// spawned compiler thread; both are `Send + Sync`. The per-arm candidate
137/// bindings are read from [`global_bindings`] inside the thread (as the
138/// eager `pick_route_for` does), so they are not carried here.
139///
140/// The streaming walk consults the SAME selector chain as the one-shot
141/// picker (the production `ChainedSelector`). As of C2 that chain is
142/// load-aware: its key is `(pressure_tier, load_tier, latency_ns,
143/// original_index)`, and the `load_tier` leg reads B1's in-flight counter
144/// through the selector's own `BackendRuntimeLookup` handle (the
145/// `BackendStreams` seam). Under no load / no pressure every leg is the
146/// no-signal default, so the lazy resolution yields the same arm as the
147/// eager `pick_route` on every input — byte-identical to pre-C2.
148#[derive(Clone)]
149pub(crate) struct StreamingPick {
150    /// The runtime selector the streaming walk consults at each branch —
151    /// the production `ChainedSelector` (VRAM-pressure guard + load tier +
152    /// Judge rank). It holds its own `BackendRuntimeLookup`, so it reads
153    /// both VRAM fit and live device load off that lookup's handles.
154    pub selector: Arc<dyn RuntimeSelector>,
155}
156
157/// Map from NodeId to a realized Storage Arc. Used both as the
158/// input cache (passed in by the caller for pre-realized leaves)
159/// and as the output cache (built up during execution).
160pub type StorageCache = HashMap<NodeId, Arc<RwLock<Storage>>>;
161
162/// The per-realize device handles live in [`crate::device_registry`] (ROADMAP row 137, seam S3 step 3b-3);
163/// re-exported here so the path every caller already uses keeps working.
164pub use crate::device_registry::DeviceRegistry;
165
166/// A registry holding the CUDA device of every CUDA storage among a captured decode's inputs. The capture API
167/// takes tensors, not devices, so the devices are read off the caller's own inputs once, here, and handed to the
168/// executor like any other caller's registry; the executor no longer scans a cache for them.
169#[cfg(feature = "cuda")]
170fn cuda_registry_of_inputs(inputs: &StorageCache) -> DeviceRegistry {
171    let mut registry = DeviceRegistry::new();
172    for arc in inputs.values() {
173        if let Ok(guard) = arc.read()
174            && let fuel_memory::BackendStorage::Cuda(c) = &guard.inner
175        {
176            registry = registry.with_cuda(c.device().clone());
177        }
178    }
179    registry
180}
181
182/// Persistent per-node output buffers for CUDA-graph capture (the
183/// "CapturedRun executor" build-out). Maps each compute node's [`NodeId`]
184/// to a FIXED-ADDRESS output [`Storage`] Arc that survives across realizes,
185/// so a captured graph's baked kernel-argument addresses stay valid on
186/// replay.
187///
188/// Two modes, both driven by the executor's Kernel arm:
189/// - **`Record`** (warm run): the executor allocates each kernel output as
190///   usual AND records the Arc here. Produces the fixed buffers.
191/// - **`Reuse`** (capture / replay run): the executor REUSES the recorded
192///   Arc for each node — no allocation (mandatory inside a capture scope) —
193///   and the kernel's write-into path writes into it in place.
194///
195/// `None` (the param default at every existing realize call site) preserves
196/// byte-identical behavior: fresh alloc every realize, nothing recorded.
197pub struct PersistentOutputs {
198    map: HashMap<NodeId, Arc<RwLock<Storage>>>,
199    mode: PersistentMode,
200}
201
202#[derive(Clone, Copy, PartialEq, Eq)]
203enum PersistentMode {
204    /// Warm run: allocate + record each kernel output.
205    Record,
206    /// Capture / replay run: reuse the recorded buffer (no alloc).
207    Reuse,
208}
209
210impl PersistentOutputs {
211    /// A fresh recording map for the warm run.
212    pub fn recording() -> Self {
213        Self {
214            map: HashMap::new(),
215            mode: PersistentMode::Record,
216        }
217    }
218
219    /// A reuse map for the capture / replay run, seeded with the buffers
220    /// a prior warm run recorded.
221    pub fn reuse(map: HashMap<NodeId, Arc<RwLock<Storage>>>) -> Self {
222        Self {
223            map,
224            mode: PersistentMode::Reuse,
225        }
226    }
227
228    /// Consume, yielding the recorded NodeId→buffer map (to seed a
229    /// [`reuse`](Self::reuse) map for the capture run).
230    pub fn into_map(self) -> HashMap<NodeId, Arc<RwLock<Storage>>> {
231        self.map
232    }
233}
234
235/// Whether a kernel op's CUDA dispatch wrapper writes its result INTO the
236/// executor-provided `outputs[0]` buffer (rather than allocating a fresh
237/// output and replacing it). Only write-into ops are safe in the
238/// executor's Reuse (capture) mode: a replace-the-buffer wrapper would
239/// allocate inside the capture scope AND change the output's device
240/// address, invalidating the captured graph. [`capture_decode`] rejects
241/// any graph whose compute nodes fall outside this set — a surfaced
242/// capability gap (telemetry-worthy), never a silent miscompile.
243///
244/// The set is the full decode op-set, all VERIFIED to replay bit-exact under
245/// capture (each with a forced-freed-memory-reuse test — see the `diag_*` and
246/// `capture_decode_*` GPU tests).
247///
248/// **History / the big correction (2026-07-10):** `MatMul` and `IndexSelect`
249/// were *briefly* excluded on the belief they weren't capture-safe (matmul's
250/// "cuBLAS internal state", index_select's "host arrays / driver anomaly").
251/// That was ALL WRONG — it was a single Fuel-side bug: `capture_decode`
252/// consumed `inputs` and retained only compute OUTPUTS, so any input buffer
253/// (weights, embedding table) the caller didn't independently hold was FREED
254/// after capture, and the captured graph replayed against freed/reused memory
255/// → intermittent partial-wrong output (cuBLAS "split-K columns", index_select
256/// "element 0"). Fixed by `CapturedDecode::retained_inputs`. cuBLAS gemm +
257/// index_select then replay bit-exact (0/50 even with forced reuse), so the
258/// baracuda GEMV + gather_rows are NOT needed for capture-safety.
259///
260/// **`Rope` (`OpKind::Rope`, corrected 2026-07-11)**: previously excluded on
261/// the (now-disproven) assumption that decode's rope always goes through
262/// `rope_with_tables` (decomposed to elementwise ops including `Concat`, see
263/// below) rather than this fused single-input kernel. Tracing a real Llama
264/// decode graph's capture_decode rejection (`capture_decode_matches_persistent`
265/// GPU test, `fuel-core`) found `Op::Rope` nodes placed by the optimizer
266/// (`rope_with_tables` is not always selected — shape-dependent). The
267/// dispatch wrapper (`cuda_rope_baracuda_wrapper!` in
268/// `baracuda_dispatch.rs`) already delegates to baracuda's write-into
269/// `rope_*_into` FFI — that mechanism predates this predicate fix, it was
270/// simply never added here. `rope.fkc.md`'s CUDA kernel is audited
271/// (`docs/architecture/10-decisions-log.md`, 2026-07-11): grid-stride,
272/// one thread per output element, reads only its own rotation-pair partner,
273/// no atomics/shared-memory/cross-thread state — genuinely capture-safe.
274///
275/// **`Concat` (4b-γ) is capture-safe ONLY for N==2 inputs** — baracuda's
276/// `concat2_into` write-into path covers exactly the decode graph's only
277/// Concat (the rope rotate-half's 2-input `concat(-x2, x1)`, from
278/// `rope_with_tables`'s CUDA decomposition). This predicate alone can't
279/// express the N-arity condition (a pure `OpKind -> bool` fn has no access
280/// to `OpParams`); `capture_decode`'s validation loop adds an explicit N>2
281/// rejection alongside the `op_kind_is_capture_writeinto` check so N>2
282/// Concat is refused at validation time, before the warm pass ever runs —
283/// the write-into wrapper's N>2 fallback (which still allocates internally
284/// for its N-2 intermediates) is therefore provably never invoked while
285/// `persistent.mode == Reuse`. N-ary write-into concat is a real future gap
286/// if a consumer needs it; not built here (no consumer today).
287///
288/// **`Op::Contiguize` (4b-γ)** — `WorkItemKind::ContiguizeOf`, not a
289/// `Kernel` work item, so this predicate never even sees it — became
290/// capture-safe via a separate write-into path (`contiguize_into`) wired
291/// directly into the `ContiguizeOf` executor arm's `PersistentOutputs`
292/// consultation, mirroring how `Kernel` nodes consult this predicate. No
293/// change needed here or in `capture_decode`'s validation loop: a given
294/// `ContiguizeOf` node's allocate-vs-zero-copy branch is a static
295/// layout/stride property, identical across the warm and capture passes
296/// (both replay the same compiled item list), so it's unconditionally safe
297/// once wired to `PersistentOutputs`.
298///
299/// LESSON: a bug reproduced through the full harness but not in isolation is
300/// the harness's fault, not the callee's — chase the differentiator (here,
301/// input lifetime), don't conclude "kernel/library not capture-safe" from it.
302///
303/// [`capture_decode`]: PipelinedExecutor::capture_decode
304/// GAP-217b: gated on `cuda` because its ONLY caller is
305/// `capture_decode` (`#[cfg(feature = "cuda")]`, ~:1266). Without this it
306/// reports as dead code on every default build — a false signal on a
307/// predicate whose doc comment is a record of hard-won capture-safety
308/// findings, i.e. exactly the kind of item someone eventually deletes for
309/// being "unused". Gating it makes the reachability claim honest instead of
310/// leaving a warning to argue the opposite.
311#[cfg(feature = "cuda")]
312fn op_kind_is_capture_writeinto(op: OpKind) -> bool {
313    matches!(
314        op,
315        // Binary elementwise — residual + gating.
316        OpKind::AddElementwise
317            | OpKind::SubElementwise
318            | OpKind::MulElementwise
319            | OpKind::DivElementwise
320            | OpKind::MaximumElementwise
321            | OpKind::MinimumElementwise
322            | OpKind::PowElementwise
323            | OpKind::RemElementwise
324            // Softmax.
325            | OpKind::SoftmaxLastDim
326            | OpKind::LogSoftmaxLastDim
327            // Affine (mul_scalar/add_scalar — the 1/√d attention scale).
328            | OpKind::Affine
329            // Dense matmul (cuBLAS gemm_dense — capture-safe; the earlier
330            // "not replay-stable" was the dangling-input bug, now fixed).
331            | OpKind::MatMul
332            // Embedding lookup (was the same dangling-input bug, not a kernel issue).
333            | OpKind::IndexSelect
334            // RMS-norm: capture-safe via the device's fixed workspace for its
335            // per-row RMS scratch (warm sizes it; capture + replay reuse, no alloc).
336            | OpKind::RmsNormLastDim
337            // Unary activations (write-into + workspace-free).
338            | OpKind::SiluElementwise
339            | OpKind::GeluTanhElementwise
340            | OpKind::GeluElementwise
341            // Negation (write-into + workspace-free) — the rope rotate-half
342            // decomposition's `neg_second` half (CapturedRun 4b-resume: rope
343            // runs decomposed on CUDA since there's no rotate-half fused kernel).
344            | OpKind::NegElementwise
345            // N==2 concat only (rope rotate-half) — see the doc comment
346            // above; N>2 is rejected explicitly in capture_decode's
347            // validation loop, not by this predicate.
348            | OpKind::Concat
349            // Rotary position embedding (fused single-input kernel) — see
350            // the doc comment above.
351            | OpKind::Rope
352    )
353}
354
355/// The product of [`PipelinedExecutor::capture_decode`]: a replayable
356/// CUDA-graph capture of a single-device decode step plus the handle to
357/// the fixed output buffer the captured launches write into.
358///
359/// Replay contract: update the fixed INPUT buffers (the Arcs passed into
360/// `capture_decode`) in place via H2D, call [`run`](Self::run)`.replay()`,
361/// then read [`output`](Self::output) — the captured launches recompute
362/// into it at the same device addresses. `persistent` holds every compute
363/// node's fixed buffer (the same addresses baked into the graph), exposed
364/// so a caller can inspect / retain them across replays.
365#[cfg(feature = "cuda")]
366pub struct CapturedDecode {
367    /// The instantiated, replayable capture.
368    pub run: fuel_cuda_backend::CapturedRun,
369    /// The realize target's fixed output buffer (written by replay).
370    pub output: Arc<RwLock<Storage>>,
371    /// The target's resolved output [`Layout`].
372    pub output_layout: Layout,
373    /// Every compute node's fixed output buffer (the capture-baked
374    /// addresses). Retained so they outlive the [`CapturedRun`].
375    pub persistent: HashMap<NodeId, Arc<RwLock<Storage>>>,
376    /// EVERY input buffer's Arc (weights, KV, per-token inputs), retained so
377    /// their device addresses — baked into the captured graph — stay valid
378    /// for the life of the capture. Without this, an input buffer the CALLER
379    /// doesn't independently hold is freed when `capture_decode` returns
380    /// (it consumes `inputs`), and replay reads freed/reused memory. This is
381    /// the fix for the "index_select / matmul mis-replay" — a dangling input
382    /// pointer, NOT a kernel/cuBLAS/driver capture issue.
383    pub retained_inputs: Vec<Arc<RwLock<Storage>>>,
384}
385
386/// Warm→capture→replay orchestration over [`capture_decode`] for a
387/// persistent decode loop (the CapturedRun build-out, Increment 4a).
388///
389/// Owns the FIXED per-token INPUT buffers — the ones that change each token
390/// (token-id, rope position, mask, KV write offset) — at stable device
391/// addresses, plus the [`CapturedDecode`]. Each generated token is one
392/// [`replay_token`](Self::replay_token): H2D-update the fixed input buffers
393/// IN PLACE (same addresses the captured graph reads), replay the captured
394/// graph (one `cuGraphLaunch`, no per-op launch overhead), then read the
395/// output at its fixed address.
396///
397/// The mechanism is graph-agnostic: [`capture`](Self::capture) runs a
398/// single-device CUDA decode graph through the persistent-output executor;
399/// the model layer (fuel-core's `DecodeSession`) supplies the held graph +
400/// the fixed buffers and drives the per-token updates. Every compute op must
401/// be capture-safe (`op_kind_is_capture_writeinto`) — `capture` surfaces any
402/// that are not (today: matmul, index_select — pending baracuda kernels).
403///
404/// [`capture_decode`]: PipelinedExecutor::capture_decode
405#[cfg(feature = "cuda")]
406pub struct CapturedDecodeSession {
407    device: fuel_cuda_backend::CudaDevice,
408    captured: CapturedDecode,
409    /// Per-token input buffers, keyed by NodeId — fixed device addresses
410    /// updated in place each token (the input addresses the captured graph
411    /// reads). A subset of the `inputs` handed to [`capture`](Self::capture).
412    per_token_inputs: HashMap<NodeId, Arc<RwLock<Storage>>>,
413    /// EVERY input buffer's Arc (weights, KV, per-token), retained so their
414    /// device addresses stay valid for the life of the capture. `capture_decode`
415    /// consumes `inputs` and only `CapturedDecode` retains the compute-output
416    /// buffers, so without this the WEIGHT input buffers would be freed and the
417    /// captured graph would replay against freed memory.
418    _retained_inputs: Vec<Arc<RwLock<Storage>>>,
419}
420
421#[cfg(feature = "cuda")]
422impl CapturedDecodeSession {
423    /// Capture the decode graph once against the given fixed input buffers.
424    ///
425    /// `inputs` are ALL the graph's leaves (weights, KV, per-token data) at
426    /// fixed device addresses; `per_token_input_ids` names the subset that
427    /// changes each token. The per-token Arcs are snapshotted (shared, not
428    /// copied) so overwriting them in place later feeds the captured graph's
429    /// fixed input reads. Returns a session ready for
430    /// [`replay_token`](Self::replay_token). Errors (never panics) if the
431    /// graph carries a capture-unsafe op or a per-token id is not an input.
432    pub fn capture(
433        graph: Arc<RwLock<Graph>>,
434        target: NodeId,
435        inputs: StorageCache,
436        per_token_input_ids: &[NodeId],
437        sym_env: SymEnv,
438    ) -> Result<Self> {
439        use fuel_memory::BackendStorage;
440        // Snapshot the per-token input Arcs + retain EVERY input Arc BEFORE
441        // `inputs` is consumed by capture_decode (so no input buffer's device
442        // address is freed while the captured graph still bakes it).
443        let retained_inputs: Vec<Arc<RwLock<Storage>>> = inputs.values().cloned().collect();
444        let mut per_token_inputs = HashMap::with_capacity(per_token_input_ids.len());
445        for &id in per_token_input_ids {
446            let arc = inputs.get(&id).cloned().ok_or_else(|| {
447                Error::Msg(format!(
448                    "CapturedDecodeSession::capture: per-token input {:?} not in inputs",
449                    id,
450                ))
451                .bt()
452            })?;
453            per_token_inputs.insert(id, arc);
454        }
455        // Derive the CUDA device from any input.
456        let device = {
457            let any = per_token_inputs
458                .values()
459                .next()
460                .or_else(|| inputs.values().next())
461                .ok_or_else(|| {
462                    Error::Msg("CapturedDecodeSession::capture: no inputs".into()).bt()
463                })?;
464            let guard = any.read().map_err(|_| poisoned("input storage"))?;
465            match &guard.inner {
466                BackendStorage::Cuda(c) => c.device().clone(),
467                other => {
468                    return Err(Error::Msg(format!(
469                        "CapturedDecodeSession::capture: input is BackendStorage::{:?}, not Cuda",
470                        other.backend_id(),
471                    ))
472                    .bt());
473                }
474            }
475        };
476        let captured = PipelinedExecutor::capture_decode(graph, target, inputs, sym_env)?;
477        Ok(Self {
478            device,
479            captured,
480            per_token_inputs,
481            _retained_inputs: retained_inputs,
482        })
483    }
484
485    /// Replay one token. For each `(node_id, host_bytes)` in `updates`,
486    /// overwrite that per-token input buffer IN PLACE (H2D, same device
487    /// address), then replay the captured graph and return the output buffer
488    /// (now holding this token's result). `host_bytes.len()` must equal the
489    /// buffer's byte length.
490    /// **Every compute node's output buffer, keyed by `NodeId`** — the
491    /// capture's inspection surface.
492    ///
493    /// Capture is usually described as a launch-overhead optimization, and that
494    /// is what Fuel currently exploits (measured 4.28x at k=1). But recording
495    /// the graph has a second, unexploited consequence: **every intermediate
496    /// gets a FIXED device address that survives across replays.** On the
497    /// ordinary path intermediates are transient — allocated, consumed, freed —
498    /// so there is nothing to look at after the fact.
499    ///
500    /// That makes a captured session a **whole-graph, per-node, addressable
501    /// snapshot of what actually executed**, which is a different artifact from
502    /// anything the planner records. `OptimizedGraph::placement_of` says what
503    /// the optimizer DECIDED; this says what the device HELD. Those can
504    /// disagree, and an independent second instrument is the only way to notice.
505    ///
506    /// Uses this enables, none of which need re-running the model:
507    /// - read any intermediate after a token;
508    /// - compare per-node against a CPU oracle — whole-graph differential,
509    ///   where FKC verification today is per-KERNEL;
510    /// - measure real per-op divergence for the tolerance/Judge work instead of
511    ///   modelling it.
512    ///
513    /// Buffers are live device memory owned by the capture; they are overwritten
514    /// by the next `replay_token`. Read them before replaying again.
515    pub fn node_outputs(&self) -> &HashMap<NodeId, Arc<RwLock<Storage>>> {
516        &self.captured.persistent
517    }
518
519    pub fn replay_token(&self, updates: &[(NodeId, &[u8])]) -> Result<Arc<RwLock<Storage>>> {
520        use fuel_memory::BackendStorage;
521        for (id, bytes) in updates {
522            let arc = self.per_token_inputs.get(id).ok_or_else(|| {
523                Error::Msg(format!(
524                    "CapturedDecodeSession::replay_token: {:?} is not a per-token input",
525                    id,
526                ))
527                .bt()
528            })?;
529            let guard = arc.read().map_err(|_| poisoned("per-token input"))?;
530            match &guard.inner {
531                BackendStorage::Cuda(c) => c.write_from_host(bytes)?,
532                other => {
533                    return Err(Error::Msg(format!(
534                        "CapturedDecodeSession::replay_token: input {:?} is \
535                         BackendStorage::{:?}, not Cuda",
536                        id,
537                        other.backend_id(),
538                    ))
539                    .bt());
540                }
541            }
542        }
543        self.captured.run.replay(&self.device)?;
544        self.device.synchronize()?;
545        Ok(Arc::clone(&self.captured.output))
546    }
547
548    /// The fixed output buffer, updated by each
549    /// [`replay_token`](Self::replay_token). Holds the warm-run result until
550    /// the first replay.
551    pub fn output(&self) -> &Arc<RwLock<Storage>> {
552        &self.captured.output
553    }
554
555    /// The output's resolved [`Layout`].
556    pub fn output_layout(&self) -> &Layout {
557        &self.captured.output_layout
558    }
559}
560
561/// What flavor of work item the executor is processing.
562/// Disambiguates the four cases:
563enum WorkItemKind {
564    /// `Op::Const` — its Storage Arc is already in the input cache.
565    /// Executor verifies the entry exists and moves on.
566    ConstAdopt,
567    /// Metadata-only view op (`Op::Transpose`, `Op::Permute`,
568    /// `Op::BroadcastTo`): the output's Storage Arc IS the
569    /// input's Storage Arc (bytes shared); `output_layout`
570    /// describes the strided view.
571    ViewOf { input: NodeId },
572    /// Reshape-style adoption: the output is contiguous in
573    /// `output_layout.shape()`. If the input is already contiguous
574    /// + zero offset, the output Arc is the input Arc (zero copy).
575    ///
576    /// Otherwise, the executor auto-contiguizes the input into a
577    /// fresh Arc and uses that.
578    ContiguizeOf { input: NodeId },
579    /// Computational kernel: allocate output, run the compiled
580    /// kernel, store the result. `compiled` is `Some(...)`.
581    Kernel,
582    /// `Op::Iota { len }` — 0-input F32 position generator
583    /// `[0.0, 1.0, …, (len-1)]`. Direct executor dispatch (no kernel /
584    /// binding-table lookup), like `WorkItemKind::Alloc`: a leaf has no
585    /// `inputs[0]` to inherit a backend from, so it can't take the normal
586    /// kernel path. The executor fills the sequence on CPU.
587    ///
588    /// `target_location` is the node's resolved placement when the planner stamped one: the CUDA
589    /// arm reads its GPU ordinal from it (`None` on an unplaced graph, which falls back to GPU 0).
590    Iota {
591        len: usize,
592        target_location: Option<DeviceLocation>,
593    },
594    /// `Op::Release` — metadata-only "this storage is no longer
595    /// needed" directive. Per `Op::Release`'s contract: the output
596    /// is a zero-element marker (NodeId placeholder for graph
597    /// bookkeeping; never read by any consumer). The executor emits
598    /// a zero-byte CPU `Storage` at the node's slot so downstream
599    /// cache lookups don't surface "missing slot" errors; the actual
600    /// deallocation of `inputs[0]` is driven by `destructive_input`
601    /// in the realize loop (Phase B), which drops the Arc held by
602    /// the cache. The held Arc's Drop chain frees device memory
603    /// (sync for CPU, stream-deferred for async backends).
604    ReleaseMarker,
605    /// `Op::WriteSlice` — in-place scatter write. The output adopts
606    /// the destination input's Storage Arc (zero-copy alias); the
607    /// kernel mutates that Arc's bytes via a write lock. The source
608    /// input's slab is copied into the destination's rectangular
609    /// region defined by `OpParams::WriteSlice`'s `ranges`.
610    ///
611    /// Carries `dest`/`source` NodeIds so the executor can:
612    /// 1. Adopt the dest's Arc as the kernel's output slot.
613    /// 2. Pass only the source as a kernel input (the dest is not
614    ///    a read-input to the kernel; it's the destination buffer
615    ///    being mutated in place).
616    ///
617    /// The realize loop's `destructive_input` cleanup evicts the
618    /// `dest` NodeId from the cache after this op runs (per
619    /// `Op::WriteSlice`'s destructive_input == Some(0) contract).
620    /// Downstream consumers read post-write bytes via this op's
621    /// own NodeId, not the dest's.
622    WriteSlice { dest: NodeId, source: NodeId },
623    /// `Op::WriteSliceRotating` — like `WriteSlice` but the rotating
624    /// axis wraps modulo `modulus`. Carries `dest`/`source`/`position`
625    /// NodeIds; the kernel reads the U32 position from `position`'s
626    /// storage and splits the write across the ring boundary if
627    /// `position % modulus + slab_len > modulus`.
628    WriteSliceRotating {
629        dest: NodeId,
630        source: NodeId,
631        position: NodeId,
632    },
633    /// `Op::WriteSliceDoff` — like `WriteSlice` but the start on `axis`
634    /// is read from a device-resident rank-0 `I64` scalar (`offset`)
635    /// at kernel launch, not host-baked. Carries `dest`/`source`/
636    /// `offset` NodeIds; the CUDA wrapper threads `offset`'s device
637    /// pointer straight to the kernel (no D2H) so a captured graph
638    /// replays at the host-updated position. No ring wrap.
639    WriteSliceDoff {
640        dest: NodeId,
641        source: NodeId,
642        offset: NodeId,
643    },
644    /// `Op::Copy { target }` — produce a fresh Storage on
645    /// `target_location`, copying bytes from `inputs[0]`'s residency.
646    ///
647    /// The kernel lookup goes through the standard binding-table path
648    /// at `(OpKind::Copy, [dt, dt], source_backend)`, so D2H is a peer
649    /// of every other op (architecture identity check #1). The
650    /// dedicated WorkItemKind exists because Op::Copy is the one op
651    /// whose output's device differs from `target_backend`:
652    /// `target_backend` is the **source** backend (where the kernel
653    /// runs — it owns the download path), while `target_location`
654    /// drives output allocation. WorkItemKind::Kernel always allocates
655    /// output on `target_backend`; Copy needs the override.
656    ///
657    /// Phase 2 of the bridge-retirement trajectory. Replaces the
658    /// per-variant `match self` in `BackendStorage::read_to_cpu_bytes`
659    /// (deleted alongside this commit) with a graph-level node the
660    /// optimizer can see, cost, and eventually fuse.
661    Copy { target_location: DeviceLocation },
662    /// `Op::Move { target }` — `Op::Copy`'s destructive sibling:
663    /// produce a fresh Storage on `target_location` via the same
664    /// data-movement kernel (binding-table lookup at
665    /// `(OpKind::Copy, [dt, dt], source_backend)`; output allocation
666    /// driven by `target_location`), then release the source. The
667    /// release half is NOT handled in the executor's arm — it rides
668    /// the realize loop's `destructive_input` cleanup
669    /// (`Op::Move::destructive_input() == Some(0)`), exactly like
670    /// `Op::Release`: the cache's Arc to the source drops after the
671    /// move runs and the Drop chain frees device memory (sync for
672    /// CPU, stream-deferred for async backends).
673    ///
674    /// Ordering safety is the graph's job, not this arm's:
675    /// `execution_plan` integrates `derive_ordering`, which pins the
676    /// Move AFTER every non-destructive reader of the source's alias
677    /// set, and `insert_safety_copies` snapshots the source for any
678    /// reader that data-flow-depends on the Move's output. A Move
679    /// therefore never strands a sibling consumer of its source.
680    ///
681    /// Same-device moves are legal and match the legacy
682    /// `GraphExecutor` contract: a plain copy producing fresh
683    /// storage on the same device, with the source still evicted
684    /// afterward.
685    Move { target_location: DeviceLocation },
686    /// `Op::Alloc { target }` — produce a freshly-allocated, zero-
687    /// initialized Storage on `target_location` with the node's shape
688    /// + dtype. Zero inputs.
689    ///
690    /// Doesn't dispatch through the binding table — the executor's
691    /// arm calls each backend's native allocator directly. For
692    /// non-CPU targets it takes the device handle from the
693    /// [`DeviceRegistry`] the caller handed the realize (a
694    /// `*_with_devices` entry point).
695    ///
696    /// Phase 3a of the bridge-retirement trajectory (post-9c).
697    /// Replaces `fuel-tensor::inference_context::alloc_zeroed_on`'s
698    /// per-`DeviceLocation` match with a graph node the optimizer
699    /// can see; the per-backend match moves from fuel-core's bridge
700    /// layer into fuel-storage's executor (the architectural dispatch
701    /// layer).
702    Alloc { target_location: DeviceLocation },
703    /// `Op::ZeroFill` — fill the input's storage bytes with zero,
704    /// in place. Adopts the input's Storage Arc as the output (same
705    /// Storage; bytes mutated). Destructive on `inputs[0]`.
706    ///
707    /// Direct executor dispatch (no binding-table lookup) per the
708    /// same rationale as `WorkItemKind::Alloc`: structural op,
709    /// per-backend dispatch. Per-backend behaviour:
710    /// - CPU: `bytes_mut().fill(0)` via the CoW path.
711    /// - CUDA: `CudaStorageBytes::zero_async` via baracuda alpha.30's
712    ///   `DeviceBuffer::zero_async` (cuMemsetD8Async, in-place).
713    /// - Vulkan: `VulkanBackend::fill_bytes_zero` via
714    ///   `vkCmdFillBuffer` — device-side, ~2× the bandwidth of the
715    ///   old host-staged zeros path that `alloc_zeroed_on` used.
716    ///
717    /// Phase 3a follow-up of bridge-retirement (post-9c). Pairs with
718    /// the uninit-alloc `WorkItemKind::Alloc` to give the
719    /// architecturally clean "Op::Alloc (uninit) → Op::ZeroFill
720    /// (explicit fill)" pipeline.
721    ZeroFill,
722    /// In-place kernel — the output adopts the input at index
723    /// `target_idx`'s Storage Arc and the kernel mutates that Arc's
724    /// bytes through a single write lock. Phase 3 of the in-place ops
725    /// infrastructure
726    /// (`docs/session-prompts/in-place-ops-infrastructure.md`).
727    ///
728    /// Kernel lookup goes through the standard binding table at
729    /// `(op_to_op_kind, [target_dtype], target_backend)`. The wrapper's
730    /// `inputs` slice is empty; `outputs[0]` is the target Arc. The
731    /// wrapper acquires `outputs[0]`'s write lock and calls the
732    /// underlying single-pointer kernel (e.g. baracuda's
733    /// `affine_inplace_*` on CUDA, or the chassis with `src == dst`
734    /// on CPU).
735    ///
736    /// Output Arc adoption: identical to `WorkItemKind::WriteSlice`
737    /// (the output's slot = the target's Arc; the realize loop's
738    /// `destructive_input` cleanup evicts the target's NodeId from the
739    /// cache afterward). Downstream consumers read post-mutation bytes
740    /// through this op's NodeId, not the target's.
741    InplaceKernel {
742        /// Index into `inputs` whose Storage Arc the output adopts.
743        /// Always equal to the source `Op::destructive_input().unwrap()`;
744        /// stored explicitly so the executor doesn't re-derive it.
745        target_idx: usize,
746    },
747    /// `Op::View { slot }` — multi-output projection (Option C,
748    /// Session 4). The output's Storage Arc IS the producer's Arc;
749    /// the WorkItem's `output_layout` was prepared by
750    /// [`fuel_graph::NodeHandle::view`] with the slot's `byte_offset`
751    /// baked into `Layout::start_offset` so downstream kernels reading
752    /// the producer's bytes as `slot_dtype` elements land on the
753    /// slot's first byte. Structurally identical to [`Self::ViewOf`]
754    /// at execute time — kept distinct so error messages and
755    /// telemetry have a clean dispatch point.
756    SlotView { producer: NodeId },
757    /// `Op::ViewOwned { slot }` — multi-output projection with an
758    /// independent destination buffer. At realize time, allocate a
759    /// fresh contiguous Storage of the slot's `(shape, dtype)` on
760    /// the producer's device, then memcpy
761    /// `producer.bytes[slot.byte_offset .. slot.byte_offset + slot.len_bytes]`
762    /// into the new storage. Session 4 ships the CPU path; non-CPU
763    /// backends return a typed error until their copy-with-offset
764    /// hooks land in the followup session.
765    SlotOwn { producer: NodeId, slot: u32 },
766}
767
768/// One unit of work emitted by the compiler thread to the executor
769/// thread.
770/// Phase name of a work item's kind, for the executor's host-phase accounting
771/// (`op_profile::PhaseTimer`). One name per variant so the table splits the
772/// per-item executor time by what the item is.
773fn work_item_kind_name(kind: &WorkItemKind) -> &'static str {
774    match kind {
775        WorkItemKind::ConstAdopt => "item.ConstAdopt",
776        WorkItemKind::ViewOf { .. } => "item.ViewOf",
777        WorkItemKind::ContiguizeOf { .. } => "item.ContiguizeOf",
778        WorkItemKind::Kernel => "item.Kernel",
779        WorkItemKind::Iota { .. } => "item.Iota",
780        WorkItemKind::ReleaseMarker => "item.ReleaseMarker",
781        WorkItemKind::WriteSlice { .. } => "item.WriteSlice",
782        WorkItemKind::WriteSliceRotating { .. } => "item.WriteSliceRotating",
783        WorkItemKind::WriteSliceDoff { .. } => "item.WriteSliceDoff",
784        WorkItemKind::Copy { .. } => "item.Copy",
785        WorkItemKind::Move { .. } => "item.Move",
786        WorkItemKind::Alloc { .. } => "item.Alloc",
787        WorkItemKind::ZeroFill => "item.ZeroFill",
788        WorkItemKind::InplaceKernel { .. } => "item.InplaceKernel",
789        WorkItemKind::SlotView { .. } => "item.SlotView",
790        WorkItemKind::SlotOwn { .. } => "item.SlotOwn",
791    }
792}
793
794/// Work items that choose no backend of their own: adopting an input-cache entry
795/// (`Op::Const`), the metadata-only view items, and `ContiguizeOf` (it runs on its
796/// input's backend; its `target_backend` is a `Cpu` placeholder, which made every
797/// Qwen3 decode step look like ~900 Vulkan -> Cpu -> Vulkan switches and forced a
798/// batch submit at each one). Their `target_backend` is a placeholder
799/// (a `Const` is always stamped `Cpu`; a view inherits its producer's or
800/// defaults to `Cpu`), so letting them take part in the chunk-boundary logic made
801/// every weight `Const` that sits between two Vulkan kernels look like a
802/// Vulkan -> Cpu -> Vulkan backend switch: the executor armed `multi_backend`,
803/// submitted the open Vulkan batch at each "switch", and then waited for it
804/// before the next Vulkan op. In Qwen3-0.6B decode that was about 400 forced
805/// submit-and-wait round trips per step (`docs/research/qwen3-vulkan-decode-profile.md`).
806fn is_backend_neutral(kind: &WorkItemKind) -> bool {
807    matches!(
808        kind,
809        WorkItemKind::ConstAdopt
810            | WorkItemKind::ViewOf { .. }
811            | WorkItemKind::SlotView { .. }
812            | WorkItemKind::ContiguizeOf { .. }
813    )
814}
815
816struct WorkItem {
817    node_id: NodeId,
818    inputs: Vec<NodeId>,
819    /// Number of elements in the output (for output Storage
820    /// allocation; multiplied by dtype size at allocation time).
821    elem_count: usize,
822    dtype: DType,
823    target_backend: BackendId,
824    /// What kind of work this represents (kernel vs adopt vs view).
825    kind: WorkItemKind,
826    /// `Some` for [`WorkItemKind::Kernel`]; `None` for the other
827    /// two. Carries the resolved kernel ref + op_params.
828    compiled: Option<CompiledNode>,
829    /// The output's [`Layout`]. For kernels: always
830    /// `Layout::contiguous(node.shape)`. For metadata-only view
831    /// ops: a strided/broadcast Layout pointing at the input's
832    /// Storage. Carried so the executor can publish the right
833    /// Layout into its layout cache and ultimately return it from
834    /// [`PipelinedExecutor::realize`].
835    output_layout: Layout,
836    /// Index into `inputs` whose storage gets destroyed by this op
837    /// (`Op::Release` / `Op::Move` → `Some(0)`; non-destructive ops
838    /// → `None`). The executor evicts the destroyed input from the
839    /// cache after the op runs, unless it's also in the realize
840    /// target set. Snapshot of `node.op.destructive_input()` at
841    /// compile time.
842    destructive_input: Option<usize>,
843    /// Multi-output bundle metadata (Option C, item 3). `Some(_)`
844    /// when the node was declared multi-output via
845    /// `Graph::set_output_views`; the Kernel arm allocates one
846    /// contiguous output Storage sized to fit every slot's bytes,
847    /// then attaches the bundle via `Storage::with_bundle` so
848    /// downstream `Op::View`/`Op::ViewOwned` nodes resolve
849    /// correctly.
850    output_bundle: Option<Arc<[fuel_ir::storage::OutputView]>>,
851}
852
853/// Merge the graph's side-effect roots into the caller's requested
854/// roots. Preserves caller order (user roots come first), dedupes,
855/// and appends side-effect-bearing nodes (`Op::Print`, `Op::Save`,
856/// etc.) so their effects fire even when not reachable from the
857/// caller's roots. Mirrors `fuel-graph-executor::extend_with_side_effect_roots`.
858///
859/// Short-circuits to a borrow-equivalent `Vec<NodeId>` when the graph
860/// has no side-effect roots — the common case during inference.
861fn extend_with_side_effect_roots(graph: &Graph, user_roots: &[NodeId]) -> Vec<NodeId> {
862    let side = graph.side_effect_roots();
863    if side.is_empty() {
864        return user_roots.to_vec();
865    }
866    let mut out = Vec::with_capacity(user_roots.len() + side.len());
867    out.extend_from_slice(user_roots);
868    for &s in side {
869        if !out.contains(&s) {
870            out.push(s);
871        }
872    }
873    out
874}
875
876/// Pipelined executor: walks a graph, compiles each node in a
877/// dedicated thread, executes the compiled stream on the calling
878/// thread.
879///
880/// # Architectural commitments (Phase 7.6 step 9c)
881///
882/// ## Fail-fast dispatch — no runtime CPU fallback
883///
884/// The binding-table lookup is fail-fast. If
885/// `global_bindings().lookup(op_kind, dtypes, backend)` returns
886/// `None`, `realize` / `realize_many` surface a typed `Error::Msg`
887/// at compile time. There is **no runtime fallback** to a CPU
888/// sibling when a registered kernel returns `Err`; we commit to the
889/// backend contract that registered kernels must succeed for shapes
890/// matching their declared coverage.
891///
892/// Rationale: per-decision-point alternatives (architecture v1.0
893/// §04) already let multiple backends register at the same key. If
894/// a backend's coverage is partial, the right answer is to register
895/// only the shapes it actually handles — not to silently fall back
896/// at runtime, which masks bugs and slows the hot path. The
897/// long-term home for "this op on this device" is graph-level
898/// dispatch insertion (Op::Copy edges to a backend that does
899/// support the shape), which makes the routing decision visible in
900/// the IR rather than hidden in the executor. Picker-arc step 4b
901/// landed exactly that: `compile_plan`'s off-device fallback
902/// (`PlanOptions::fallback_placements_for`) admits a candidate on
903/// another device when the pinned device lacks the implementation,
904/// and the bridge's cross-device-copy pass stitches residency
905/// around the off-device winner. There is exactly ONE fallback
906/// owner — the plan-time picker; this executor still dispatches
907/// fail-fast, and ops with no implementation anywhere surface the
908/// plan-time `NoBackendForOp` error.
909///
910/// This is a deliberate departure from the legacy executor's
911/// `cpu_fallback(op, inputs, shape, dtype, cache)` semantics.
912///
913/// ## Optimizer separation — callers compose
914///
915/// The pipelined executor does **not** run `fuel_graph::opt` or any
916/// `RuleRegistry` pass itself. Callers that want graph-level
917/// optimization compose it at the call site:
918///
919/// ```ignore
920/// let optimized_targets = registry.optimize_to_fixpoint(&graph, &targets);
921/// PipelinedExecutor::realize_many(graph, &optimized_targets, inputs)?;
922/// ```
923///
924/// Rationale: the legacy `GraphExecutor<B>::with_optimization(bool)`
925/// coupling reflected its per-typed-entry API surface
926/// (`realize_f32`, etc.) where the convenience of a single
927/// optimize+realize call was load-bearing. The pipelined path has
928/// a uniform `realize_many` that composes trivially — no need to
929/// re-couple them at the executor layer. This keeps the executor
930/// focused on execution and lets the optimizer evolve
931/// independently (different rule registries per call site, mid-
932/// pipeline opt+realize+opt+realize patterns, etc.).
933pub struct PipelinedExecutor;
934
935impl PipelinedExecutor {
936    /// Realize `target` and every transitive dependency. Compilation
937    /// runs in a worker thread; execution runs on the calling
938    /// thread.
939    ///
940    /// Pre-conditions:
941    ///
942    /// - Every reachable `Op::Const` node must have a corresponding
943    ///   entry in `inputs` (pre-realized Storage Arc).
944    /// - Every reachable non-`Const` node must have its
945    ///   `target_backend` set in the graph
946    ///   (`Graph::set_target_backend`).
947    /// - The op + dtype must be registered in `global_bindings()`.
948    ///
949    /// Returns the realized `Storage` Arc for `target` plus its
950    /// resolved [`Layout`]. The Layout is contiguous for kernel
951    /// outputs; for graphs whose target is a metadata-only view
952    /// op (`Op::Transpose`, `Op::Permute`, `Op::BroadcastTo`),
953    /// the returned Storage shares its bytes with an upstream
954    /// node and the Layout encodes the view's strides + offset.
955    ///
956    /// Production-correct: errors on any unmet precondition rather
957    /// than panicking.
958    pub fn realize(
959        graph: Arc<RwLock<Graph>>,
960        target: NodeId,
961        inputs: StorageCache,
962    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
963        Self::realize_inner(
964            graph,
965            target,
966            inputs,
967            OrderSource::Default,
968            SymEnv::default(),
969        )
970        .map(|(s, l, _produced)| (s, l))
971    }
972
973    /// [`Self::realize`] with the device handles the caller already holds (ROADMAP row 137, seam S3 step 3c):
974    /// a CUDA or Vulkan place named in `devices` is where the executor finds its handle. Use this for any
975    /// graph that allocates on, or copies to, a GPU; the plain [`Self::realize`] has no handle to give the
976    /// executor, so it is for CPU graphs and for graphs whose GPU work needs none.
977    pub fn realize_with_devices(
978        graph: Arc<RwLock<Graph>>,
979        target: NodeId,
980        inputs: StorageCache,
981        devices: DeviceRegistry,
982    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
983        Self::realize_inner_with(
984            graph,
985            target,
986            inputs,
987            OrderSource::Default,
988            SymEnv::default(),
989            devices,
990        )
991        .map(|(s, l, _produced)| (s, l))
992    }
993
994    /// Env-carrying sibling of [`Self::realize`]: realize `target` with a
995    /// per-pass [`SymEnv`] supplying the runtime bindings for any
996    /// `DynScalar` op params (today: `Op::WriteSlice`'s dynamic start
997    /// offset — Phase D symbolic extents). An **empty** env is
998    /// byte-identical to [`Self::realize`]; the env is consulted only by ops
999    /// that carry a `DynScalar`, so a graph with none ignores it. Uses
1000    /// the default (`execution_plan`) dispatch order.
1001    ///
1002    /// This is the input-determined path for persistent decode (the
1003    /// per-token `cached_len` write offset). The `OptimizedGraph`/route
1004    /// entry points keep an empty env until the realize bridge threads
1005    /// the session env through them (Phase D step 1, fuel-core).
1006    pub fn realize_with_env(
1007        graph: Arc<RwLock<Graph>>,
1008        target: NodeId,
1009        inputs: StorageCache,
1010        sym_env: SymEnv,
1011    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1012        Self::realize_inner(graph, target, inputs, OrderSource::Default, sym_env)
1013            .map(|(s, l, _produced)| (s, l))
1014    }
1015
1016    /// Producing sibling of [`Self::realize_with_env`]: realize `target` and
1017    /// ALSO return the [`SymEnv`] of symbols BOUND BY PRODUCERS during the
1018    /// pass — data-determined dynamic shapes (`Op::NonZeroIndices`'s
1019    /// runtime count, etc.). The returned env is disjoint from the input
1020    /// `sym_env` (which is input-determined). Empty when the graph has no
1021    /// data-determined producer. This is the observation point for the
1022    /// increment-2a bind seam; a downstream pass consumes these bindings
1023    /// as dynamic extents.
1024    pub fn realize_with_env_producing(
1025        graph: Arc<RwLock<Graph>>,
1026        target: NodeId,
1027        inputs: StorageCache,
1028        sym_env: SymEnv,
1029    ) -> Result<(Arc<RwLock<Storage>>, Layout, SymEnv)> {
1030        Self::realize_inner(graph, target, inputs, OrderSource::Default, sym_env)
1031    }
1032
1033    /// PR-A3b-1 entry: realize `target` driven from `optimized`'s
1034    /// in-place "plan IS the graph" form. The dispatch order is the
1035    /// `OptimizedGraph`'s `extract_runs`/`lower_run` lowering (computed
1036    /// after safety-copy insertion); per-node kernel resolution uses
1037    /// the binding-table-lookup path (no `ExecutionPlan`, so no
1038    /// route-picking — A3b-1 is branchless). The optimize-time
1039    /// `generation` drives the `TopologyChanged` chunk-boundary check.
1040    ///
1041    /// Pre-conditions match [`Self::realize`]: every reachable kernel-bearing
1042    /// node must have `target_backend` set (the bridge's
1043    /// `stamp_plan_backends` does this) and a registered binding.
1044    pub fn realize_with_optimized(
1045        graph: Arc<RwLock<Graph>>,
1046        target: NodeId,
1047        inputs: StorageCache,
1048        optimized: &OptimizedGraph,
1049    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1050        Self::realize_inner(
1051            graph,
1052            target,
1053            inputs,
1054            OrderSource::Optimized {
1055                optimized,
1056                route: None,
1057            },
1058            SymEnv::default(),
1059        )
1060        .map(|(s, l, _produced)| (s, l))
1061    }
1062
1063    /// [`Self::realize_with_optimized`] with the device handles the caller already holds (ROADMAP row 137,
1064    /// seam S3 step 3b): a CUDA or Vulkan place named in `devices` is not looked for in the storage cache.
1065    pub fn realize_with_optimized_with_devices(
1066        graph: Arc<RwLock<Graph>>,
1067        target: NodeId,
1068        inputs: StorageCache,
1069        optimized: &OptimizedGraph,
1070        devices: DeviceRegistry,
1071    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1072        Self::realize_inner_with(
1073            graph,
1074            target,
1075            inputs,
1076            OrderSource::Optimized {
1077                optimized,
1078                route: None,
1079            },
1080            SymEnv::default(),
1081            devices,
1082        )
1083        .map(|(s, l, _produced)| (s, l))
1084    }
1085
1086    /// [`Self::realize_with_optimized_picking_env`] with the device handles the caller already holds.
1087    #[allow(clippy::too_many_arguments)]
1088    pub fn realize_with_optimized_picking_env_with_devices(
1089        graph: Arc<RwLock<Graph>>,
1090        target: NodeId,
1091        inputs: StorageCache,
1092        optimized: &OptimizedGraph,
1093        selector: Option<Arc<dyn RuntimeSelector>>,
1094        lookup: Option<BackendRuntimeLookup>,
1095        sym_env: SymEnv,
1096        devices: DeviceRegistry,
1097    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1098        let order_source = match Self::streaming_pick_for(&graph, selector, lookup)? {
1099            Some(pick) => {
1100                return Self::realize_inner_with(
1101                    graph,
1102                    target,
1103                    inputs,
1104                    OrderSource::Streaming {
1105                        optimized,
1106                        pick: &pick,
1107                    },
1108                    sym_env,
1109                    devices,
1110                )
1111                .map(|(s, l, _produced)| (s, l));
1112            }
1113            None => OrderSource::Optimized {
1114                optimized,
1115                route: None,
1116            },
1117        };
1118        Self::realize_inner_with(graph, target, inputs, order_source, sym_env, devices)
1119            .map(|(s, l, _produced)| (s, l))
1120    }
1121
1122    /// [`Self::realize_with_optimized_picking_cached_env`] with the device handles the caller already holds.
1123    #[allow(clippy::too_many_arguments)]
1124    pub fn realize_with_optimized_picking_cached_env_with_devices(
1125        graph: Arc<RwLock<Graph>>,
1126        target: NodeId,
1127        inputs: StorageCache,
1128        optimized: &OptimizedGraph,
1129        order_cache: &std::sync::OnceLock<Vec<NodeId>>,
1130        selector: Option<Arc<dyn RuntimeSelector>>,
1131        lookup: Option<BackendRuntimeLookup>,
1132        sym_env: SymEnv,
1133        devices: DeviceRegistry,
1134    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1135        let order_source = match Self::streaming_pick_for(&graph, selector, lookup)? {
1136            Some(pick) => {
1137                return Self::realize_inner_with(
1138                    graph,
1139                    target,
1140                    inputs,
1141                    OrderSource::Streaming {
1142                        optimized,
1143                        pick: &pick,
1144                    },
1145                    sym_env,
1146                    devices,
1147                )
1148                .map(|(s, l, _produced)| (s, l));
1149            }
1150            None => OrderSource::Cached {
1151                optimized,
1152                order_cache,
1153            },
1154        };
1155        Self::realize_inner_with(graph, target, inputs, order_source, sym_env, devices)
1156            .map(|(s, l, _produced)| (s, l))
1157    }
1158
1159    /// Env-carrying sibling of [`Self::realize_with_optimized`]: same
1160    /// optimized-graph dispatch, but with a per-pass [`SymEnv`] supplying
1161    /// the runtime bindings for `DynScalar` op params (Phase D symbolic
1162    /// extents). An empty env is byte-identical to
1163    /// [`Self::realize_with_optimized`]. The realize bridge threads its session
1164    /// env through here for persistent decode.
1165    pub fn realize_with_optimized_env(
1166        graph: Arc<RwLock<Graph>>,
1167        target: NodeId,
1168        inputs: StorageCache,
1169        optimized: &OptimizedGraph,
1170        sym_env: SymEnv,
1171    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1172        Self::realize_inner(
1173            graph,
1174            target,
1175            inputs,
1176            OrderSource::Optimized {
1177                optimized,
1178                route: None,
1179            },
1180            sym_env,
1181        )
1182        .map(|(s, l, _produced)| (s, l))
1183    }
1184
1185    /// PR-C1 entry: realize `target` driven from `optimized`'s in-place
1186    /// form **following the runtime route picker's chosen arms**. The
1187    /// dispatch order is the route-aware lowering
1188    /// ([`fuel_graph::lower_picked_route`]) over `route` — the per-branch
1189    /// arm the picker (Picker 2) selected by live telemetry. A branch
1190    /// absent from `route` defaults to arm 0, so an **empty** route is
1191    /// byte-identical to [`Self::realize_with_optimized`] (the no-pressure /
1192    /// no-telemetry contract). A branchless graph has no branches ⇒ the
1193    /// route is empty ⇒ this is exactly the arm-0 path.
1194    pub fn realize_with_optimized_route(
1195        graph: Arc<RwLock<Graph>>,
1196        target: NodeId,
1197        inputs: StorageCache,
1198        optimized: &OptimizedGraph,
1199        route: &PickedRoute,
1200    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1201        Self::realize_inner(
1202            graph,
1203            target,
1204            inputs,
1205            OrderSource::Optimized {
1206                optimized,
1207                route: Some(route),
1208            },
1209            SymEnv::default(),
1210        )
1211        .map(|(s, l, _produced)| (s, l))
1212    }
1213
1214    /// Env-carrying sibling of [`Self::realize_with_optimized_route`] — the
1215    /// route-aware lowering with a per-pass [`SymEnv`]. An empty env is
1216    /// byte-identical to [`Self::realize_with_optimized_route`].
1217    pub fn realize_with_optimized_route_env(
1218        graph: Arc<RwLock<Graph>>,
1219        target: NodeId,
1220        inputs: StorageCache,
1221        optimized: &OptimizedGraph,
1222        route: &PickedRoute,
1223        sym_env: SymEnv,
1224    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1225        Self::realize_inner(
1226            graph,
1227            target,
1228            inputs,
1229            OrderSource::Optimized {
1230                optimized,
1231                route: Some(route),
1232            },
1233            sym_env,
1234        )
1235        .map(|(s, l, _produced)| (s, l))
1236    }
1237
1238    /// Cleanup Step C/D entry: the executor OWNS `Op::Branch` arm-selection.
1239    /// Given the runtime `selector` + the live device `lookup` (built
1240    /// bridge-side from the realize `Device` + Judge oracle and passed in,
1241    /// exactly like the residency `input_residency` provider), pick one arm per
1242    /// branch HERE — at dispatch — then lower the chosen route. The per-arm
1243    /// candidates are re-enumerated from the runtime binding registry + the
1244    /// graph (Step D: no threaded `ExecutionPlan`).
1245    ///
1246    /// No `selector` (the `runtime_selector_disabled()` opt-out) or a
1247    /// branchless graph yields the arm-0 lowering, byte-identical to Phase B.
1248    ///
1249    /// **Step E Phase C, PR C1 — STREAMING.** A branched graph WITH a
1250    /// selector no longer resolves the whole route up front: it routes to the
1251    /// `OrderSource::Streaming` walk, where the compiler thread resolves
1252    /// each branch lazily as the frontier reaches it (via
1253    /// [`resolve_branch`]). C1 keeps the SAME VRAM-only selector chain — so
1254    /// the streamed route equals the one-shot `pick_route` route byte-for-byte
1255    /// — and only changes *when* a branch resolves; C2 makes that moment read
1256    /// live device load.
1257    pub fn realize_with_optimized_picking_env(
1258        graph: Arc<RwLock<Graph>>,
1259        target: NodeId,
1260        inputs: StorageCache,
1261        optimized: &OptimizedGraph,
1262        selector: Option<Arc<dyn RuntimeSelector>>,
1263        lookup: Option<BackendRuntimeLookup>,
1264        sym_env: SymEnv,
1265    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1266        match Self::streaming_pick_for(&graph, selector, lookup)? {
1267            Some(pick) => Self::realize_inner(
1268                graph,
1269                target,
1270                inputs,
1271                OrderSource::Streaming {
1272                    optimized,
1273                    pick: &pick,
1274                },
1275                sym_env,
1276            )
1277            .map(|(s, l, _produced)| (s, l)),
1278            None => Self::realize_with_optimized_env(graph, target, inputs, optimized, sym_env),
1279        }
1280    }
1281
1282    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
1283    /// §5) — cached sibling of [`Self::realize_with_optimized_picking_env`]
1284    /// for the plan-once persistent-decode caller, which holds `order_cache`
1285    /// across repeated calls over the SAME graph/roots/`optimized` (one per
1286    /// `DecodeSession`, initially empty). On a branchless graph with no
1287    /// selector pressure (the decode shape this is for), dispatches via
1288    /// [`OrderSource::Cached`] — computed once, reused thereafter, see that
1289    /// variant's doc for the safety argument. A branched graph WITH a
1290    /// resolved selector pick falls back to the uncached
1291    /// [`OrderSource::Streaming`] path unchanged (caching doesn't apply
1292    /// there; this entry point exists for the decode case, not to cover
1293    /// every caller).
1294    pub fn realize_with_optimized_picking_cached_env(
1295        graph: Arc<RwLock<Graph>>,
1296        target: NodeId,
1297        inputs: StorageCache,
1298        optimized: &OptimizedGraph,
1299        order_cache: &std::sync::OnceLock<Vec<NodeId>>,
1300        selector: Option<Arc<dyn RuntimeSelector>>,
1301        lookup: Option<BackendRuntimeLookup>,
1302        sym_env: SymEnv,
1303    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1304        match Self::streaming_pick_for(&graph, selector, lookup)? {
1305            Some(pick) => Self::realize_inner(
1306                graph,
1307                target,
1308                inputs,
1309                OrderSource::Streaming {
1310                    optimized,
1311                    pick: &pick,
1312                },
1313                sym_env,
1314            )
1315            .map(|(s, l, _produced)| (s, l)),
1316            None => Self::realize_inner(
1317                graph,
1318                target,
1319                inputs,
1320                OrderSource::Cached {
1321                    optimized,
1322                    order_cache,
1323                },
1324                sym_env,
1325            )
1326            .map(|(s, l, _produced)| (s, l)),
1327        }
1328    }
1329
1330    /// Build the [`StreamingPick`] for the executor's picking entry points —
1331    /// the streaming successor of the one-shot `pick_route_for` (which was the
1332    /// relocated body of the bridge's old `resolve_runtime_route`). Returns
1333    /// `None` (⇒ arm-0 lowering, the untouched `route: None` /
1334    /// `dispatch_order` path) when there is no `selector` (the disabled
1335    /// opt-out) or the graph has no `Op::Branch` (the branchless fast-path:
1336    /// skip the streaming machinery entirely so the common case is unchanged
1337    /// and byte-identical). Otherwise it carries the selector + lookup into
1338    /// the [`OrderSource::Streaming`] walk, which resolves each branch at the
1339    /// frontier (PR C1). The per-arm candidates are re-enumerated from the
1340    /// runtime binding registry inside the compiler thread (Step D — was the
1341    /// threaded `ExecutionPlan`).
1342    fn streaming_pick_for(
1343        graph: &Arc<RwLock<Graph>>,
1344        selector: Option<Arc<dyn RuntimeSelector>>,
1345        // Accepted for call-site parity with `pick_route` but not stored: the
1346        // streaming walk reads VRAM + load through the selector, which holds its
1347        // own `BackendRuntimeLookup`.
1348        _lookup: Option<BackendRuntimeLookup>,
1349    ) -> Result<Option<StreamingPick>> {
1350        let Some(selector) = selector else {
1351            return Ok(None);
1352        };
1353        let g = graph
1354            .read()
1355            .map_err(|_| Error::Msg("graph lock poisoned".into()).bt())?;
1356        let has_branch = (0..g.len()).any(|i| matches!(g.node(NodeId(i)).op, Op::Branch { .. }));
1357        if !has_branch {
1358            return Ok(None);
1359        }
1360        Ok(Some(StreamingPick { selector }))
1361    }
1362
1363    /// Capture a single-device CUDA decode step's kernel launches into a
1364    /// replayable [`CapturedRun`] (the CapturedRun executor build-out).
1365    ///
1366    /// Runs the graph TWICE against fixed-address buffers:
1367    ///   1. **Warm (record)**: realize normally into a fresh cache cloned
1368    ///      from `inputs`, recording every compute node's output Arc as its
1369    ///      fixed capture buffer, and synchronizing so the result is stable.
1370    ///   2. **Capture (reuse)**: re-issue the same launch sequence — each
1371    ///      node writing INTO its recorded buffer via the write-into kernel
1372    ///      path (no allocation) — inside [`CudaDevice::capture_run`],
1373    ///      producing an instantiated [`CapturedRun`].
1374    ///
1375    /// Both passes share the SAME input Arcs (cloned map, shared buffers)
1376    /// and the SAME recorded output buffers, so every device address the
1377    /// captured graph bakes in is stable for replay. To replay a later
1378    /// token: overwrite the fixed input buffers in place (H2D), call
1379    /// `run.replay(dev)`, then read `output`.
1380    ///
1381    /// Contract (surfaced as `Err`, never a panic or a mid-capture alloc):
1382    ///   - CUDA-only, single device: every compute node targets `Cuda`;
1383    ///     no cross-device `Op::Copy`/`Move` in the graph.
1384    ///   - Every compute node's op must have a write-into CUDA wrapper
1385    ///     (`op_kind_is_capture_writeinto`); an unsupported op surfaces a
1386    ///     clear capability gap rather than silently breaking the capture.
1387    ///   - Inputs must be contiguous (no auto-Contiguize alloc in capture).
1388    #[cfg(feature = "cuda")]
1389    pub fn capture_decode(
1390        graph: Arc<RwLock<Graph>>,
1391        target: NodeId,
1392        inputs: StorageCache,
1393        sym_env: SymEnv,
1394    ) -> Result<CapturedDecode> {
1395        use fuel_memory::BackendStorage;
1396
1397        // Front matter mirrors realize_inner: safety copies + frozen order.
1398        {
1399            let mut g = graph.write().map_err(|_| poisoned("graph lock"))?;
1400            let effective_roots = extend_with_side_effect_roots(&g, &[target]);
1401            insert_safety_copies(&mut g, &effective_roots);
1402        }
1403        let (compiler_work, _wait_set, seed_layouts) = {
1404            let g = graph.read().map_err(|_| poisoned("graph lock"))?;
1405            let effective_roots = extend_with_side_effect_roots(&g, &[target]);
1406            let (work, wait_set) =
1407                compiler_work_and_wait_set_for(&g, &effective_roots, &OrderSource::Default);
1408            let mut layouts: HashMap<NodeId, Layout> = HashMap::with_capacity(inputs.len());
1409            for &id in inputs.keys() {
1410                layouts.insert(id, g.layout(id));
1411            }
1412            (work, wait_set, layouts)
1413        };
1414
1415        // Compile every WorkItem once (one compiler thread) and collect them
1416        // so both passes replay the identical sequence.
1417        let (tx, rx) = channel::<Result<WorkItem>>();
1418        let graph_for_compiler = Arc::clone(&graph);
1419        let compiler = thread::spawn(move || {
1420            compiler_thread_body(graph_for_compiler, compiler_work, sym_env, tx);
1421        });
1422        let mut items: Vec<WorkItem> = Vec::new();
1423        for item in rx {
1424            items.push(item?);
1425        }
1426        compiler
1427            .join()
1428            .map_err(|_| Error::Msg("compiler thread panicked".to_string()).bt())?;
1429
1430        // CapturedRun 4b Step-4 diagnostic: name every kernel placed OFF Cuda
1431        // (an unseeded / audited-loser op that forces a cross-device copy and
1432        // blocks capture), so verification-ledger seeding can target it
1433        // precisely. Fires only when a capture is attempted AND something is
1434        // mis-placed — otherwise silent.
1435        {
1436            let off: Vec<String> = items
1437                .iter()
1438                .filter_map(|it| match &it.kind {
1439                    WorkItemKind::Kernel if it.target_backend != BackendId::Cuda => {
1440                        let desc = it
1441                            .compiled
1442                            .as_ref()
1443                            .map(|c| format!("{:?} dtypes={:?}", c.op, c.dtypes))
1444                            .unwrap_or_else(|| "?".to_string());
1445                        Some(format!(
1446                            "node {:?}: {desc} on {:?}",
1447                            it.node_id, it.target_backend
1448                        ))
1449                    }
1450                    _ => None,
1451                })
1452                .collect();
1453            if !off.is_empty() {
1454                eprintln!(
1455                    "[capture-diag] {} kernel(s) placed OFF Cuda (these block capture): {}",
1456                    off.len(),
1457                    off.join("; "),
1458                );
1459            }
1460        }
1461
1462        // Capture-safety validation — surface every gap up front, before any
1463        // launch, so a capture scope is never entered on an unsupported graph.
1464        for item in &items {
1465            match &item.kind {
1466                // Op::Move: the destructive half (releasing the source) is
1467                // driven by the realize loop's `destructive_input` cleanup,
1468                // which runs once per REALIZE call — not once per `replay()`.
1469                // A captured graph's `replay()` re-executes the same baked
1470                // launches repeatedly without re-running that surrounding
1471                // cleanup between replays, so whether a repeat-replayed Move
1472                // is even meaningful is unclear; out of scope here (4b-ζ) —
1473                // keep rejecting every Move unconditionally.
1474                WorkItemKind::Move { .. } => {
1475                    return Err(Error::Msg(format!(
1476                        "capture_decode: graph has an Op::Move at node {:?}; \
1477                         Move's destructive source-release half is driven by \
1478                         per-realize cleanup, not per-replay, so capture is \
1479                         not supported for Move (out of scope — see the \
1480                         `capture_decode` validation loop's Move arm).",
1481                        item.node_id,
1482                    ))
1483                    .bt());
1484                }
1485                // Op::Copy: a same-device CUDA→CUDA copy (e.g. an
1486                // `insert_safety_copies` snapshot) has a write-into wrapper
1487                // (`copy_from_cuda_wrapper`'s `BackendStorage::Cuda` branch,
1488                // via `CudaStorageBytes::copy_from_device`) and is
1489                // capture-safe. A copy whose `target_location` is `Cpu` or
1490                // `Vulkan` is a genuine host round-trip / cross-backend
1491                // transfer and can never be part of a CUDA graph capture —
1492                // keep rejecting those. (`gpu_id` is not cross-checked
1493                // against the capture device, matching the `Kernel` arm's
1494                // `target_backend` check just above: today's decode graphs
1495                // are single-GPU only.)
1496                WorkItemKind::Copy { target_location } => {
1497                    if !matches!(target_location, DeviceLocation::Cuda { .. }) {
1498                        return Err(Error::Msg(format!(
1499                            "capture_decode: graph has a cross-device Op::Copy at \
1500                             node {:?} (target {:?}); capture requires a \
1501                             single-device CUDA decode step — only same-device \
1502                             CUDA→CUDA copies are capture-safe.",
1503                            item.node_id, target_location,
1504                        ))
1505                        .bt());
1506                    }
1507                }
1508                WorkItemKind::Kernel => {
1509                    if item.target_backend != BackendId::Cuda {
1510                        return Err(Error::Msg(format!(
1511                            "capture_decode: kernel node {:?} targets {:?}, not Cuda",
1512                            item.node_id, item.target_backend,
1513                        ))
1514                        .bt());
1515                    }
1516                    let compiled = item.compiled.as_ref().ok_or_else(|| {
1517                        Error::Msg(format!(
1518                            "capture_decode: kernel node {:?} has no compiled op",
1519                            item.node_id,
1520                        ))
1521                        .bt()
1522                    })?;
1523                    let op = compiled.op;
1524                    if !op_kind_is_capture_writeinto(op) {
1525                        return Err(Error::Msg(format!(
1526                            "capture_decode: op {:?} (node {:?}) has no write-into CUDA \
1527                             wrapper yet — capture unsupported for this op. Extend \
1528                             op_kind_is_capture_writeinto once its write-into variant lands.",
1529                            op, item.node_id,
1530                        ))
1531                        .bt());
1532                    }
1533                    // Concat's capture-safety is conditional on arity — N==2
1534                    // has a write-into path (concat2_into), N>2 does not (its
1535                    // wrapper falls back to an allocating N-1 chain). This
1536                    // can't be expressed by op_kind_is_capture_writeinto (a
1537                    // pure OpKind -> bool predicate with no OpParams access),
1538                    // so reject N>2 explicitly here, BEFORE the warm pass —
1539                    // see op_kind_is_capture_writeinto's doc comment.
1540                    if op == OpKind::Concat {
1541                        if let OpParams::Concat {
1542                            input_dim_sizes, ..
1543                        } = &compiled.op_params
1544                        {
1545                            if input_dim_sizes.len() != 2 {
1546                                return Err(Error::Msg(format!(
1547                                    "capture_decode: Concat node {:?} has {} inputs; only \
1548                                     2-input concat (the rope rotate-half shape) has a \
1549                                     write-into CUDA path today — N-ary (N>2) concat would \
1550                                     allocate mid-capture.",
1551                                    item.node_id,
1552                                    input_dim_sizes.len(),
1553                                ))
1554                                .bt());
1555                            }
1556                        }
1557                    }
1558                }
1559                // View / adopt / slot kinds: no alloc, no launch — capture-safe.
1560                _ => {}
1561            }
1562        }
1563
1564        // ---- Pass 1: warm (record) — fixed buffers + a synchronized result --
1565        let mut persistent = PersistentOutputs::recording();
1566        let mut warm_cache: StorageCache = inputs.clone();
1567        let mut warm_layouts = seed_layouts.clone();
1568        let mut warm_syms = SymEnv::new();
1569        let mut warm_devices = cuda_registry_of_inputs(&warm_cache);
1570        let mut index_reads = IndexReads::default();
1571        for item in &items {
1572            let _handle = execute_work_item(
1573                item,
1574                &mut warm_cache,
1575                &mut warm_devices,
1576                &mut warm_layouts,
1577                &mut warm_syms,
1578                false,
1579                Some(&mut persistent),
1580                Some(&mut index_reads),
1581            )
1582            .map_err(|e| with_node_location(&graph, item.node_id, e))?;
1583        }
1584        // Flush all warm launches before capture (device idle; result stable).
1585        sync_active_cuda_devices(&warm_cache)?;
1586        index_reads.check()?;
1587
1588        let output = warm_cache.get(&target).cloned().ok_or_else(|| {
1589            Error::Msg(format!(
1590                "capture_decode: target {:?} not realized in warm run",
1591                target,
1592            ))
1593            .bt()
1594        })?;
1595        let output_layout = warm_layouts.get(&target).cloned().ok_or_else(|| {
1596            Error::Msg(format!("capture_decode: target {:?} has no layout", target)).bt()
1597        })?;
1598
1599        // Derive the CUDA device from the target's storage for capture_run.
1600        let device = {
1601            let guard = output.read().map_err(|_| poisoned("output storage"))?;
1602            match &guard.inner {
1603                BackendStorage::Cuda(c) => c.device().clone(),
1604                other => {
1605                    return Err(Error::Msg(format!(
1606                        "capture_decode: target {:?} is BackendStorage::{:?}, not Cuda",
1607                        target,
1608                        other.backend_id(),
1609                    ))
1610                    .bt());
1611                }
1612            }
1613        };
1614
1615        // ---- Pass 2: capture (reuse) — record the launch sequence ----------
1616        let mut reuse = PersistentOutputs::reuse(persistent.into_map());
1617        // Retain EVERY input buffer before `inputs` is consumed: the captured
1618        // graph bakes their device addresses, so they must outlive it even if
1619        // the caller doesn't independently hold them.
1620        let retained_inputs: Vec<Arc<RwLock<Storage>>> = inputs.values().cloned().collect();
1621        let mut cap_cache: StorageCache = inputs;
1622        let mut cap_layouts = seed_layouts;
1623        let mut cap_syms = SymEnv::new();
1624        let mut cap_devices = cuda_registry_of_inputs(&cap_cache);
1625        let mut inner_err: Option<Error> = None;
1626        let items_ref = &items;
1627        let graph_ref = &graph;
1628        let run = device.capture_run(|_stream| {
1629            // Inside the capture scope: NO device alloc, NO host sync. Each
1630            // kernel launches on device.stream() (now capturing) and writes
1631            // into its reused fixed buffer.
1632            for item in items_ref {
1633                match execute_work_item(
1634                    item,
1635                    &mut cap_cache,
1636                    &mut cap_devices,
1637                    &mut cap_layouts,
1638                    &mut cap_syms,
1639                    false,
1640                    Some(&mut reuse),
1641                    // A captured replay cannot sync, so its reads are not checked (GAP-415).
1642                    None,
1643                ) {
1644                    Ok(_handle) => {}
1645                    Err(e) => {
1646                        inner_err = Some(with_node_location(graph_ref, item.node_id, e));
1647                        break;
1648                    }
1649                }
1650            }
1651            Ok(())
1652        })?;
1653        if let Some(e) = inner_err {
1654            return Err(e);
1655        }
1656
1657        Ok(CapturedDecode {
1658            run,
1659            output,
1660            output_layout,
1661            retained_inputs,
1662            persistent: reuse.into_map(),
1663        })
1664    }
1665
1666    fn realize_inner(
1667        graph: Arc<RwLock<Graph>>,
1668        target: NodeId,
1669        inputs: StorageCache,
1670        order_source: OrderSource<'_>,
1671        sym_env: SymEnv,
1672    ) -> Result<(Arc<RwLock<Storage>>, Layout, SymEnv)> {
1673        Self::realize_inner_with(
1674            graph,
1675            target,
1676            inputs,
1677            order_source,
1678            sym_env,
1679            DeviceRegistry::new(),
1680        )
1681    }
1682
1683    /// [`Self::realize_inner`] with the device handles the caller already holds.
1684    fn realize_inner_with(
1685        graph: Arc<RwLock<Graph>>,
1686        target: NodeId,
1687        inputs: StorageCache,
1688        order_source: OrderSource<'_>,
1689        sym_env: SymEnv,
1690        device_handles: DeviceRegistry,
1691    ) -> Result<(Arc<RwLock<Storage>>, Layout, SymEnv)> {
1692        // Auto-insert safety copies for in-place ops whose target
1693        // has additional readers in this realize set (residual-
1694        // connection cycle break). No-op when no destructive ops
1695        // are present.
1696        {
1697            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.safety_copies");
1698            let mut g = graph.write().map_err(|_| poisoned("graph lock"))?;
1699            let effective_roots = extend_with_side_effect_roots(&g, &[target]);
1700            insert_safety_copies(&mut g, &effective_roots);
1701        }
1702
1703        // Execution plan + initial layouts for the input cache
1704        // entries, computed on the calling thread to keep the
1705        // compiler thread free of graph-locking responsibilities.
1706        // Side-effect roots (Op::Print, Op::Save, etc.) are merged
1707        // into the walk so their effects fire even when not
1708        // reachable from the user's `target`. `execution_plan`
1709        // integrates `derive_ordering`'s view-aware pinning so
1710        // destructive ops run AFTER non-destructive readers of
1711        // their targets.
1712        let (compiler_work, wait_set, mut layout_cache): (
1713            CompilerWork,
1714            WaitSet,
1715            HashMap<NodeId, Layout>,
1716        ) = {
1717            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.plan_order");
1718            let g = graph.read().map_err(|_| poisoned("graph lock"))?;
1719            let effective_roots = extend_with_side_effect_roots(&g, &[target]);
1720            // PR-A3b-1: the OptimizedGraph path lowers via
1721            // `extract_runs`/`lower_run` (computed here, AFTER
1722            // `insert_safety_copies`, so the order covers freshly
1723            // inserted safety-copy nodes). The default path keeps the
1724            // pre-A3b-1 `execution_plan` walk. On a branchless graph the
1725            // two sequences are identical (A3a equivalence gate).
1726            //
1727            // PR-C1: a `Streaming` source is NOT flattened here — it is
1728            // handed to the compiler thread as a `CompilerWork::Streaming`
1729            // spec so the thread resolves each branch lazily at the
1730            // frontier (see `compiler_thread_body`).
1731            //
1732            // Step E A4b open question #4: the SAME pass also derives the
1733            // `WaitSet` from the materialized order ("event only where
1734            // waited" — see `compiler_work_and_wait_set_for`).
1735            let (work, wait_set) =
1736                compiler_work_and_wait_set_for(&g, &effective_roots, &order_source);
1737            let mut layouts = HashMap::with_capacity(inputs.len());
1738            for &id in inputs.keys() {
1739                layouts.insert(id, g.layout(id));
1740            }
1741            (work, wait_set, layouts)
1742        };
1743
1744        let (tx, rx) = channel::<Result<WorkItem>>();
1745        let graph_for_compiler = Arc::clone(&graph);
1746
1747        // Compiler thread: read graph nodes, resolve kernels,
1748        // push WorkItems. On error, push the error and bail. PR-C1: for a
1749        // `Streaming` work spec the thread also resolves each branch's arm
1750        // at the frontier (the SAME VRAM-only selector the one-shot picker
1751        // uses) before compiling that arm's runs.
1752        let compiler = {
1753            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.spawn_compiler");
1754            thread::spawn(move || {
1755                let _t = crate::compiled::op_profile::PhaseTimer::start(
1756                    "compiler_thread (runs concurrently)",
1757                );
1758                compiler_thread_body(graph_for_compiler, compiler_work, sym_env, tx);
1759            })
1760        };
1761
1762        // Executor on this thread: consume WorkItems, gather
1763        // inputs from the cache, allocate outputs, call kernels,
1764        // populate the cache. After each destructive op
1765        // (Op::Release / Op::Move) evict the destroyed input from
1766        // the cache, unless it's the realize target.
1767        //
1768        // Phase 4.3: at each dispatch-chunk boundary (target_backend
1769        // change), check the live SystemTopology generation against
1770        // the plan's stamped generation. Mismatch surfaces
1771        // `Error::TopologyChanged`; the realize layer
1772        // (`pipelined_bridge`) catches it, rebuilds the plan against
1773        // the fresh topology, and retries.
1774        let plan_generation: Option<u64> = generation_for(&order_source);
1775        let mut current_chunk_backend: Option<BackendId> = None;
1776        let mut cache: StorageCache = inputs;
1777        let mut devices = device_handles;
1778        // Data-dependent dynamic-shapes: symbols BOUND BY PRODUCERS during
1779        // this pass (e.g. `Op::NonZeroIndices`'s runtime count). Distinct
1780        // from the compile-time `sym_env` (input-determined, moved into the
1781        // compiler thread): these become known only as ops execute. Returned
1782        // to the caller so a downstream pass can consume them.
1783        let mut produced_syms = SymEnv::new();
1784        // Step E A4b-1: per-node async-completion handles. Each producing node's
1785        // `execute_compiled` returns a `CompletionHandle` (CUDA → a recorded
1786        // `Event`; CPU/Vulkan → `Ready`) instead of being `wait`ed inline. We
1787        // store them here, wait the SOURCE producer's handle before a
1788        // cross-device copy (A4b-3, below), and drain whatever remains at
1789        // realize-end.
1790        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
1791        // Step E A4b-4: eagerly-submitted-but-not-yet-waited Vulkan batches. The
1792        // OVERLAP enabler — when we LEAVE a Vulkan chunk (or are about to block on
1793        // a CUDA copy) we `submit_pending` the open Vulkan batch so the iGPU runs
1794        // it while the executor records/dispatches the next (CUDA) chunk, instead
1795        // of letting it sit merely-recorded until realize-end (the A4b-2 behavior,
1796        // which never overlapped). Each submitted batch is tracked here and waited
1797        // at the in-flight-lifetime guard (before a Vulkan read / Vulkan-referenced
1798        // eviction / realize-end). `multi_backend` gates ALL eager submits so a
1799        // single-device realize never touches this path (byte-identical to A4b-2).
1800        let mut inflight_vulkan: Vec<InflightVulkan> = Vec::new();
1801        // ROADMAP row 158: the backlog this realize adds to the device queues; its `Drop` takes it back out on
1802        // the Ok path and when an error unwinds the walk.
1803        let mut backlog = crate::dispatch::BacklogLedger::new();
1804        // GAP-415: out-of-range CUDA index reads, checked before any result leaves this run.
1805        let mut index_reads = IndexReads::default();
1806        // Step E A4b-4: set true the first time the dispatch order transitions
1807        // between two DIFFERENT non-CPU... actually any two distinct backends — a
1808        // genuine backend switch. On a pure-CUDA or pure-Vulkan graph there is no
1809        // switch, so this stays false and the eager-submit / in-flight machinery is
1810        // unreachable (single-device byte-identical + throughput-neutral, §5).
1811        let mut multi_backend = false;
1812        let loop_total = crate::compiled::op_profile::PhaseTimer::start("realize.loop_total");
1813        loop {
1814            let t_wait =
1815                crate::compiled::op_profile::PhaseTimer::start("realize.wait_for_compiler");
1816            let Ok(item) = rx.recv() else {
1817                break;
1818            };
1819            drop(t_wait);
1820            let item = item?;
1821            // Chunk-boundary hook (target_backend change). Existing duty: the
1822            // `TopologyChanged` generation check. Step E A4b-4 adds two duties:
1823            // (1) detect a genuine backend switch → arm `multi_backend`; (2) when
1824            // LEAVING a Vulkan chunk on a multi-backend graph, eager-submit the
1825            // open Vulkan batch so the iGPU starts it concurrently with the chunk
1826            // we are about to dispatch (the overlap win).
1827            if !is_backend_neutral(&item.kind) && current_chunk_backend != Some(item.target_backend)
1828            {
1829                if let Some(plan_gen) = plan_generation {
1830                    let live = crate::dispatch::topology_generation();
1831                    if live != plan_gen {
1832                        return Err(Error::TopologyChanged {
1833                            plan_generation: plan_gen,
1834                            current_generation: live,
1835                        }
1836                        .bt());
1837                    }
1838                }
1839                let leaving = current_chunk_backend;
1840                if let Some(prev) = leaving
1841                    && prev != item.target_backend
1842                {
1843                    // A real backend switch occurred — this realize is
1844                    // genuinely multi-backend.
1845                    multi_backend = true;
1846                    // Leaving a Vulkan chunk → submit it NOW so it runs on the
1847                    // iGPU while we record/dispatch the next chunk. Whole-chunk
1848                    // granularity (the open batch IS the just-finished Vulkan
1849                    // chunk with all its intra-CB barriers) — UAF/race-safe per
1850                    // `eager_submit_all_vulkan`'s contract.
1851                    if prev == BackendId::Vulkan {
1852                        {
1853                            let _pt = crate::compiled::op_profile::PhaseTimer::start(
1854                                "realize.eager_submit_vulkan",
1855                            );
1856                            eager_submit_all_vulkan(&cache, &mut inflight_vulkan)?;
1857                        }
1858                    }
1859                }
1860                current_chunk_backend = Some(item.target_backend);
1861            }
1862            // Vulkan realizes run the async path (deferred eviction, size-based eager
1863            // submit) even on a single device: ordering between batches is structural
1864            // (inter-batch barrier + epoch-gated buffer reuse), not a host wait.
1865            if item.target_backend == BackendId::Vulkan && matches!(item.kind, WorkItemKind::Kernel)
1866            {
1867                multi_backend = true;
1868            }
1869            // Same-device cross-chunk RAW/WAR safety between Vulkan batches (the old
1870            // "Invariant E": wait every in-flight Vulkan batch on the HOST before
1871            // recording a new Vulkan op) is now structural: the Vulkan recorder
1872            // starts every batch with a memory barrier whose first scope covers all
1873            // earlier submissions on the queue (`Recorder::record_inter_batch_barrier`),
1874            // so a later batch cannot read or overwrite what an earlier in-flight
1875            // one is still using. The host therefore keeps recording while the
1876            // GPU runs the batches already submitted; waits remain only where the
1877            // host needs a result (D2H reads), before freeing a buffer, and at
1878            // realize-end.
1879            // Step E A4b-3 + A4b-4: the cross-device residency boundary.
1880            if matches!(
1881                item.kind,
1882                WorkItemKind::Copy { .. } | WorkItemKind::Move { .. }
1883            ) {
1884                // A4b-4: before we (possibly) block the host on the CUDA producer,
1885                // eager-submit any open Vulkan chunk so the iGPU runs it WHILE we
1886                // wait on CUDA (the §5.1 ordering — submit Vulkan *before* draining
1887                // CUDA). Cheap + safe; gated to multi-backend (no-op single-device).
1888                if multi_backend {
1889                    {
1890                        let _pt = crate::compiled::op_profile::PhaseTimer::start(
1891                            "realize.eager_submit_vulkan",
1892                        );
1893                        eager_submit_all_vulkan(&cache, &mut inflight_vulkan)?;
1894                    }
1895                }
1896                if let Some(&producer) = item.inputs.first() {
1897                    // A4b-4: a VULKAN-source D2H must read COMPLETED data, and the
1898                    // Vulkan download path only flushes the OPEN batch (not our
1899                    // in-flight ones) — so wait the in-flight Vulkan batches here.
1900                    // For a CUDA/CPU source we do NOT wait Vulkan (the copy reads no
1901                    // Vulkan buffer); waiting it would needlessly serialize the
1902                    // independent Vulkan sub-DAG and kill the overlap. The Vulkan
1903                    // work that was eager-submitted at the chunk boundary keeps
1904                    // running concurrently until ITS result is the one being copied.
1905                    if multi_backend && copy_source_is_vulkan(&cache, producer)? {
1906                        {
1907                            let _pt = crate::compiled::op_profile::PhaseTimer::start(
1908                                "realize.drain_inflight_vulkan",
1909                            );
1910                            drain_inflight_vulkan(&mut inflight_vulkan)?;
1911                        }
1912                    }
1913                    // Step E A4b-3: FINER CUDA source-drain — wait ONLY the source
1914                    // producer's recorded event (not the whole source device), so
1915                    // the OTHER sub-DAG's independent in-flight CUDA work keeps
1916                    // running. No-op for a Vulkan/CPU producer (no CUDA handle).
1917                    wait_producer_handle(&mut handles, producer)?;
1918                    index_reads.check()?;
1919                }
1920            }
1921            let t_exec =
1922                crate::compiled::op_profile::PhaseTimer::start(work_item_kind_name(&item.kind));
1923            let handle = execute_work_item(
1924                &item,
1925                &mut cache,
1926                &mut devices,
1927                &mut layout_cache,
1928                &mut produced_syms,
1929                will_be_waited(&wait_set, item.node_id),
1930                // No persistent-output mode on the standard realize paths —
1931                // fresh alloc per node, byte-identical to pre-CapturedRun.
1932                None,
1933                Some(&mut index_reads),
1934            )
1935            .map_err(|e| with_node_location(&graph, item.node_id, e))?;
1936            drop(t_exec);
1937            store_handle(&mut handles, item.node_id, handle);
1938            feed_backlog(&mut backlog, &cache, &item);
1939            if let Some(d_idx) = item.destructive_input
1940                && let Some(&destroyed) = item.inputs.get(d_idx)
1941                && destroyed != target
1942            {
1943                // Step E A2.1 (in-flight-batch DATA-BUFFER lifetime — the
1944                // UAF guard, now DEFERRED-DELETION instead of a drain). A
1945                // `SubmittedBatch` owns its CB/descriptors/transients but
1946                // NOT the DATA buffers it reads (those live here in the
1947                // cache); recycling a data buffer an in-flight/open CB still
1948                // reads is a use-after-free. PRE-A2.1 we host-blocked here —
1949                // `drain_inflight_vulkan` (wait every in-flight batch) +
1950                // `force_flush` (submit+wait the open batch) — which stalled
1951                // the iGPU work we were overlapping with CUDA at EVERY such
1952                // eviction. A2.1 instead RETAINS the evicted buffer until the
1953                // reader fences signal: it eager-submits the open batch (no
1954                // wait → it becomes a fenced in-flight batch) and moves a
1955                // refcount clone of the buffer into every in-flight batch, so
1956                // the buffer frees POST-fence on each batch's `Drop`
1957                // (follow-on #2) with NO host block. Conservative over all
1958                // batches (no cheap buffer→batch map — the same reason the old
1959                // drain waited all of them). CUDA eviction is stream-ordered-
1960                // safe via A3. Single-device (multi_backend == false) keeps the
1961                // pre-A2.1 blocking force_flush of the OPEN batch (the else
1962                // branch) — byte-identical + UAF-safe there; the deferred path is
1963                // unsafe single-device (no eager-submit/in-flight tracking, and the
1964                // cross-batch RAW guard at :832 doesn't run — see
1965                // force_flush_vulkan's doc).
1966                let _t =
1967                    crate::compiled::op_profile::PhaseTimer::start("realize.evict_destroyed_input");
1968                if multi_backend {
1969                    defer_evicted_vulkan_buffer(&cache, destroyed, &mut inflight_vulkan)?;
1970                } else if let Some(d_arc) = cache.get(&destroyed) {
1971                    let _f = crate::compiled::op_profile::PhaseTimer::start(
1972                        "realize.evict_force_flush_vulkan",
1973                    );
1974                    force_flush_vulkan(d_arc)?;
1975                }
1976                cache.remove(&destroyed);
1977                layout_cache.remove(&destroyed);
1978                // Drop the evicted node's CUDA handle (if still present)
1979                // so the realize-end drain's empty-map assert stays
1980                // meaningful. The free itself is stream-ordered-safe (A3).
1981                handles.remove(&destroyed);
1982            }
1983        }
1984
1985        drop(loop_total);
1986        {
1987            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.join_compiler");
1988            compiler
1989                .join()
1990                .map_err(|_| Error::Msg("compiler thread panicked".to_string()).bt())?;
1991        }
1992
1993        // Step E A4b-1: drain every outstanding async handle before the result is
1994        // read / the cache drops (freeing intermediates). For CUDA this waits the
1995        // recorded events (one stream/device ⇒ waiting the latest drains all prior
1996        // stream work too; see `drain_handles`).
1997        let post_loop = crate::compiled::op_profile::PhaseTimer::start("realize.post_loop_drains");
1998        drain_handles(&mut handles)?;
1999        // Step E A4b open question #4 — "event only where waited": most CUDA
2000        // nodes in this realize never got an Event (elided per the `WaitSet`),
2001        // so `drain_handles` above only retired the (typically few) tracked
2002        // handles. This blanket per-device `cuStreamSynchronize` flushes the
2003        // elided work too — safe + sufficient because of single-stream-per-
2004        // device ordering (see `sync_active_cuda_devices`'s doc).
2005        sync_active_cuda_devices(&cache)?;
2006        index_reads.check()?;
2007        // Step E A4b-4: wait every eagerly-submitted (in-flight) Vulkan batch
2008        // before the cache drops, freeing the data buffers their CBs read. Empty
2009        // on a single-device realize (nothing was eager-submitted).
2010        {
2011            let _pt =
2012                crate::compiled::op_profile::PhaseTimer::start("realize.drain_inflight_vulkan");
2013            drain_inflight_vulkan(&mut inflight_vulkan)?;
2014        }
2015        // Step E A4b-2: drain all deferred Vulkan work before reading/returning
2016        // the result (and before the cache drops, freeing buffers). The A2
2017        // submit+wait is now SPLIT — `drain_vulkan_pending` submits the open
2018        // batch then waits it via a `VulkanCompletion` handle. Byte-identical to
2019        // A2 for pure-Vulkan (one submission at realize-end, just split).
2020        drain_vulkan_pending(&cache)?;
2021        debug_assert!(
2022            inflight_vulkan.is_empty(),
2023            "A4b-4: in-flight Vulkan batch list must be empty after realize-end drain",
2024        );
2025
2026        drop(post_loop);
2027        let storage = cache.remove(&target).ok_or_else(|| {
2028            Error::Msg(format!(
2029                "PipelinedExecutor::realize: target slot {:?} not populated after execution",
2030                target
2031            ))
2032            .bt()
2033        })?;
2034        let layout = layout_cache.remove(&target).ok_or_else(|| {
2035            Error::Msg(format!(
2036                "PipelinedExecutor::realize: target layout {:?} not populated after execution",
2037                target
2038            ))
2039            .bt()
2040        })?;
2041        {
2042            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.drop_cache");
2043            drop(cache);
2044            drop(handles);
2045            drop(layout_cache);
2046        }
2047        Ok((storage, layout, produced_syms))
2048    }
2049
2050    /// Realize multiple targets in one walk. Each target's transitive
2051    /// dependency set is collapsed into a single execution plan
2052    /// (via [`execution_plan`]); shared subgraphs are evaluated
2053    /// once. Returns a `Vec<(Storage, Layout)>` whose order matches
2054    /// `targets`.
2055    ///
2056    /// This is Phase A of Phase 7.6 step 9c — feature-parity with the
2057    /// legacy `GraphExecutor::realize_many_f32`. Multi-session
2058    /// migration target ([memory: project_phase_7_6_step_9c_parity_audit.md]).
2059    ///
2060    /// Pre-conditions: every reachable `Op::Const` must be in
2061    /// `inputs`; every reachable non-`Const` must have its
2062    /// `target_backend` set; the op + dtype must be registered in
2063    /// `global_bindings()`. Same as single-target [`Self::realize`].
2064    pub fn realize_many(
2065        graph: Arc<RwLock<Graph>>,
2066        targets: &[NodeId],
2067        inputs: StorageCache,
2068    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2069        Self::realize_many_inner(
2070            graph,
2071            targets,
2072            inputs,
2073            OrderSource::Default,
2074            SymEnv::default(),
2075        )
2076    }
2077
2078    /// [`Self::realize_many`] with the device handles the caller already holds (ROADMAP row 137, seam S3
2079    /// step 3b).
2080    pub fn realize_many_with_devices(
2081        graph: Arc<RwLock<Graph>>,
2082        targets: &[NodeId],
2083        inputs: StorageCache,
2084        devices: DeviceRegistry,
2085    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2086        Self::realize_many_inner_with(
2087            graph,
2088            targets,
2089            inputs,
2090            OrderSource::Default,
2091            SymEnv::default(),
2092            devices,
2093        )
2094    }
2095
2096    /// [`Self::realize_many_with_optimized_picking_env`] with the device handles the caller already holds.
2097    #[allow(clippy::too_many_arguments)]
2098    pub fn realize_many_with_optimized_picking_env_with_devices(
2099        graph: Arc<RwLock<Graph>>,
2100        targets: &[NodeId],
2101        inputs: StorageCache,
2102        optimized: &OptimizedGraph,
2103        selector: Option<Arc<dyn RuntimeSelector>>,
2104        lookup: Option<BackendRuntimeLookup>,
2105        sym_env: SymEnv,
2106        devices: DeviceRegistry,
2107    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2108        let order_source = match Self::streaming_pick_for(&graph, selector, lookup)? {
2109            Some(pick) => {
2110                return Self::realize_many_inner_with(
2111                    graph,
2112                    targets,
2113                    inputs,
2114                    OrderSource::Streaming {
2115                        optimized,
2116                        pick: &pick,
2117                    },
2118                    sym_env,
2119                    devices,
2120                );
2121            }
2122            None => OrderSource::Optimized {
2123                optimized,
2124                route: None,
2125            },
2126        };
2127        Self::realize_many_inner_with(graph, targets, inputs, order_source, sym_env, devices)
2128    }
2129
2130    /// Multi-target PR-A3b-1 entry — the `realize_many` sibling of
2131    /// [`Self::realize_with_optimized`]. Drives the executor from the
2132    /// `OptimizedGraph`'s run lowering via the binding-table-lookup
2133    /// path, with the optimize-time `generation` keying the
2134    /// `TopologyChanged` chunk-boundary check.
2135    pub fn realize_many_with_optimized(
2136        graph: Arc<RwLock<Graph>>,
2137        targets: &[NodeId],
2138        inputs: StorageCache,
2139        optimized: &OptimizedGraph,
2140    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2141        Self::realize_many_inner(
2142            graph,
2143            targets,
2144            inputs,
2145            OrderSource::Optimized {
2146                optimized,
2147                route: None,
2148            },
2149            SymEnv::default(),
2150        )
2151    }
2152
2153    /// Env-carrying sibling of [`Self::realize_many_with_optimized`] (Phase D
2154    /// symbolic extents). An empty env is byte-identical to it.
2155    pub fn realize_many_with_optimized_env(
2156        graph: Arc<RwLock<Graph>>,
2157        targets: &[NodeId],
2158        inputs: StorageCache,
2159        optimized: &OptimizedGraph,
2160        sym_env: SymEnv,
2161    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2162        Self::realize_many_inner(
2163            graph,
2164            targets,
2165            inputs,
2166            OrderSource::Optimized {
2167                optimized,
2168                route: None,
2169            },
2170            sym_env,
2171        )
2172    }
2173
2174    /// Multi-target PR-C1 entry — the `realize_many` sibling of
2175    /// [`Self::realize_with_optimized_route`]. Lowers each target's runs
2176    /// following the picker's chosen arms via
2177    /// [`fuel_graph::lower_picked_route`].
2178    pub fn realize_many_with_optimized_route(
2179        graph: Arc<RwLock<Graph>>,
2180        targets: &[NodeId],
2181        inputs: StorageCache,
2182        optimized: &OptimizedGraph,
2183        route: &PickedRoute,
2184    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2185        Self::realize_many_inner(
2186            graph,
2187            targets,
2188            inputs,
2189            OrderSource::Optimized {
2190                optimized,
2191                route: Some(route),
2192            },
2193            SymEnv::default(),
2194        )
2195    }
2196
2197    /// Env-carrying sibling of [`Self::realize_many_with_optimized_route`]
2198    /// (Phase D symbolic extents). An empty env is byte-identical to it.
2199    pub fn realize_many_with_optimized_route_env(
2200        graph: Arc<RwLock<Graph>>,
2201        targets: &[NodeId],
2202        inputs: StorageCache,
2203        optimized: &OptimizedGraph,
2204        route: &PickedRoute,
2205        sym_env: SymEnv,
2206    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2207        Self::realize_many_inner(
2208            graph,
2209            targets,
2210            inputs,
2211            OrderSource::Optimized {
2212                optimized,
2213                route: Some(route),
2214            },
2215            sym_env,
2216        )
2217    }
2218
2219    /// Multi-target sibling of [`Self::realize_with_optimized_picking_env`] —
2220    /// the executor resolves one arm per `Op::Branch` (cleanup Step C/D) over
2221    /// the effective targets. PR C1: a branched graph routes to the
2222    /// `OrderSource::Streaming` walk (lazy per-branch resolution at the
2223    /// frontier); branchless / no-selector falls to the untouched arm-0 path.
2224    pub fn realize_many_with_optimized_picking_env(
2225        graph: Arc<RwLock<Graph>>,
2226        targets: &[NodeId],
2227        inputs: StorageCache,
2228        optimized: &OptimizedGraph,
2229        selector: Option<Arc<dyn RuntimeSelector>>,
2230        lookup: Option<BackendRuntimeLookup>,
2231        sym_env: SymEnv,
2232    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2233        match Self::streaming_pick_for(&graph, selector, lookup)? {
2234            Some(pick) => Self::realize_many_inner(
2235                graph,
2236                targets,
2237                inputs,
2238                OrderSource::Streaming {
2239                    optimized,
2240                    pick: &pick,
2241                },
2242                sym_env,
2243            ),
2244            None => {
2245                Self::realize_many_with_optimized_env(graph, targets, inputs, optimized, sym_env)
2246            }
2247        }
2248    }
2249
2250    fn realize_many_inner(
2251        graph: Arc<RwLock<Graph>>,
2252        targets: &[NodeId],
2253        inputs: StorageCache,
2254        order_source: OrderSource<'_>,
2255        sym_env: SymEnv,
2256    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2257        Self::realize_many_inner_with(
2258            graph,
2259            targets,
2260            inputs,
2261            order_source,
2262            sym_env,
2263            DeviceRegistry::new(),
2264        )
2265    }
2266
2267    /// [`Self::realize_many_inner`] with the device handles the caller already holds.
2268    fn realize_many_inner_with(
2269        graph: Arc<RwLock<Graph>>,
2270        targets: &[NodeId],
2271        inputs: StorageCache,
2272        order_source: OrderSource<'_>,
2273        sym_env: SymEnv,
2274        device_handles: DeviceRegistry,
2275    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2276        if targets.is_empty() {
2277            return Ok(Vec::new());
2278        }
2279
2280        // Auto-insert safety copies for in-place ops whose target
2281        // has additional readers in this realize set (residual-
2282        // connection cycle break). No-op when no destructive ops
2283        // are present.
2284        {
2285            let mut g = graph.write().map_err(|_| poisoned("graph lock"))?;
2286            let effective_roots = extend_with_side_effect_roots(&g, targets);
2287            insert_safety_copies(&mut g, &effective_roots);
2288        }
2289
2290        // Execution plan covering every target's dependency set +
2291        // initial layouts for the input cache entries. Side-effect
2292        // roots merge in so their effects fire even when not
2293        // reachable from any target. `execution_plan` integrates
2294        // `derive_ordering`'s view-aware pinning so destructive ops
2295        // run AFTER non-destructive readers of their targets.
2296        let (compiler_work, wait_set, mut layout_cache): (
2297            CompilerWork,
2298            WaitSet,
2299            HashMap<NodeId, Layout>,
2300        ) = {
2301            let g = graph.read().map_err(|_| poisoned("graph lock"))?;
2302            let effective_roots = extend_with_side_effect_roots(&g, targets);
2303            // PR-A3b-1: derive from the OptimizedGraph's run lowering
2304            // when present (post-safety-copies); else the legacy
2305            // `execution_plan` walk. Identical on branchless graphs.
2306            //
2307            // PR-C1: a `Streaming` source is handed to the compiler thread
2308            // unflattened (resolves branches at the frontier).
2309            //
2310            // Step E A4b open question #4: also derives the `WaitSet`
2311            // ("event only where waited") from the same materialized order.
2312            let (work, wait_set) =
2313                compiler_work_and_wait_set_for(&g, &effective_roots, &order_source);
2314            let mut layouts = HashMap::with_capacity(inputs.len());
2315            for &id in inputs.keys() {
2316                layouts.insert(id, g.layout(id));
2317            }
2318            (work, wait_set, layouts)
2319        };
2320
2321        // Caller's target set — used to gate destructive-input
2322        // eviction so we don't drop a tensor the caller asked for.
2323        let target_set: std::collections::HashSet<NodeId> = targets.iter().copied().collect();
2324
2325        let (tx, rx) = channel::<Result<WorkItem>>();
2326        let graph_for_compiler = Arc::clone(&graph);
2327
2328        let compiler = thread::spawn(move || {
2329            compiler_thread_body(graph_for_compiler, compiler_work, sym_env, tx);
2330        });
2331
2332        // Phase 4.3: per-chunk SystemTopology generation check (see
2333        // realize_inner for the rationale). PR-A3b-1: the OptimizedGraph
2334        // path supplies its own optimize-time generation.
2335        let plan_generation: Option<u64> = generation_for(&order_source);
2336        let mut current_chunk_backend: Option<BackendId> = None;
2337        let mut cache: StorageCache = inputs;
2338        let mut devices = device_handles;
2339        // Data-dependent dynamic-shapes producer-bound symbols (see
2340        // `realize_inner`). `realize_many` does not expose them today; the
2341        // env is dropped at pass end (producers still publish, keeping the
2342        // seam uniform across both realize loops).
2343        let mut produced_syms = SymEnv::new();
2344        // Step E A4b-1/A4b-3: per-node async-completion handles (see realize_inner
2345        // for the full rationale). Map drained at realize-end; the cross-device
2346        // copy waits the SOURCE producer's handle (A4b-3).
2347        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
2348        // Step E A4b-4: eagerly-submitted in-flight Vulkan batches + the
2349        // multi-backend gate. See realize_inner for the full rationale — this is
2350        // the identical eager-submit / in-flight-lifetime machinery applied to the
2351        // multi-target walk. `multi_backend` arms on a genuine backend switch and
2352        // gates every eager submit, so a single-device realize_many is
2353        // byte-identical to A4b-2.
2354        let mut inflight_vulkan: Vec<InflightVulkan> = Vec::new();
2355        // ROADMAP row 158: the backlog this realize adds to the device queues; its `Drop` takes it back out on
2356        // the Ok path and when an error unwinds the walk.
2357        let mut backlog = crate::dispatch::BacklogLedger::new();
2358        // GAP-415: out-of-range CUDA index reads, checked before any result leaves this run.
2359        let mut index_reads = IndexReads::default();
2360        let mut multi_backend = false;
2361        for item in rx {
2362            let item = item?;
2363            // Chunk-boundary hook: TopologyChanged check + (A4b-4) backend-switch
2364            // detection + eager-submit-on-leaving-a-Vulkan-chunk.
2365            if !is_backend_neutral(&item.kind) && current_chunk_backend != Some(item.target_backend)
2366            {
2367                if let Some(plan_gen) = plan_generation {
2368                    let live = crate::dispatch::topology_generation();
2369                    if live != plan_gen {
2370                        return Err(Error::TopologyChanged {
2371                            plan_generation: plan_gen,
2372                            current_generation: live,
2373                        }
2374                        .bt());
2375                    }
2376                }
2377                let leaving = current_chunk_backend;
2378                if let Some(prev) = leaving
2379                    && prev != item.target_backend
2380                {
2381                    multi_backend = true;
2382                    if prev == BackendId::Vulkan {
2383                        eager_submit_all_vulkan(&cache, &mut inflight_vulkan)?;
2384                    }
2385                }
2386                current_chunk_backend = Some(item.target_backend);
2387            }
2388            // Vulkan realizes run the async path (deferred eviction, size-based eager
2389            // submit) even on a single device: ordering between batches is structural
2390            // (inter-batch barrier + epoch-gated buffer reuse), not a host wait.
2391            if item.target_backend == BackendId::Vulkan && matches!(item.kind, WorkItemKind::Kernel)
2392            {
2393                multi_backend = true;
2394            }
2395            // Inter-batch Vulkan ordering is structural (see realize_inner): no host
2396            // wait before recording a new Vulkan op.
2397            // Step E A4b-3 + A4b-4: cross-device residency boundary. See
2398            // realize_inner for the full rationale.
2399            if matches!(
2400                item.kind,
2401                WorkItemKind::Copy { .. } | WorkItemKind::Move { .. }
2402            ) {
2403                // A4b-4: submit any open Vulkan chunk so the iGPU runs while the
2404                // host (possibly) waits on the CUDA producer.
2405                if multi_backend {
2406                    eager_submit_all_vulkan(&cache, &mut inflight_vulkan)?;
2407                }
2408                if let Some(&producer) = item.inputs.first() {
2409                    // A4b-4: wait in-flight Vulkan ONLY for a Vulkan-source D2H
2410                    // (reads completed data; download flushes only the OPEN batch).
2411                    // A CUDA/CPU source does NOT wait Vulkan (preserves overlap).
2412                    if multi_backend && copy_source_is_vulkan(&cache, producer)? {
2413                        drain_inflight_vulkan(&mut inflight_vulkan)?;
2414                    }
2415                    // Step E A4b-3: finer CUDA source-drain — wait ONLY the producer.
2416                    wait_producer_handle(&mut handles, producer)?;
2417                    index_reads.check()?;
2418                }
2419            }
2420            let handle = execute_work_item(
2421                &item,
2422                &mut cache,
2423                &mut devices,
2424                &mut layout_cache,
2425                &mut produced_syms,
2426                will_be_waited(&wait_set, item.node_id),
2427                // No persistent-output mode on the standard realize paths —
2428                // fresh alloc per node, byte-identical to pre-CapturedRun.
2429                None,
2430                Some(&mut index_reads),
2431            )
2432            .map_err(|e| with_node_location(&graph, item.node_id, e))?;
2433            store_handle(&mut handles, item.node_id, handle);
2434            feed_backlog(&mut backlog, &cache, &item);
2435            if let Some(d_idx) = item.destructive_input
2436                && let Some(&destroyed) = item.inputs.get(d_idx)
2437                && !target_set.contains(&destroyed)
2438            {
2439                // Step E A2.1 (in-flight DATA-BUFFER lifetime — UAF guard,
2440                // now DEFERRED-DELETION instead of a drain): retain the
2441                // evicted buffer until the reader fences signal — eager-
2442                // submit the open batch (no wait) + move a refcount clone of
2443                // the buffer into every in-flight batch, freeing it post-
2444                // fence on each batch's `Drop` with NO host block. Replaces
2445                // the pre-A2.1 `drain_inflight_vulkan` + open-batch
2446                // `force_flush` (two host-blocking fence waits). See
2447                // `defer_evicted_vulkan_buffer` / realize_inner for the
2448                // UAF/leak argument. CUDA eviction is A3 stream-safe.
2449                // Single-device (multi_backend == false) keeps the pre-A2.1
2450                // blocking force_flush of the OPEN batch (the else branch) —
2451                // byte-identical + UAF-safe; the deferred path is unsafe there
2452                // (see force_flush_vulkan's doc).
2453                if multi_backend {
2454                    defer_evicted_vulkan_buffer(&cache, destroyed, &mut inflight_vulkan)?;
2455                } else if let Some(d_arc) = cache.get(&destroyed) {
2456                    force_flush_vulkan(d_arc)?;
2457                }
2458                cache.remove(&destroyed);
2459                layout_cache.remove(&destroyed);
2460                // CUDA eviction is stream-ordered-safe (A3); drop the
2461                // handle so the realize-end empty-map assert stays valid.
2462                handles.remove(&destroyed);
2463            }
2464        }
2465
2466        compiler
2467            .join()
2468            .map_err(|_| Error::Msg("compiler thread panicked".to_string()).bt())?;
2469
2470        // Step E A4b-1: drain every outstanding async handle (CUDA events) before
2471        // results are read / the cache drops.
2472        drain_handles(&mut handles)?;
2473        // Step E A4b open question #4: blanket per-device stream sync for the
2474        // elided nodes `drain_handles` never tracked — see `realize_inner`'s
2475        // identical comment / `sync_active_cuda_devices`'s doc for the argument.
2476        sync_active_cuda_devices(&cache)?;
2477        index_reads.check()?;
2478        // Step E A4b-4: wait every eagerly-submitted in-flight Vulkan batch before
2479        // the cache drops. Empty on a single-device realize.
2480        drain_inflight_vulkan(&mut inflight_vulkan)?;
2481        // Step E A4b-2: drain all deferred Vulkan work — submit the open batch
2482        // then wait it via a `VulkanCompletion` handle (the A2 submit+wait, split;
2483        // byte-identical for pure-Vulkan — one submission at realize-end).
2484        drain_vulkan_pending(&cache)?;
2485        debug_assert!(
2486            inflight_vulkan.is_empty(),
2487            "A4b-4: in-flight Vulkan batch list must be empty after realize-end drain",
2488        );
2489
2490        // Verify every target was realized + collect outputs in
2491        // target order. We don't `remove` from the cache because the
2492        // same NodeId can appear twice in `targets` (caller wants the
2493        // same storage twice) — clone the Arc instead.
2494        let mut out = Vec::with_capacity(targets.len());
2495        for &target in targets {
2496            let storage = cache.get(&target).cloned().ok_or_else(|| {
2497                Error::Msg(format!(
2498                    "PipelinedExecutor::realize_many: target {:?} not populated after execution",
2499                    target
2500                ))
2501                .bt()
2502            })?;
2503            let layout = layout_cache.get(&target).cloned().ok_or_else(|| {
2504                Error::Msg(format!(
2505                    "PipelinedExecutor::realize_many: target layout {:?} not populated after execution",
2506                    target
2507                ))
2508                .bt()
2509            })?;
2510            out.push((storage, layout));
2511        }
2512        Ok(out)
2513    }
2514}
2515
2516/// Resolve the executor's dispatch order from the configured
2517/// [`OrderSource`]. PR-A3b-1: `Optimized` lowers the in-place
2518/// "plan IS the graph" form via `extract_runs`/`lower_run`; `Default`
2519/// keeps the pre-A3b-1 `execution_plan` walk. Both produce the same
2520/// `NodeId` sequence on a branchless graph (A3a equivalence gate),
2521/// computed here AFTER safety-copy insertion so either path covers
2522/// any freshly inserted copies.
2523fn order_for(
2524    graph: &Graph,
2525    effective_roots: &[NodeId],
2526    order_source: &OrderSource<'_>,
2527) -> Vec<NodeId> {
2528    match order_source {
2529        OrderSource::Default => execution_plan(graph, effective_roots),
2530        // The streaming walk is driven in the compiler thread (it
2531        // interleaves arm resolution with compilation), so `order_for`
2532        // never flattens it on the production path. This arm exists only
2533        // for match totality / non-pipelined callers: it collects the SAME
2534        // lazily-resolved order eagerly (the streaming walk with the same
2535        // `resolve_branch` over the threaded selector), which equals the
2536        // one-shot `lower_picked_route(pick_route(..))` order.
2537        OrderSource::Streaming {
2538            optimized: _optimized,
2539            pick,
2540        } => {
2541            let bindings = global_bindings();
2542            fuel_graph::lower_picked_route_streaming(graph, effective_roots, |branch| {
2543                resolve_branch(graph, branch, &bindings, pick.selector.as_ref())
2544            })
2545        }
2546        OrderSource::Optimized { optimized, route } => {
2547            // Lower the runs over the *effective* roots (user targets +
2548            // any spliced/side-effect roots) so the order matches the
2549            // walk's reachable set rather than only the optimize-time
2550            // roots. On a branchless graph this is the same concatenated
2551            // `lower_run` sequence the OptimizedGraph reports.
2552            //
2553            // PR-C1: when the picker supplied a route, follow the chosen
2554            // arms (`lower_picked_route`); otherwise the arm-0 lowering
2555            // (`OptimizedGraph::dispatch_order`). An empty route is
2556            // byte-identical to arm-0, so the two paths agree whenever
2557            // the picker chose arm-0 everywhere (the no-pressure case).
2558            match route {
2559                Some(route) => fuel_graph::lower_picked_route(graph, effective_roots, route),
2560                None => {
2561                    // A transient view built solely to call `dispatch_order`;
2562                    // it does no planning, so it carries no placements. The
2563                    // real optimization's map lives on `optimized`.
2564                    let view = OptimizedGraph {
2565                        roots: effective_roots.to_vec(),
2566                        generation: optimized.generation,
2567                        placements: None,
2568                        eviction: None,
2569                    };
2570                    view.dispatch_order(graph)
2571                }
2572            }
2573        }
2574        // Resolved by `compiler_work_and_wait_set_for` before delegating
2575        // here (the whole point of `Cached` is to skip this computation
2576        // on a hit) — never reached. Kept exhaustive rather than wildcarded
2577        // so a future `OrderSource` variant can't silently fall through.
2578        OrderSource::Cached { .. } => {
2579            unreachable!("OrderSource::Cached is resolved before order_for is called")
2580        }
2581    }
2582}
2583
2584/// Step E A4b open question #4 — "event only where waited". The producer
2585/// [`NodeId`]s that some later `Op::Copy`/`Op::Move` node in `order` will
2586/// `wait_producer_handle` on (the executor's cross-device residency
2587/// boundary — see `wait_producer_handle`, whose `item.inputs.first()` read
2588/// this mirrors exactly). A CUDA node whose id is absent from the returned
2589/// set has NO mid-walk reader: same-device consumers are correct via stream
2590/// ordering alone (they never `wait`), and nothing touches its handle before
2591/// the realize-end drain, so [`crate::compiled::execute_compiled_with_wait_hint`]
2592/// can skip recording an `Event` for it entirely.
2593///
2594/// Requires a materialized `order` (works for [`OrderSource::Default`] /
2595/// [`OrderSource::Optimized`], whose [`CompilerWork::Order`] is a frozen
2596/// `Vec<NodeId>` computed up front) — see
2597/// [`compiler_work_and_wait_set_for`] for the [`OrderSource::Streaming`]
2598/// fallback.
2599fn build_wait_set(graph: &Graph, order: &[NodeId]) -> HashSet<NodeId> {
2600    let mut set = HashSet::new();
2601    for &id in order {
2602        let node = graph.node(id);
2603        if matches!(node.op, Op::Copy { .. } | Op::Move { .. })
2604            && let Some(&producer) = node.inputs.first()
2605        {
2606            set.insert(producer);
2607        }
2608    }
2609    set
2610}
2611
2612/// Step E A4b open question #4: the executor's per-realize wait-set.
2613/// `None` is the CONSERVATIVE fallback — every CUDA node still gets an Event
2614/// (today's pre-elision behavior, byte-identical). `Some(set)` restricts
2615/// event production to `set`'s members ([`build_wait_set`]'s output);
2616/// everything else gets `CompletionHandle::Ready` with no Event recorded.
2617type WaitSet = Option<HashSet<NodeId>>;
2618
2619/// Whether `node_id`'s completion handle must be individually observable
2620/// (i.e. `execute_compiled_with_wait_hint`'s `will_be_waited`). `None` (the
2621/// [`OrderSource::Streaming`] fallback — never elides) is always `true`.
2622#[inline]
2623fn will_be_waited(wait_set: &WaitSet, node_id: NodeId) -> bool {
2624    match wait_set {
2625        None => true,
2626        Some(set) => set.contains(&node_id),
2627    }
2628}
2629
2630/// Build the [`CompilerWork`] the compiler thread walks for the configured
2631/// [`OrderSource`], plus the [`WaitSet`] "event only where waited" (open
2632/// question #4) consults. The non-streaming sources flatten up front via
2633/// [`order_for`] (unchanged) and the SAME materialized order feeds
2634/// [`build_wait_set`], so the pre-scan and the dispatch order never
2635/// disagree. [`OrderSource::Streaming`] is handed to the compiler thread as
2636/// a [`CompilerWork::Streaming`] spec — NOT flattened here — so the thread
2637/// resolves branches lazily at the frontier (Step E Phase C, PR C1); the lazy
2638/// order can't be pre-scanned without eagerly resolving it (which would
2639/// defeat the point of streaming), so it falls back to the conservative
2640/// `WaitSet::None` — event every node, unchanged behavior. Holds the graph
2641/// read-lock only for the flattening branches; the streaming branch defers
2642/// the lock to the compiler thread.
2643fn compiler_work_and_wait_set_for(
2644    graph: &Graph,
2645    effective_roots: &[NodeId],
2646    order_source: &OrderSource<'_>,
2647) -> (CompilerWork, WaitSet) {
2648    match order_source {
2649        OrderSource::Streaming { pick, .. } => (
2650            CompilerWork::Streaming {
2651                roots: effective_roots.to_vec(),
2652                pick: (*pick).clone(),
2653            },
2654            None,
2655        ),
2656        OrderSource::Cached {
2657            optimized,
2658            order_cache,
2659        } => {
2660            let order = order_cache.get_or_init(|| {
2661                order_for(
2662                    graph,
2663                    effective_roots,
2664                    &OrderSource::Optimized {
2665                        optimized,
2666                        route: None,
2667                    },
2668                )
2669            });
2670            let wait_set = build_wait_set(graph, order);
2671            (CompilerWork::Order(order.clone()), Some(wait_set))
2672        }
2673        other => {
2674            let order = order_for(graph, effective_roots, other);
2675            let wait_set = build_wait_set(graph, &order);
2676            (CompilerWork::Order(order), Some(wait_set))
2677        }
2678    }
2679}
2680
2681/// The topology generation that keys the executor's `TopologyChanged`
2682/// chunk-boundary check. Uses the `OptimizedGraph`'s optimize-time
2683/// generation (PR-A3b-1 path). `None` ⇒ no check (the plain
2684/// `realize`/`realize_many` entries).
2685fn generation_for(order_source: &OrderSource<'_>) -> Option<u64> {
2686    match order_source {
2687        OrderSource::Optimized { optimized, .. } => Some(optimized.generation),
2688        OrderSource::Streaming { optimized, .. } => Some(optimized.generation),
2689        OrderSource::Cached { optimized, .. } => Some(optimized.generation),
2690        OrderSource::Default => None,
2691    }
2692}
2693
2694/// What the compiler thread walks: either a pre-flattened dispatch
2695/// `Order` (the `Default` / `Optimized` paths — unchanged), or a
2696/// `Streaming` spec the thread resolves branch-by-branch at the frontier
2697/// (Step E Phase C, PR C1).
2698enum CompilerWork {
2699    /// A frozen topological order (computed up front by `order_for`). The
2700    /// compiler thread compiles each node and sends it in turn.
2701    Order(Vec<NodeId>),
2702    /// The streaming run-walk: the compiler thread drives
2703    /// [`fuel_graph::walk_picked_route_streaming`] over `roots`, resolving
2704    /// each `Op::Branch` lazily via [`resolve_branch`] as the frontier
2705    /// reaches its arm-entry, and compiling + sending only the chosen
2706    /// arm's runs. `roots` are the effective roots (same set `order_for`
2707    /// lowers over). Byte-identical to `Order(lower_picked_route(
2708    /// pick_route(..)))` in C1 (same VRAM-only selector).
2709    Streaming {
2710        roots: Vec<NodeId>,
2711        pick: StreamingPick,
2712    },
2713}
2714
2715/// Compiler thread body. Holds the graph read-lock + a thread-local
2716/// layout cache and emits `WorkItem`s in topological order. For
2717/// [`CompilerWork::Order`] it walks the frozen order; for
2718/// [`CompilerWork::Streaming`] it resolves each branch at the frontier and
2719/// emits only the chosen arm's runs (Step E Phase C, PR C1). Sends
2720/// `Err(...)` and stops on the first failure.
2721fn compiler_thread_body(
2722    graph: Arc<RwLock<Graph>>,
2723    work: CompilerWork,
2724    sym_env: SymEnv,
2725    tx: Sender<Result<WorkItem>>,
2726) {
2727    let bindings = global_bindings();
2728
2729    let g = match graph.read() {
2730        Ok(g) => g,
2731        Err(_) => {
2732            let _ = tx.send(Err(poisoned("graph lock in compiler")));
2733            return;
2734        }
2735    };
2736
2737    // Compiler-thread-local layout cache. Populated as compile_one
2738    // walks topologically; downstream nodes look up their inputs'
2739    // layouts here (rather than from the graph side-table) to honor
2740    // the strided layouts emitted by metadata-only view ops earlier
2741    // in the same realize call.
2742    let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
2743    // `compile_one` for one node + send; returns `false` to stop the walk
2744    // (channel closed or compile error). Shared by both work modes so the
2745    // streamed and frozen-order paths compile identically.
2746    // Arm exits of live branches. The reconverge node reads ARM 0's exit (the runnability invariant),
2747    // so when the picker chooses an arm k >= 1 its exit is the value the reconverge must see: right
2748    // after compiling that exit, alias arm 0's exit id to it (a zero-copy `ViewOf`). Non-chosen arms
2749    // are never compiled, so an exit that is compiled here is the chosen one.
2750    let alias_exits: HashMap<NodeId, NodeId> = {
2751        let mut m = HashMap::new();
2752        for i in 0..g.len() {
2753            let id = NodeId(i);
2754            if matches!(g.node(id).op, Op::Branch { .. }) {
2755                let arms = &g.node(id).inputs;
2756                for &exit in arms.iter().skip(1) {
2757                    m.insert(exit, arms[0]);
2758                }
2759            }
2760        }
2761        m
2762    };
2763    // Diagnostic (`FUEL_PRINT_BRANCH_COUNT`): every node the compiler thread sends, in order, so a failed
2764    // realize can be read against the order it was fed.
2765    let print_order = std::env::var_os("FUEL_PRINT_BRANCH_COUNT").is_some();
2766    let compile_and_send = |id: NodeId, layout_cache: &mut HashMap<NodeId, Layout>| -> bool {
2767        if print_order {
2768            let n = g.node(id);
2769            eprintln!(
2770                "fuel: send Node#{} {} inputs={:?} backend={:?} placement={:?}",
2771                id.0,
2772                format!("{:?}", n.op).chars().take(40).collect::<String>(),
2773                n.inputs.iter().map(|i| i.0).collect::<Vec<_>>(),
2774                g.target_backend(id),
2775                g.placement(id),
2776            );
2777        }
2778        let item = compile_one(&g, id, layout_cache, &bindings, &sym_env);
2779        let stop_on_err = item.is_err();
2780        if tx.send(item).is_err() {
2781            return false;
2782        }
2783        if stop_on_err {
2784            return false;
2785        }
2786        if let Some(&arm0_exit) = alias_exits.get(&id)
2787            && tx
2788                .send(Ok(arm_exit_alias_item(&g, arm0_exit, id, layout_cache)))
2789                .is_err()
2790        {
2791            return false;
2792        }
2793        true
2794    };
2795
2796    match work {
2797        CompilerWork::Order(order) => {
2798            for id in order {
2799                if !compile_and_send(id, &mut layout_cache) {
2800                    return;
2801                }
2802            }
2803        }
2804        CompilerWork::Streaming { roots, pick } => {
2805            // Resolve each branch lazily at its arm-entry. C1 built the
2806            // streaming frontier; C2 made `pick.selector` load-aware (the
2807            // production `ChainedSelector` now reads each arm's live device
2808            // load — `pending_work_count / slot_capacity` via the
2809            // `BackendStreams` seam — as a key leg under the VRAM guard),
2810            // so this resolution reads live device load at THIS moment: the
2811            // executor has been submitting/draining (and updating the B1
2812            // counter) while the compiler ran ahead. Emit only the chosen
2813            // arm's runs, compiling + sending each node as the walk reaches
2814            // it — genuine streaming (resolution interleaved with
2815            // dispatch), not a pre-flattened order.
2816            let mut stopped = false;
2817            fuel_graph::walk_picked_route_streaming(
2818                &g,
2819                &roots,
2820                |branch| resolve_branch(&g, branch, &bindings, pick.selector.as_ref()),
2821                |members| {
2822                    if stopped {
2823                        return;
2824                    }
2825                    for &id in members {
2826                        if !compile_and_send(id, &mut layout_cache) {
2827                            stopped = true;
2828                            return;
2829                        }
2830                    }
2831                },
2832            );
2833        }
2834    }
2835}
2836
2837/// The work item that makes arm 0's exit id carry the value of the chosen arm's exit: a zero-copy
2838/// `ViewOf` (the executor clones the source's storage into `alias_id`'s cache slot). Emitted right
2839/// after the chosen exit, before the reconverge node that reads `alias_id`. The two exits agree on
2840/// shape and dtype by the branch's cast-to-uniform rule, so the layout is the source's.
2841fn arm_exit_alias_item(
2842    graph: &Graph,
2843    alias_id: NodeId,
2844    source: NodeId,
2845    layout_cache: &mut HashMap<NodeId, Layout>,
2846) -> WorkItem {
2847    let node = graph.node(alias_id);
2848    let layout = layout_cache
2849        .get(&source)
2850        .cloned()
2851        .unwrap_or_else(|| Layout::contiguous(graph.node(source).shape.clone()));
2852    layout_cache.insert(alias_id, layout.clone());
2853    WorkItem {
2854        node_id: alias_id,
2855        inputs: vec![source],
2856        elem_count: node.shape.elem_count(),
2857        dtype: node.dtype,
2858        target_backend: graph
2859            .target_backend(source)
2860            .or_else(|| graph.target_backend(alias_id))
2861            .unwrap_or(BackendId::Cpu),
2862        kind: WorkItemKind::ViewOf { input: source },
2863        compiled: None,
2864        output_layout: layout,
2865        destructive_input: None,
2866        output_bundle: None,
2867    }
2868}
2869
2870/// Resolve the [`CompiledNode`] for a kernel-bearing graph node via
2871/// the first-registered [`compile_node`] binding-table lookup.
2872///
2873/// `op_params` always comes from the executor's
2874/// `op_to_op_params(graph, node, id, layout_cache, sym_env)` — the live
2875/// OpParams shape (reduce dims, conv geometry, the per-pass
2876/// `SymEnv`-resolved `WriteSlice` offset, etc.) derives from the graph
2877/// node + its resolved input layouts at execute time.
2878fn resolve_compiled(
2879    graph: &Graph,
2880    node: &fuel_graph::Node,
2881    op_kind: OpKind,
2882    dtypes: &[DType],
2883    target_backend: BackendId,
2884    op_params: OpParams,
2885    bindings: &KernelBindingTable,
2886) -> Result<CompiledNode> {
2887    let mut compiled = compile_node(op_kind, dtypes, target_backend, op_params, bindings)?;
2888    // ROADMAP row 158: price the launch ONCE here so the executor's per-op feed of the device backlog is a
2889    // field read, not a cost-model query (see `compiled::estimate_static_ns`).
2890    if target_backend != BackendId::Cpu {
2891        let shapes: Vec<fuel_ir::Shape> = node
2892            .inputs
2893            .iter()
2894            .map(|&i| graph.node(i).shape.clone())
2895            .collect();
2896        compiled.est_ns = crate::compiled::estimate_static_ns(
2897            op_kind,
2898            dtypes,
2899            &shapes,
2900            target_backend,
2901            &compiled.op_params,
2902            bindings,
2903        );
2904    }
2905    Ok(compiled)
2906}
2907
2908/// Resolve one node into a `WorkItem` and update `layout_cache`
2909/// with the node's output layout. Three op shapes:
2910///
2911/// - `Op::Const` — adopts the entry from the input cache; layout is
2912///   read from the graph's side-table (or its contiguous fallback).
2913///
2914/// - Metadata-only view op — output layout is read from the graph's
2915///   side-table (populated by `Graph::push` at construction time);
2916///   the executor adopts the input's Storage Arc (no allocation, no
2917///   kernel).
2918///
2919/// - Computational op — output layout is `Layout::contiguous(node.shape)`
2920///   because today's kernels write contiguous output. The compiler
2921///   resolves the kernel ref and emits a Kernel work item.
2922fn compile_one(
2923    graph: &Graph,
2924    id: NodeId,
2925    layout_cache: &mut HashMap<NodeId, Layout>,
2926    bindings: &KernelBindingTable,
2927    sym_env: &SymEnv,
2928) -> Result<WorkItem> {
2929    let node = graph.node(id);
2930    let elem_count = node.shape.elem_count();
2931    let inputs = node.inputs.clone();
2932    // Snapshot destructive-input metadata from the graph at compile
2933    // time so the executor can evict the destroyed input from its
2934    // cache after the op runs (Op::Release / Op::Move semantics).
2935    let destructive_input = node.op.destructive_input();
2936
2937    if matches!(node.op, Op::Const) {
2938        let output_layout = graph.layout(id);
2939        layout_cache.insert(id, output_layout.clone());
2940        return Ok(WorkItem {
2941            node_id: id,
2942            inputs,
2943            elem_count,
2944            dtype: node.dtype,
2945            target_backend: BackendId::Cpu,
2946            kind: WorkItemKind::ConstAdopt,
2947            compiled: None,
2948            output_layout,
2949            destructive_input,
2950            output_bundle: None,
2951        });
2952    }
2953
2954    if node.op.is_view_op() {
2955        if inputs.len() != 1 {
2956            return Err(Error::Msg(format!(
2957                "view op {:?} expects 1 input, got {}",
2958                node.op,
2959                inputs.len(),
2960            ))
2961            .bt());
2962        }
2963        // Layout is read from the graph's side-table — populated by
2964        // `Graph::push` at construction time for view ops, and by
2965        // graph-rewriting opt passes that emit view nodes. The
2966        // compiler does not re-derive: graph.layout(id) is the single
2967        // source of truth.
2968        let output_layout = graph.layout(id);
2969        layout_cache.insert(id, output_layout.clone());
2970        // Inherit the upstream's target_backend (or default CPU) —
2971        // metadata-only adoption doesn't actually run on a backend,
2972        // but downstream consumers look at target_backend so it
2973        // needs to be set sensibly. Any device works.
2974        let target_backend = graph
2975            .target_backend(id)
2976            .or_else(|| graph.target_backend(inputs[0]))
2977            .unwrap_or(BackendId::Cpu);
2978        return Ok(WorkItem {
2979            node_id: id,
2980            inputs,
2981            elem_count,
2982            dtype: node.dtype,
2983            target_backend,
2984            kind: WorkItemKind::ViewOf {
2985                input: node.inputs[0],
2986            },
2987            compiled: None,
2988            output_layout,
2989            destructive_input,
2990            output_bundle: None,
2991        });
2992    }
2993
2994    // Op::View — multi-output projection (Option C, Session 4).
2995    // Structurally identical to a metadata-only view op at realize
2996    // time: clone the producer's Storage Arc into the View's cache
2997    // slot. The graph's layout side-table, populated by
2998    // `Tensor::view`, already carries the slot's effective layout
2999    // (slot.byte_offset baked into start_offset in slot-dtype-element
3000    // units).
3001    if let Op::View { .. } = node.op {
3002        if inputs.len() != 1 {
3003            return Err(Error::Msg(format!(
3004                "Op::View expects 1 input (the producer), got {}",
3005                inputs.len(),
3006            ))
3007            .bt());
3008        }
3009        let output_layout = graph.layout(id);
3010        layout_cache.insert(id, output_layout.clone());
3011        let target_backend = graph
3012            .target_backend(id)
3013            .or_else(|| graph.target_backend(inputs[0]))
3014            .unwrap_or(BackendId::Cpu);
3015        return Ok(WorkItem {
3016            node_id: id,
3017            inputs: inputs.clone(),
3018            elem_count,
3019            dtype: node.dtype,
3020            target_backend,
3021            kind: WorkItemKind::SlotView {
3022                producer: inputs[0],
3023            },
3024            compiled: None,
3025            output_layout,
3026            destructive_input,
3027            output_bundle: None,
3028        });
3029    }
3030
3031    // Op::ViewOwned — copies the slot's bytes into a fresh
3032    // contiguous Storage at realize time. Output layout is
3033    // contiguous starting at offset 0 (the memcpy produced an
3034    // independent buffer).
3035    if let Op::ViewOwned { slot } = node.op {
3036        if inputs.len() != 1 {
3037            return Err(Error::Msg(format!(
3038                "Op::ViewOwned expects 1 input (the producer), got {}",
3039                inputs.len(),
3040            ))
3041            .bt());
3042        }
3043        let output_layout = Layout::contiguous(node.shape.clone());
3044        layout_cache.insert(id, output_layout.clone());
3045        let target_backend = graph
3046            .target_backend(id)
3047            .or_else(|| graph.target_backend(inputs[0]))
3048            .unwrap_or(BackendId::Cpu);
3049        return Ok(WorkItem {
3050            node_id: id,
3051            inputs: inputs.clone(),
3052            elem_count,
3053            dtype: node.dtype,
3054            target_backend,
3055            kind: WorkItemKind::SlotOwn {
3056                producer: inputs[0],
3057                slot,
3058            },
3059            compiled: None,
3060            output_layout,
3061            destructive_input,
3062            output_bundle: None,
3063        });
3064    }
3065
3066    if matches!(node.op, Op::Release) {
3067        // Op::Release produces a zero-element marker output. The
3068        // marker storage is CPU + 0 bytes — nothing reads it; it
3069        // exists so cache lookups on the Release NodeId resolve.
3070        // The actual deallocation of `inputs[0]` happens in the
3071        // realize loop via `destructive_input` cleanup.
3072        if inputs.len() != 1 {
3073            return Err(
3074                Error::Msg(format!("Op::Release expects 1 input, got {}", inputs.len(),)).bt(),
3075            );
3076        }
3077        let output_layout = Layout::contiguous(node.shape.clone());
3078        layout_cache.insert(id, output_layout.clone());
3079        // Inherit the source's target_backend so any downstream
3080        // backend-aware logic (telemetry, scheduling) sees a sensible
3081        // value. The marker doesn't actually run on any backend.
3082        let target_backend = graph
3083            .target_backend(id)
3084            .or_else(|| graph.target_backend(inputs[0]))
3085            .unwrap_or(BackendId::Cpu);
3086        return Ok(WorkItem {
3087            node_id: id,
3088            inputs,
3089            elem_count,
3090            dtype: node.dtype,
3091            target_backend,
3092            kind: WorkItemKind::ReleaseMarker,
3093            compiled: None,
3094            output_layout,
3095            destructive_input,
3096            output_bundle: None,
3097        });
3098    }
3099
3100    // In-place ops (Phase 3 of in-place ops infrastructure): kernel
3101    // lookup goes through the standard binding-table path, but the
3102    // executor adopts the target's Arc as the output instead of
3103    // allocating fresh bytes. The compile-time predicate is exactly
3104    // `op.destructive_input().is_some()` AND NOT one of the
3105    // structural ops (WriteSlice / ZeroFill / Release / Move) which
3106    // have their own dedicated WorkItemKind arms in this function.
3107    if !matches!(
3108        node.op,
3109        Op::WriteSlice { .. }
3110            | Op::WriteSliceRotating { .. }
3111            | Op::WriteSliceDoff { .. }
3112            | Op::ZeroFill
3113            | Op::Release
3114            | Op::Move { .. },
3115    ) && let Some(target_idx) = node.op.destructive_input()
3116    {
3117        if inputs.len() <= target_idx {
3118            return Err(Error::Msg(format!(
3119                "in-place op {:?} declares destructive_input={target_idx} \
3120                     but has only {} input(s)",
3121                node.op,
3122                inputs.len(),
3123            ))
3124            .bt());
3125        }
3126        let target_backend = graph.target_backend(id).ok_or_else(|| {
3127            Error::Msg(format!(
3128                "PipelinedExecutor: in-place op node {id:?} has no target_backend set",
3129            ))
3130            .bt()
3131        })?;
3132        let op_kind = op_to_op_kind(&node.op).ok_or_else(|| {
3133            Error::Msg(format!(
3134                "PipelinedExecutor: in-place op {:?} has no op_to_op_kind mapping",
3135                node.op,
3136            ))
3137            .bt()
3138        })?;
3139        let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3140        let dtypes = build_lookup_dtypes(graph, node);
3141        let compiled = resolve_compiled(
3142            graph,
3143            node,
3144            op_kind,
3145            &dtypes,
3146            target_backend,
3147            op_params,
3148            bindings,
3149        )?;
3150        // Output adopts target's Layout (same Storage Arc, same shape).
3151        let output_layout = graph.layout(inputs[target_idx]);
3152        layout_cache.insert(id, output_layout.clone());
3153        return Ok(WorkItem {
3154            node_id: id,
3155            inputs: inputs.clone(),
3156            elem_count,
3157            dtype: node.dtype,
3158            target_backend,
3159            kind: WorkItemKind::InplaceKernel { target_idx },
3160            compiled: Some(compiled),
3161            output_layout,
3162            destructive_input,
3163            output_bundle: None,
3164        });
3165    }
3166
3167    if matches!(node.op, Op::WriteSlice { .. }) {
3168        // WriteSlice: kernel lookup happens like a normal kernel, but
3169        // the work item carries a dedicated kind so the executor
3170        // knows to adopt the destination's Arc as the output rather
3171        // than allocating a fresh buffer. The destination's NodeId is
3172        // captured here so the executor doesn't have to re-derive it.
3173        if inputs.len() != 2 {
3174            return Err(Error::Msg(format!(
3175                "Op::WriteSlice expects 2 inputs (destination, source), got {}",
3176                inputs.len(),
3177            ))
3178            .bt());
3179        }
3180        let target_backend = graph.target_backend(id).ok_or_else(|| {
3181            Error::Msg(format!(
3182                "PipelinedExecutor: WriteSlice node {:?} has no target_backend set",
3183                id
3184            ))
3185            .bt()
3186        })?;
3187        let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3188        let dtypes = build_lookup_dtypes(graph, node);
3189        let compiled = resolve_compiled(
3190            graph,
3191            node,
3192            OpKind::WriteSlice,
3193            &dtypes,
3194            target_backend,
3195            op_params,
3196            bindings,
3197        )?;
3198        // Output adopts the destination's Layout — same Storage Arc,
3199        // same shape. Downstream consumers that want a post-write
3200        // sub-extent compose an explicit Op::Slice (WriteSlice does
3201        // not encode partial extents).
3202        let output_layout = graph.layout(inputs[0]);
3203        layout_cache.insert(id, output_layout.clone());
3204        return Ok(WorkItem {
3205            node_id: id,
3206            inputs: inputs.clone(),
3207            elem_count,
3208            dtype: node.dtype,
3209            target_backend,
3210            kind: WorkItemKind::WriteSlice {
3211                dest: inputs[0],
3212                source: inputs[1],
3213            },
3214            compiled: Some(compiled),
3215            output_layout,
3216            destructive_input,
3217            output_bundle: None,
3218        });
3219    }
3220
3221    if matches!(node.op, Op::WriteSliceRotating { .. }) {
3222        // WriteSliceRotating: same shape as WriteSlice but with a
3223        // third input (position scalar). Dispatch through the
3224        // binding table at `OpKind::WriteSliceRotating`; the
3225        // executor's arm reads the position from `position`'s
3226        // storage and the kernel splits across the ring boundary.
3227        if inputs.len() != 3 {
3228            return Err(Error::Msg(format!(
3229                "Op::WriteSliceRotating expects 3 inputs (destination, source, position), got {}",
3230                inputs.len(),
3231            ))
3232            .bt());
3233        }
3234        let target_backend = graph.target_backend(id).ok_or_else(|| {
3235            Error::Msg(format!(
3236                "PipelinedExecutor: WriteSliceRotating node {:?} has no target_backend set",
3237                id
3238            ))
3239            .bt()
3240        })?;
3241        let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3242        let dtypes = build_lookup_dtypes(graph, node);
3243        let compiled = resolve_compiled(
3244            graph,
3245            node,
3246            OpKind::WriteSliceRotating,
3247            &dtypes,
3248            target_backend,
3249            op_params,
3250            bindings,
3251        )?;
3252        let output_layout = graph.layout(inputs[0]);
3253        layout_cache.insert(id, output_layout.clone());
3254        return Ok(WorkItem {
3255            node_id: id,
3256            inputs: inputs.clone(),
3257            elem_count,
3258            dtype: node.dtype,
3259            target_backend,
3260            kind: WorkItemKind::WriteSliceRotating {
3261                dest: inputs[0],
3262                source: inputs[1],
3263                position: inputs[2],
3264            },
3265            compiled: Some(compiled),
3266            output_layout,
3267            destructive_input,
3268            output_bundle: None,
3269        });
3270    }
3271
3272    if matches!(node.op, Op::WriteSliceDoff { .. }) {
3273        // WriteSliceDoff: same shape as WriteSlice but with a third
3274        // input (device-resident I64 offset). Dispatch through the
3275        // binding table at `OpKind::WriteSliceDoff`; the executor's arm
3276        // threads the offset's device pointer straight to the kernel
3277        // (no D2H, capture-safe).
3278        if inputs.len() != 3 {
3279            return Err(Error::Msg(format!(
3280                "Op::WriteSliceDoff expects 3 inputs (destination, source, offset), got {}",
3281                inputs.len(),
3282            ))
3283            .bt());
3284        }
3285        let target_backend = graph.target_backend(id).ok_or_else(|| {
3286            Error::Msg(format!(
3287                "PipelinedExecutor: WriteSliceDoff node {:?} has no target_backend set",
3288                id
3289            ))
3290            .bt()
3291        })?;
3292        let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3293        let dtypes = build_lookup_dtypes(graph, node);
3294        let compiled = resolve_compiled(
3295            graph,
3296            node,
3297            OpKind::WriteSliceDoff,
3298            &dtypes,
3299            target_backend,
3300            op_params,
3301            bindings,
3302        )?;
3303        let output_layout = graph.layout(inputs[0]);
3304        layout_cache.insert(id, output_layout.clone());
3305        return Ok(WorkItem {
3306            node_id: id,
3307            inputs: inputs.clone(),
3308            elem_count,
3309            dtype: node.dtype,
3310            target_backend,
3311            kind: WorkItemKind::WriteSliceDoff {
3312                dest: inputs[0],
3313                source: inputs[1],
3314                offset: inputs[2],
3315            },
3316            compiled: Some(compiled),
3317            output_layout,
3318            destructive_input,
3319            output_bundle: None,
3320        });
3321    }
3322
3323    if let Op::Alloc { target } = node.op {
3324        // Op::Alloc { target }: produce a fresh zero-init Storage on
3325        // `target` with node.shape * node.dtype. Zero inputs.
3326        // Direct executor dispatch via WorkItemKind::Alloc — no
3327        // binding-table lookup (the device handle threading isn't
3328        // expressible through the binding table's current key shape).
3329        if !inputs.is_empty() {
3330            return Err(
3331                Error::Msg(format!("Op::Alloc expects 0 inputs, got {}", inputs.len(),)).bt(),
3332            );
3333        }
3334        let output_layout = Layout::contiguous(node.shape.clone());
3335        layout_cache.insert(id, output_layout.clone());
3336        // target_backend is informational here (the executor's Alloc
3337        // arm consults target_location for allocation routing); set
3338        // it to target's backend for consistency with how downstream
3339        // nodes inherit/read it.
3340        let target_backend = target.backend();
3341        return Ok(WorkItem {
3342            node_id: id,
3343            inputs,
3344            elem_count,
3345            dtype: node.dtype,
3346            target_backend,
3347            kind: WorkItemKind::Alloc {
3348                target_location: target,
3349            },
3350            compiled: None,
3351            output_layout,
3352            destructive_input,
3353            output_bundle: None,
3354        });
3355    }
3356
3357    if let Op::Iota { len } = node.op {
3358        // Op::Iota { len }: 0-input F32 position generator
3359        // [0.0, 1.0, …, (len-1)]. Direct executor dispatch via
3360        // WorkItemKind::Iota — no binding-table lookup (a leaf has no
3361        // inputs[0] to inherit a backend from). Modeled on Op::Alloc.
3362        if !inputs.is_empty() {
3363            return Err(
3364                Error::Msg(format!("Op::Iota expects 0 inputs, got {}", inputs.len(),)).bt(),
3365            );
3366        }
3367        let output_layout = Layout::contiguous(node.shape.clone());
3368        layout_cache.insert(id, output_layout.clone());
3369        // Leaf: the planner may not place a 0-input node, so fall back to
3370        // CPU. Iota is a tiny host-side generator; its only consumer today
3371        // is the CPU flash-attn decomposition's alibi bias.
3372        let target_backend = graph.target_backend(id).unwrap_or(BackendId::Cpu);
3373        return Ok(WorkItem {
3374            node_id: id,
3375            inputs,
3376            elem_count,
3377            dtype: node.dtype,
3378            target_backend,
3379            kind: WorkItemKind::Iota {
3380                len,
3381                target_location: graph.placement(id),
3382            },
3383            compiled: None,
3384            output_layout,
3385            destructive_input,
3386            output_bundle: None,
3387        });
3388    }
3389
3390    if matches!(node.op, Op::ZeroFill) {
3391        // Op::ZeroFill: 1 input (the buffer to zero); output aliases
3392        // input's Storage Arc (destructive in-place). No binding-
3393        // table lookup — per-backend dispatch in execute_work_item.
3394        if inputs.len() != 1 {
3395            return Err(Error::Msg(format!(
3396                "Op::ZeroFill expects 1 input, got {}",
3397                inputs.len(),
3398            ))
3399            .bt());
3400        }
3401        // Output layout: contiguous in the node's shape. We don't
3402        // require the input to be contiguous (auto_contiguize in the
3403        // executor handles strided inputs), but the destructive
3404        // semantic means callers should only ZeroFill an Op::Alloc
3405        // output today.
3406        let output_layout = Layout::contiguous(node.shape.clone());
3407        layout_cache.insert(id, output_layout.clone());
3408        let target_backend = graph
3409            .target_backend(id)
3410            .or_else(|| graph.target_backend(inputs[0]))
3411            .unwrap_or(BackendId::Cpu);
3412        return Ok(WorkItem {
3413            node_id: id,
3414            inputs,
3415            elem_count,
3416            dtype: node.dtype,
3417            target_backend,
3418            kind: WorkItemKind::ZeroFill,
3419            compiled: None,
3420            output_layout,
3421            destructive_input,
3422            output_bundle: None,
3423        });
3424    }
3425
3426    if let Op::Copy { target } = node.op {
3427        // Op::Copy { target }: download bytes from the source residency
3428        // to a fresh Storage allocated on `target`. Kernel lookup uses
3429        // `target_backend` = source backend (set by `prepare()` on the
3430        // realize device the source is on); the wrapper does the actual
3431        // transfer (e.g. Vulkan::download_bytes → memcpy into a CPU
3432        // CpuStorageBytes). The output Storage's variant is determined
3433        // by `target_location` and allocated in `execute_work_item`'s
3434        // WorkItemKind::Copy arm.
3435        if inputs.len() != 1 {
3436            return Err(
3437                Error::Msg(format!("Op::Copy expects 1 input, got {}", inputs.len(),)).bt(),
3438            );
3439        }
3440        let target_backend = graph.target_backend(id).ok_or_else(|| {
3441            Error::Msg(format!(
3442                "PipelinedExecutor: Op::Copy node {:?} has no target_backend \
3443                 set (= source backend, the one whose kernel runs the \
3444                 download)",
3445                id
3446            ))
3447            .bt()
3448        })?;
3449        let op_params = OpParams::None;
3450        let dtypes = build_lookup_dtypes(graph, node);
3451        let compiled = resolve_compiled(
3452            graph,
3453            node,
3454            OpKind::Copy,
3455            &dtypes,
3456            target_backend,
3457            op_params,
3458            bindings,
3459        )?;
3460        // Output layout: contiguous in the node's shape (mirrors the
3461        // source's logical shape). Auto-contiguize on the input side
3462        // (in execute_work_item) handles strided source views by
3463        // materializing them into a contiguous source buffer before
3464        // the kernel runs.
3465        let output_layout = Layout::contiguous(node.shape.clone());
3466        layout_cache.insert(id, output_layout.clone());
3467        return Ok(WorkItem {
3468            node_id: id,
3469            inputs,
3470            elem_count,
3471            dtype: node.dtype,
3472            target_backend,
3473            kind: WorkItemKind::Copy {
3474                target_location: target,
3475            },
3476            compiled: Some(compiled),
3477            output_layout,
3478            destructive_input,
3479            output_bundle: None,
3480        });
3481    }
3482
3483    if let Op::Move { target } = node.op {
3484        // Op::Move { target }: identical data-movement half to
3485        // Op::Copy — kernel lookup at (OpKind::Copy, [dt, dt],
3486        // source_backend); output allocated on `target` by the
3487        // executor's Copy/Move arm. The destructive half (release
3488        // the source) rides the realize loop's `destructive_input`
3489        // cleanup via the snapshot taken at the top of this function
3490        // (`Op::Move::destructive_input() == Some(0)`). Ordering
3491        // safety (a Move must not strand a sibling consumer of its
3492        // source) is `execution_plan`/`derive_ordering`'s job — the
3493        // Move is pinned after every non-destructive reader of the
3494        // source's alias set before any work item is emitted.
3495        if inputs.len() != 1 {
3496            return Err(
3497                Error::Msg(format!("Op::Move expects 1 input, got {}", inputs.len(),)).bt(),
3498            );
3499        }
3500        let target_backend = graph.target_backend(id).ok_or_else(|| {
3501            Error::Msg(format!(
3502                "PipelinedExecutor: Op::Move node {:?} has no target_backend \
3503                 set (= source backend, the one whose kernel runs the \
3504                 transfer)",
3505                id
3506            ))
3507            .bt()
3508        })?;
3509        let op_params = OpParams::None;
3510        let dtypes = build_lookup_dtypes(graph, node);
3511        let compiled = resolve_compiled(
3512            graph,
3513            node,
3514            OpKind::Copy,
3515            &dtypes,
3516            target_backend,
3517            op_params,
3518            bindings,
3519        )?;
3520        // Output layout: contiguous in the node's shape, same as
3521        // Op::Copy (the transfer materializes strided sources via
3522        // auto-contiguize on the input side).
3523        let output_layout = Layout::contiguous(node.shape.clone());
3524        layout_cache.insert(id, output_layout.clone());
3525        return Ok(WorkItem {
3526            node_id: id,
3527            inputs,
3528            elem_count,
3529            dtype: node.dtype,
3530            target_backend,
3531            kind: WorkItemKind::Move {
3532                target_location: target,
3533            },
3534            compiled: Some(compiled),
3535            output_layout,
3536            destructive_input,
3537            output_bundle: None,
3538        });
3539    }
3540
3541    if matches!(node.op, Op::Reshape(_)) {
3542        if inputs.len() != 1 {
3543            return Err(
3544                Error::Msg(format!("Op::Reshape expects 1 input, got {}", inputs.len(),)).bt(),
3545            );
3546        }
3547        let input_layout = graph.layout(inputs[0]);
3548        // Output is contiguous in the new shape — bytes per element
3549        // are unchanged, so a contiguous input flows through with
3550        // zero copy. A non-contiguous input is auto-contiguized at
3551        // execute time and the result is naturally contiguous.
3552        let output_layout = Layout::contiguous(node.shape.clone());
3553        layout_cache.insert(id, output_layout.clone());
3554        let target_backend = graph
3555            .target_backend(id)
3556            .or_else(|| graph.target_backend(inputs[0]))
3557            .unwrap_or(BackendId::Cpu);
3558        // Sanity: same total element count.
3559        let in_elem_count = input_layout.shape().elem_count();
3560        if in_elem_count != elem_count {
3561            return Err(Error::Msg(format!(
3562                "Op::Reshape changes element count: input {} → output {}",
3563                in_elem_count, elem_count,
3564            ))
3565            .bt());
3566        }
3567        return Ok(WorkItem {
3568            node_id: id,
3569            inputs,
3570            elem_count,
3571            dtype: node.dtype,
3572            target_backend,
3573            kind: WorkItemKind::ContiguizeOf {
3574                input: node.inputs[0],
3575            },
3576            compiled: None,
3577            output_layout,
3578            destructive_input,
3579            output_bundle: None,
3580        });
3581    }
3582
3583    if matches!(node.op, Op::Contiguize) {
3584        // Op::Contiguize: same execute-time path as Reshape, but
3585        // output shape == input shape so there's no element-count
3586        // check. Zero-copy when input is already contiguous +
3587        // zero-offset (the ContiguizeOf arm in execute_work_item
3588        // adopts the input Arc); otherwise auto_contiguize allocates
3589        // a fresh contiguous Storage on the input's backend.
3590        if inputs.len() != 1 {
3591            return Err(Error::Msg(format!(
3592                "Op::Contiguize expects 1 input, got {}",
3593                inputs.len(),
3594            ))
3595            .bt());
3596        }
3597        let output_layout = Layout::contiguous(node.shape.clone());
3598        layout_cache.insert(id, output_layout.clone());
3599        let target_backend = graph
3600            .target_backend(id)
3601            .or_else(|| graph.target_backend(inputs[0]))
3602            .unwrap_or(BackendId::Cpu);
3603        return Ok(WorkItem {
3604            node_id: id,
3605            inputs,
3606            elem_count,
3607            dtype: node.dtype,
3608            target_backend,
3609            kind: WorkItemKind::ContiguizeOf {
3610                input: node.inputs[0],
3611            },
3612            compiled: None,
3613            output_layout,
3614            destructive_input,
3615            output_bundle: None,
3616        });
3617    }
3618
3619    // Runtime fused op — a JIT-adopted (Tier-2) kernel. `Op::Fused(fid, _)`
3620    // with `fid.is_runtime()` has no `OpKind` (the op was synthesized after
3621    // startup): its kernel resolves from the SAME binding table as every
3622    // static kernel, under `BindingKey::RuntimeFused(fid)` — the dtype tuple
3623    // is the key, so an absent kernel AND a dtype mismatch are one honest
3624    // `NoBackendForOp` miss. A deterministic *lookup*, not a decision: the
3625    // optimizer's gate emitted the arm only when this kernel was bound, and
3626    // pinned `target_backend` (`runtime-fused-op-registration.md` §6). The
3627    // guards are invariant checks, never live fallbacks.
3628    if let Op::Fused(fid, _) = &node.op
3629        && fid.is_runtime()
3630    {
3631        let target_backend = graph.target_backend(id).ok_or_else(|| {
3632            Error::Msg(format!(
3633                "PipelinedExecutor: runtime fused op {:?} (node {:?}) has no \
3634                     target_backend — the arm emitter pins it at emission",
3635                fid, id,
3636            ))
3637            .bt()
3638        })?;
3639        // v1: single-output only. Reject a multi-output bundle explicitly
3640        // rather than silently dropping it.
3641        if graph.output_views_arc(id).is_some() {
3642            return Err(Error::Msg(format!(
3643                "PipelinedExecutor: runtime fused op {:?} (node {:?}) carries a \
3644                     multi-output bundle — synthesized kernels are single-output in v1",
3645                fid, id,
3646            ))
3647            .bt());
3648        }
3649        let dtypes = build_lookup_dtypes(graph, node);
3650        let (kernel, caps) = bindings.lookup_with_caps(
3651            crate::kernel::BindingKey::RuntimeFused(*fid),
3652            &dtypes,
3653            target_backend,
3654        )?;
3655        let output_layout = Layout::contiguous(node.shape.clone());
3656        layout_cache.insert(id, output_layout.clone());
3657        // Deliberate, not a fallthrough to `op_to_op_params` (which doesn't
3658        // know runtime ops): the node's `Runtime { scalars }` — the live
3659        // `extract:` values, pattern pre-order — becomes `JitScalars` (the
3660        // launch appends them as the kernel's trailing `p{i}` args); a
3661        // param-free op carries `None` (its launch is layout-driven:
3662        // pointers + element count).
3663        let op_params = match &node.op {
3664            Op::Fused(_, FusedOpParams::Runtime { scalars }) if !scalars.is_empty() => {
3665                OpParams::JitScalars {
3666                    scalars: scalars.clone(),
3667                }
3668            }
3669            _ => OpParams::None,
3670        };
3671        let compiled = CompiledNode {
3672            op: OpKind::RuntimeFused,
3673            dtypes: KernelDTypes::from_slice(&dtypes),
3674            backend: target_backend,
3675            kernel,
3676            caps,
3677            op_params,
3678            est_ns: 0,
3679        };
3680        return Ok(WorkItem {
3681            node_id: id,
3682            inputs,
3683            elem_count,
3684            dtype: node.dtype,
3685            target_backend,
3686            kind: WorkItemKind::Kernel,
3687            compiled: Some(compiled),
3688            output_layout,
3689            destructive_input,
3690            output_bundle: None,
3691        });
3692    }
3693
3694    let target_backend = graph.target_backend(id).ok_or_else(|| {
3695        Error::Msg(format!(
3696            "PipelinedExecutor: node {:?} ({:?}) has no target_backend set",
3697            id, node.op
3698        ))
3699        .bt()
3700    })?;
3701
3702    let op_kind = op_to_op_kind(&node.op).ok_or_else(|| {
3703        Error::Msg(format!(
3704            "PipelinedExecutor: op {:?} not yet mapped to an OpKind \
3705             (Phase C migrates more ops as they're registered)",
3706            node.op,
3707        ))
3708        .bt()
3709    })?;
3710
3711    let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3712    // Build the per-operand dtype list for the binding-table lookup —
3713    // inputs in order, then outputs. Variadic uniform-dtype ops
3714    // (Concat) collapse to the canonical `[T_in, T_out]` shorthand to
3715    // match how registrations index them.
3716    let dtypes = build_lookup_dtypes(graph, node);
3717    let compiled = resolve_compiled(
3718        graph,
3719        node,
3720        op_kind,
3721        &dtypes,
3722        target_backend,
3723        op_params,
3724        bindings,
3725    )?;
3726    let output_layout = Layout::contiguous(node.shape.clone());
3727    layout_cache.insert(id, output_layout.clone());
3728    // Multi-output: snapshot the producer's bundle metadata. When
3729    // `Some(_)`, the Kernel arm allocates a single Storage sized to
3730    // fit every slot and attaches the bundle via
3731    // `Storage::with_bundle` so downstream Op::View/Op::ViewOwned
3732    // resolve correctly.
3733    let output_bundle = graph.output_views_arc(id);
3734    Ok(WorkItem {
3735        node_id: id,
3736        inputs,
3737        elem_count,
3738        dtype: node.dtype,
3739        target_backend,
3740        kind: WorkItemKind::Kernel,
3741        compiled: Some(compiled),
3742        output_layout,
3743        destructive_input,
3744        output_bundle,
3745    })
3746}
3747
3748/// Build the per-operand dtype list used as the binding-table lookup
3749/// key. Inputs in order, then the output. Variadic-uniform ops
3750/// (Concat) collapse to the canonical `[T_in, T_out]` shorthand to
3751/// match how those wrappers are registered (otherwise an N-way concat
3752/// would need N+1 distinct registrations per dtype).
3753///
3754/// `pub(crate)` — `crate::plan::compile_plan` (step 9b) reuses this
3755/// to key the route picker's binding-table lookup the same way the
3756/// pipelined path does.
3757pub(crate) fn build_lookup_dtypes(graph: &Graph, node: &Node) -> Vec<DType> {
3758    if matches!(node.op, Op::Concat { .. }) {
3759        // Concat: all inputs share node.dtype by construction.
3760        let in_dt = node
3761            .inputs
3762            .first()
3763            .map(|&id| graph.node(id).dtype)
3764            .unwrap_or(node.dtype);
3765        return vec![in_dt, node.dtype];
3766    }
3767    if matches!(node.op, Op::WriteSlice { .. }) {
3768        // WriteSlice: the destination (inputs[0]) is exposed to the
3769        // executor as the OUTPUT slot (in-place adoption), not as an
3770        // input the kernel reads. Canonicalize the binding-table key
3771        // to `[T_source, T_out]` so registrations match the kernel's
3772        // actual surface (one input slab + one output buffer).
3773        let src_dt = node
3774            .inputs
3775            .get(1)
3776            .map(|&id| graph.node(id).dtype)
3777            .unwrap_or(node.dtype);
3778        return vec![src_dt, node.dtype];
3779    }
3780    if matches!(node.op, Op::WriteSliceRotating { .. }) {
3781        // Same canonicalization as WriteSlice: dest = output slot;
3782        // position (inputs[2]) is read by the kernel via the
3783        // position-input parameter, not the binding-table key.
3784        let src_dt = node
3785            .inputs
3786            .get(1)
3787            .map(|&id| graph.node(id).dtype)
3788            .unwrap_or(node.dtype);
3789        return vec![src_dt, node.dtype];
3790    }
3791    if matches!(node.op, Op::WriteSliceDoff { .. }) {
3792        // Same canonicalization as WriteSlice: dest = output slot;
3793        // offset (inputs[2], I64) is a non-key runtime operand read by
3794        // the kernel via its device pointer, not the binding-table key.
3795        let src_dt = node
3796            .inputs
3797            .get(1)
3798            .map(|&id| graph.node(id).dtype)
3799            .unwrap_or(node.dtype);
3800        return vec![src_dt, node.dtype];
3801    }
3802    let mut dts: Vec<DType> = node.inputs.iter().map(|&id| graph.node(id).dtype).collect();
3803    dts.push(node.dtype);
3804    dts
3805}
3806
3807/// SoftmaxLastDim is reachable only through `Op::Fused(FusedOps::
3808/// SOFTMAX_LAST_DIM, _)` post-step-5 (the legacy `Op::SoftmaxLastDim`
3809/// primitive variant was retired). This helper collapses the
3810/// op-to-OpKind/OpParams shapes for callers that want a single-arm
3811/// match.
3812fn op_is_softmax_last_dim(op: &Op) -> bool {
3813    matches!(op, Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM)
3814}
3815
3816/// FusedLinear is reachable only through `Op::Fused(FusedOps::
3817/// FUSED_LINEAR, _)` post-step-5.
3818fn op_is_fused_linear(op: &Op) -> bool {
3819    matches!(op, Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::FUSED_LINEAR)
3820}
3821
3822/// RowScaledMatMul (row 172 item 1): `(a @ b) * row_scale`, reached only through
3823/// `Op::Fused(FusedOps::ROW_SCALED_MATMUL, _)`. Shares FusedLinear's
3824/// `OpParams::Matmul` params; its third input is the `[..., M, 1]` row scale.
3825fn op_is_row_scaled_matmul(op: &Op) -> bool {
3826    matches!(op, Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::ROW_SCALED_MATMUL)
3827}
3828
3829/// Does the executor have an arm that runs `op` on `backend`? Only for ops it dispatches DIRECTLY
3830/// (no binding-table kernel, so the planner cannot reject them for lack of a binding). `None` means
3831/// the op is not direct-dispatched and this answer does not apply (the binding table decides).
3832///
3833/// Source of truth for [`check_direct_arms_wired`]; keep in step with the `execute_work_item` arms.
3834pub(crate) fn direct_arm_wired(op: &Op, backend: BackendId) -> Option<bool> {
3835    match op {
3836        // CPU generates it; CUDA generates on the host and uploads (GAP-380 a2). The cuda arm is
3837        // compiled only with the `cuda` feature, and a CUDA stamp cannot arise without it.
3838        Op::Iota { .. } => Some(
3839            backend == BackendId::Cpu || (cfg!(feature = "cuda") && backend == BackendId::Cuda),
3840        ),
3841        _ => None,
3842    }
3843}
3844
3845/// Plan-time guard (PM, 2026-11-12): a node stamped for a backend whose executor has no arm for its
3846/// op fails HERE, with the node and op named, instead of as an `Err` inside the executor mid-run.
3847/// Run after the backend stamp. A graph with every arm wired is a no-op.
3848pub(crate) fn check_direct_arms_wired(graph: &Graph, roots: &[NodeId]) -> Result<()> {
3849    for id in fuel_graph::topo_order_multi(graph, roots) {
3850        let node = graph.node(id);
3851        let backend = graph.target_backend(id).unwrap_or(BackendId::Cpu);
3852        if direct_arm_wired(&node.op, backend) == Some(false) {
3853            return Err(Error::Msg(format!(
3854                "plan: Node#{} ({:?}, out shape={:?} dtype={:?}) is placed on {backend:?} but the executor                  has no {backend:?} arm for this op (wired arms: see pipelined::direct_arm_wired)",
3855                id.0,
3856                node.op,
3857                node.shape,
3858                node.dtype,
3859            ))
3860            .bt());
3861        }
3862    }
3863    Ok(())
3864}
3865
3866/// Map a `fuel_graph::Op` to a `fuel_ir::dispatch::OpKind`.
3867/// Returns `None` for ops that haven't been wired into the new
3868/// dispatch path yet — Phase C extends this as op families migrate.
3869///
3870/// `pub(crate)` — `crate::plan::compile_plan` (step 9b) reuses this
3871/// to skip nodes the binding-table doesn't index (view ops,
3872/// `Op::Const`, not-yet-migrated ops) when building bindings.
3873pub(crate) fn op_to_op_kind(op: &Op) -> Option<OpKind> {
3874    match op {
3875        Op::Add => Some(OpKind::AddElementwise),
3876        Op::Sub => Some(OpKind::SubElementwise),
3877        Op::Mul => Some(OpKind::MulElementwise),
3878        Op::Div => Some(OpKind::DivElementwise),
3879        Op::Relu => Some(OpKind::ReluElementwise),
3880        Op::Neg => Some(OpKind::NegElementwise),
3881        Op::Sqr => Some(OpKind::SqrElementwise),
3882        Op::Sqrt => Some(OpKind::SqrtElementwise),
3883        Op::Tanh => Some(OpKind::TanhElementwise),
3884        Op::Exp => Some(OpKind::ExpElementwise),
3885        Op::Log => Some(OpKind::LogElementwise),
3886        Op::Sin => Some(OpKind::SinElementwise),
3887        Op::Cos => Some(OpKind::CosElementwise),
3888        Op::Sigmoid => Some(OpKind::SigmoidElementwise),
3889        Op::Silu => Some(OpKind::SiluElementwise),
3890        Op::GeluTanh => Some(OpKind::GeluTanhElementwise),
3891        Op::Step => Some(OpKind::StepElementwise),
3892        Op::Recip => Some(OpKind::RecipElementwise),
3893        Op::Abs => Some(OpKind::AbsElementwise),
3894        Op::Equal => Some(OpKind::EqualElementwise),
3895        Op::Ne => Some(OpKind::NotEqualElementwise),
3896        Op::Lt => Some(OpKind::LessElementwise),
3897        Op::Le => Some(OpKind::LessEqualElementwise),
3898        Op::Gt => Some(OpKind::GreaterElementwise),
3899        Op::Ge => Some(OpKind::GreaterEqualElementwise),
3900        Op::Where => Some(OpKind::Where),
3901        Op::Floor => Some(OpKind::FloorElementwise),
3902        Op::Ceil => Some(OpKind::CeilElementwise),
3903        Op::Round => Some(OpKind::RoundElementwise),
3904        Op::Sign => Some(OpKind::SignElementwise),
3905        Op::Erf => Some(OpKind::ErfElementwise),
3906        Op::Gelu => Some(OpKind::GeluElementwise),
3907        Op::Pow => Some(OpKind::PowElementwise),
3908        Op::Rsqrt => Some(OpKind::RsqrtElementwise),
3909        Op::Rem => Some(OpKind::RemElementwise),
3910        Op::Flip { .. } => Some(OpKind::Flip),
3911        Op::Roll { .. } => Some(OpKind::Roll),
3912        Op::CumSum { .. } => Some(OpKind::CumSum),
3913        Op::Triu { .. } => Some(OpKind::Triu),
3914        Op::Tril { .. } => Some(OpKind::Tril),
3915        Op::LogSoftmaxLastDim => Some(OpKind::LogSoftmaxLastDim),
3916        Op::LogSoftmaxLastDimBackward => Some(OpKind::LogSoftmaxLastDimBackward),
3917        Op::MaskedFill { .. } => Some(OpKind::MaskedFill),
3918        Op::Pad { .. } => Some(OpKind::Pad),
3919        Op::PadBackward { .. } => Some(OpKind::PadBackward),
3920        Op::SumDim(_) => Some(OpKind::SumReduce),
3921        Op::MaxDim(_) => Some(OpKind::MaxReduce),
3922        Op::MinDim(_) => Some(OpKind::MinReduce),
3923        Op::MeanDim(_) => Some(OpKind::MeanReduce),
3924        Op::SumAll => Some(OpKind::SumReduce),
3925        Op::MaxAll => Some(OpKind::MaxReduce),
3926        Op::MinAll => Some(OpKind::MinReduce),
3927        Op::MeanAll => Some(OpKind::MeanReduce),
3928        Op::MatMul => Some(OpKind::MatMul),
3929        Op::Cast(_) => Some(OpKind::Cast),
3930        // Phase 7.6 step 5: fused-op dispatch routes through
3931        // `Op::Fused(fid, _)`; the legacy `Op::Conv2D` /
3932        // `Op::FusedLinear` / `Op::SoftmaxLastDim` /
3933        // `Op::RmsNormLastDim` / `Op::LayerNormLastDim` / `Op::Rope`
3934        // arms were dropped together with the variants.
3935        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::CONV2D => Some(OpKind::Conv2D),
3936        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::CONV2D_EPILOGUE => {
3937            Some(OpKind::Conv2DEpilogue)
3938        }
3939        // Phase 7.6 step 5 (final): legacy `Op::ConvTranspose2D` /
3940        // `Op::FlashAttn` / `Op::PagedAttn` arms dropped with the
3941        // variants; dispatch flows only through `Op::Fused`.
3942        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D => {
3943            Some(OpKind::ConvTranspose2D)
3944        }
3945        Op::ReduceSumTo(_) => Some(OpKind::ReduceSumTo),
3946        Op::ReduceMaxTo(_) => Some(OpKind::ReduceMaxTo),
3947        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::FLASH_ATTN => {
3948            Some(OpKind::FlashAttn)
3949        }
3950        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::PAGED_ATTN => {
3951            Some(OpKind::PagedAttn)
3952        }
3953        Op::AddScalar(_) => Some(OpKind::Affine),
3954        Op::MulScalar(_) => Some(OpKind::Affine),
3955        Op::Clamp { .. } => Some(OpKind::ClampElementwise),
3956        Op::PowI(_) => Some(OpKind::PowIElementwise),
3957        Op::Maximum => Some(OpKind::MaximumElementwise),
3958        Op::Minimum => Some(OpKind::MinimumElementwise),
3959        Op::Concat { .. } => Some(OpKind::Concat),
3960        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM => {
3961            Some(OpKind::SoftmaxLastDim)
3962        }
3963        // Phase 7.6 step 6 follow-up: backward helpers now route
3964        // through the byte-level binding table too.
3965        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM_BACKWARD => {
3966            Some(OpKind::SoftmaxLastDimBackward)
3967        }
3968        Op::Fused(fid, _)
3969            if *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM_BACKWARD =>
3970        {
3971            Some(OpKind::LayerNormLastDimBackward)
3972        }
3973        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM_BACKWARD => {
3974            Some(OpKind::RmsNormLastDimBackward)
3975        }
3976        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::REDUCE_MAX_TO_BACKWARD => {
3977            Some(OpKind::ReduceMaxToBackward)
3978        }
3979        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::POWI_BACKWARD => {
3980            Some(OpKind::PowIElementwiseBackward)
3981        }
3982        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::FUSED_LINEAR => {
3983            Some(OpKind::FusedLinear)
3984        }
3985        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::ROW_SCALED_MATMUL => {
3986            Some(OpKind::RowScaledMatMul)
3987        }
3988        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::TOP_K_LAST_DIM => {
3989            Some(OpKind::TopKLastDim)
3990        }
3991        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::MATMUL_TOP_K => {
3992            Some(OpKind::MatMulTopK)
3993        }
3994        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM => {
3995            Some(OpKind::RmsNormLastDim)
3996        }
3997        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM => {
3998            Some(OpKind::LayerNormLastDim)
3999        }
4000        Op::IndexSelect { .. } => Some(OpKind::IndexSelect),
4001        Op::Gather { .. } => Some(OpKind::Gather),
4002        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::ROPE => Some(OpKind::Rope),
4003        Op::IndexAdd { .. } => Some(OpKind::IndexAdd),
4004        Op::ScatterAdd { .. } => Some(OpKind::ScatterAdd),
4005        Op::NonZeroIndices { .. } => Some(OpKind::NonZeroIndices),
4006        Op::ArgMaxDim(_) => Some(OpKind::ArgMaxDim),
4007        Op::ArgMinDim(_) => Some(OpKind::ArgMinDim),
4008        // Phase 7.6 step 5 (final): legacy `Op::QMatMul` arm dropped.
4009        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::QMATMUL => {
4010            Some(OpKind::QMatMul)
4011        }
4012        Op::WriteSlice { .. } => Some(OpKind::WriteSlice),
4013        Op::WriteSliceRotating { .. } => Some(OpKind::WriteSliceRotating),
4014        Op::WriteSliceDoff { .. } => Some(OpKind::WriteSliceDoff),
4015        // Phase 2 of bridge-retirement (post-9c): Op::Copy dispatches
4016        // through the binding table at OpKind::Copy. The BackendId
4017        // axis encodes the source backend (the kernel runs there —
4018        // download from local memory). The executor handles output
4019        // allocation on the target via a dedicated WorkItemKind::Copy
4020        // arm, since target_location differs from target_backend for
4021        // this op (the only one with that property today).
4022        Op::Copy { .. } => Some(OpKind::Copy),
4023        // Op::Move dispatches the same data-movement kernel as
4024        // Op::Copy — the destructive release of the source is
4025        // realize-loop bookkeeping (`destructive_input` cleanup), not
4026        // a kernel. Same OpKind, same source-backend key convention.
4027        // `compile_plan` skips both (residency-determined, not a
4028        // picker decision).
4029        Op::Move { .. } => Some(OpKind::Copy),
4030        // Phase 3 of the in-place ops infrastructure: each in-place Op
4031        // variant maps to its OpKind so the binding-table dispatch can
4032        // resolve a kernel. The executor's dedicated WorkItemKind
4033        // arms (added alongside) handle the storage-Arc adoption.
4034        Op::ReluInplace => Some(OpKind::ReluInplace),
4035        Op::SiluInplace => Some(OpKind::SiluInplace),
4036        Op::GeluTanhInplace => Some(OpKind::GeluTanhInplace),
4037        Op::TanhInplace => Some(OpKind::TanhInplace),
4038        Op::SigmoidInplace => Some(OpKind::SigmoidInplace),
4039        Op::NegInplace => Some(OpKind::NegInplace),
4040        Op::AbsInplace => Some(OpKind::AbsInplace),
4041        Op::SqrInplace => Some(OpKind::SqrInplace),
4042        Op::SqrtInplace => Some(OpKind::SqrtInplace),
4043        Op::RsqrtInplace => Some(OpKind::RsqrtInplace),
4044        Op::RecipInplace => Some(OpKind::RecipInplace),
4045        Op::ExpInplace => Some(OpKind::ExpInplace),
4046        Op::LogInplace => Some(OpKind::LogInplace),
4047        Op::SinInplace => Some(OpKind::SinInplace),
4048        Op::CosInplace => Some(OpKind::CosInplace),
4049        Op::SignInplace => Some(OpKind::SignInplace),
4050        Op::FloorInplace => Some(OpKind::FloorInplace),
4051        Op::CeilInplace => Some(OpKind::CeilInplace),
4052        Op::RoundInplace => Some(OpKind::RoundInplace),
4053        Op::ErfInplace => Some(OpKind::ErfInplace),
4054        Op::GeluInplace => Some(OpKind::GeluInplace),
4055        Op::ClampInplace { .. } => Some(OpKind::ClampInplace),
4056        Op::PowIInplace(_) => Some(OpKind::PowIInplace),
4057        // In-place binary variants (Add/Sub/Mul/Div/MaskedFill) and
4058        // their OpKind siblings are tracked by a parallel session and
4059        // toggle in and out of the Op enum as that work progresses.
4060        // No multi-output arm references them; nothing to map here in
4061        // the current HEAD.
4062        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::INPLACE_AFFINE => {
4063            Some(OpKind::InplaceAffine)
4064        }
4065        Op::Fused(fid, _)
4066            if *fid == fuel_graph::registry::FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY =>
4067        {
4068            Some(OpKind::FusedSoftmaxCrossEntropy)
4069        }
4070        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::CAUSAL_CONV1D => {
4071            Some(OpKind::CausalConv1d)
4072        }
4073        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SELECTIVE_SCAN => {
4074            Some(OpKind::SelectiveScan)
4075        }
4076        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SSD_CHUNK_SCAN => {
4077            Some(OpKind::SsdChunkScan)
4078        }
4079        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::NF4_MATMUL => {
4080            Some(OpKind::Nf4Matmul)
4081        }
4082        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::AWQ_MATMUL => {
4083            Some(OpKind::AwqMatmul)
4084        }
4085        // Phase 3a (post-9c): Op::Alloc + Op::ZeroFill are structural
4086        // ops dispatched directly via `WorkItemKind::Alloc` /
4087        // `WorkItemKind::ZeroFill` (no binding-table lookup).
4088        // `compile_plan` skips these.
4089        Op::Alloc { .. } | Op::ZeroFill => None,
4090        _ => None,
4091    }
4092}
4093
4094/// Build the [`OpParams`] for `node`'s op. Most ops use
4095/// `OpParams::None`; reductions / matmul / conv / slice carry their
4096/// op-specific extras here. The graph is consulted to read input
4097/// shapes (e.g. reductions need the input shape to walk the
4098/// multi-index — Storage only carries bytes + dtype).
4099///
4100/// Phase C — extends as op families migrate. Returns Err if a
4101/// graph-shape lookup fails (currently can't, but the signature is
4102/// `Result` so future cases needing validation slot in cleanly).
4103/// Encode an `f64` value into the byte pattern of `dtype`. Used by
4104/// `Op::Pad` (Constant mode) to pre-convert the fill value once at
4105/// op_params time, so the kernel itself stays dtype-agnostic.
4106fn encode_value_to_bytes(dtype: DType, value: f64) -> Result<Vec<u8>> {
4107    match dtype {
4108        DType::F32 => Ok((value as f32).to_le_bytes().to_vec()),
4109        DType::F64 => Ok(value.to_le_bytes().to_vec()),
4110        DType::BF16 => Ok(half::bf16::from_f32(value as f32).to_le_bytes().to_vec()),
4111        DType::F16 => Ok(half::f16::from_f32(value as f32).to_le_bytes().to_vec()),
4112        DType::U8 => Ok(vec![value as u8]),
4113        DType::U32 => Ok((value as u32).to_le_bytes().to_vec()),
4114        other => Err(Error::Msg(format!(
4115            "encode_value_to_bytes: dtype {other:?} not yet supported for Pad fill",
4116        ))
4117        .bt()),
4118    }
4119}
4120
4121/// Encode a typed `Scalar` to its little-endian byte representation.
4122/// Used by Op::MaskedFill so the kernel only sees bytes — never has
4123/// to know the value's dtype.
4124fn scalar_to_bytes(s: fuel_ir::Scalar) -> Vec<u8> {
4125    use fuel_ir::Scalar;
4126    match s {
4127        Scalar::U8(v) => vec![v],
4128        Scalar::I8(v) => vec![v as u8],
4129        Scalar::U32(v) => v.to_le_bytes().to_vec(),
4130        Scalar::I16(v) => v.to_le_bytes().to_vec(),
4131        Scalar::I32(v) => v.to_le_bytes().to_vec(),
4132        Scalar::I64(v) => v.to_le_bytes().to_vec(),
4133        Scalar::BF16(v) => v.to_le_bytes().to_vec(),
4134        Scalar::F16(v) => v.to_le_bytes().to_vec(),
4135        Scalar::F32(v) => v.to_le_bytes().to_vec(),
4136        Scalar::F64(v) => v.to_le_bytes().to_vec(),
4137        Scalar::Bool(b) => vec![b as u8],
4138        Scalar::F8E4M3(v) => vec![v.to_bits()],
4139        Scalar::F8E5M2(v) => vec![v.to_bits()],
4140        // OCP-MX E8M0 block scale is a raw byte on the wire (`2^(X-127)`,
4141        // decoded kernel-side); a single byte is its own LE encoding.
4142        Scalar::F8E8M0(v) => vec![v],
4143    }
4144}
4145
4146fn op_to_op_params(
4147    graph: &Graph,
4148    node: &Node,
4149    node_id: NodeId,
4150    layout_cache: &HashMap<NodeId, Layout>,
4151    sym_env: &SymEnv,
4152) -> Result<OpParams> {
4153    // Helper: read an input's layout from the compiler-thread-local
4154    // cache (which is current within the realize call), falling back
4155    // to the graph's side-table if the input wasn't visited (which
4156    // shouldn't happen in topo order, but the fallback keeps the
4157    // path safe).
4158    let input_layout = |input_id: NodeId| -> Layout {
4159        layout_cache
4160            .get(&input_id)
4161            .cloned()
4162            .unwrap_or_else(|| graph.layout(input_id))
4163    };
4164    Ok(match &node.op {
4165        // Phase 7.6 step 5 (final): legacy `Op::QMatMul` arm dropped.
4166        Op::Fused(_, fuel_graph::registry::FusedOpParams::QMatMul { quant_type, k, n }) => {
4167            // Inputs: (activations f32 [..., m, k], weight_bytes
4168            // u32-typed). Output shape (this Node's shape) is
4169            // [..., m, n]. Flatten leading dims into batch_count.
4170            if node.inputs.len() != 2 {
4171                return Err(Error::Msg(format!(
4172                    "Op::QMatMul expects 2 inputs (activations, weight_bytes), got {}",
4173                    node.inputs.len(),
4174                ))
4175                .bt());
4176            }
4177            let act_layout = input_layout(node.inputs[0]);
4178            let act_dims = act_layout.shape().dims();
4179            if act_dims.len() < 2 {
4180                return Err(Error::Msg(format!(
4181                    "Op::QMatMul: activations must be rank ≥ 2, got {act_dims:?}",
4182                ))
4183                .bt());
4184            }
4185            let m = act_dims[act_dims.len() - 2];
4186            let k_act = act_dims[act_dims.len() - 1];
4187            if k_act != *k {
4188                return Err(Error::Msg(format!(
4189                    "Op::QMatMul: activation last dim ({k_act}) must equal Op's k ({k})",
4190                ))
4191                .bt());
4192            }
4193            let batch_count: usize = act_dims[..act_dims.len() - 2].iter().product();
4194            OpParams::QMatMul {
4195                quant_type: *quant_type,
4196                batch_count,
4197                m,
4198                n: *n,
4199                k: *k,
4200            }
4201        }
4202        Op::ArgMaxDim(d) | Op::ArgMinDim(d) => {
4203            // Reuse OpParams::Reduce — same shape contract; the
4204            // single reduce dim is the argmax/argmin axis. Input
4205            // layout flows through KernelRef's `layouts[0]`.
4206            OpParams::Reduce {
4207                dims: vec![*d],
4208                keepdim: false,
4209            }
4210        }
4211        Op::SumDim(d) | Op::MaxDim(d) | Op::MinDim(d) | Op::MeanDim(d) => OpParams::Reduce {
4212            dims: vec![*d],
4213            keepdim: false,
4214        },
4215        Op::SumAll | Op::MaxAll | Op::MinAll | Op::MeanAll => {
4216            let il = input_layout(node.inputs[0]);
4217            let rank = il.shape().rank();
4218            OpParams::Reduce {
4219                dims: (0..rank).collect(),
4220                keepdim: false,
4221            }
4222        }
4223        Op::MatMul => {
4224            // Batched matmul: lhs `[..lhs_batch.., m, k]` @
4225            // rhs `[..rhs_batch.., k, n]` → out `[..lhs_batch.., m, n]`.
4226            // Per-axis the batch dims either match or follow GQA-style
4227            // divisibility (lhs_dim > rhs_dim && lhs_dim % rhs_dim == 0);
4228            // the kernel honors the latter via `rhs_idx = lhs_idx / n_rep`.
4229            if node.inputs.len() != 2 {
4230                return Err(Error::Msg(format!(
4231                    "Op::MatMul expects 2 inputs, got {}",
4232                    node.inputs.len(),
4233                ))
4234                .bt());
4235            }
4236            let lhs = input_layout(node.inputs[0]);
4237            let rhs = input_layout(node.inputs[1]);
4238            let lhs_dims = lhs.shape().dims();
4239            let rhs_dims = rhs.shape().dims();
4240            if lhs_dims.len() < 2 || rhs_dims.len() < 2 {
4241                return Err(Error::Msg(format!(
4242                    "Op::MatMul requires both inputs rank ≥ 2; got lhs={:?} rhs={:?}",
4243                    lhs_dims, rhs_dims,
4244                ))
4245                .bt());
4246            }
4247            if lhs_dims.len() != rhs_dims.len() {
4248                return Err(Error::Msg(format!(
4249                    "Op::MatMul: ranks must match (auto-broadcast happens at \
4250                     graph construction time); got lhs rank {} vs rhs rank {}",
4251                    lhs_dims.len(),
4252                    rhs_dims.len(),
4253                ))
4254                .bt());
4255            }
4256            let rank = lhs_dims.len();
4257            let batch_rank = rank - 2;
4258            // Per-axis validation: equal or GQA-divisible.
4259            for i in 0..batch_rank {
4260                let la = lhs_dims[i];
4261                let ra = rhs_dims[i];
4262                let ok = la == ra || (ra > 0 && la > ra && la % ra == 0);
4263                if !ok {
4264                    return Err(Error::Msg(format!(
4265                        "Op::MatMul: batch dim {i} disallowed combination \
4266                         (lhs={la}, rhs={ra}); must be equal or \
4267                         GQA-divisible (lhs > rhs && lhs % rhs == 0)",
4268                    ))
4269                    .bt());
4270                }
4271            }
4272            let lhs_batch_dims: Vec<usize> = lhs_dims[..batch_rank].to_vec();
4273            let rhs_batch_dims: Vec<usize> = rhs_dims[..batch_rank].to_vec();
4274            let (m, k_lhs) = (lhs_dims[rank - 2], lhs_dims[rank - 1]);
4275            let (k_rhs, n) = (rhs_dims[rank - 2], rhs_dims[rank - 1]);
4276            if k_lhs != k_rhs {
4277                return Err(Error::Msg(format!(
4278                    "Op::MatMul: contracting dims disagree — lhs trailing is \
4279                     [{m}, {k_lhs}], rhs trailing is [{k_rhs}, {n}]",
4280                ))
4281                .bt());
4282            }
4283            // Data-determined-M (sparse-MoE): a side-table row count makes
4284            // `m` the capacity and this the compute count. Dual-path,
4285            // mirroring WriteSlice: resolve in the compile-time SymEnv
4286            // (static / input-determined) now; else DEFER a producer-bound
4287            // sym to execute; else it is a genuine caller error.
4288            let m_compute = match graph.matmul_row_count(node_id) {
4289                None => MatmulM::All,
4290                Some(dyn_m) => match dyn_m.resolve(sym_env) {
4291                    Some(c) => {
4292                        if c > m {
4293                            return Err(Error::Msg(format!(
4294                                "Op::MatMul: resolved row count {c} exceeds capacity {m}",
4295                            ))
4296                            .bt());
4297                        }
4298                        MatmulM::Rows(c)
4299                    }
4300                    None => match dyn_m {
4301                        fuel_ir::DynScalar::Sym(s) if graph.binds_data_determined_sym(s) => {
4302                            MatmulM::Deferred(dyn_m)
4303                        }
4304                        _ => {
4305                            return Err(Error::Msg(format!(
4306                                "Op::MatMul: dynamic row count {dyn_m:?} is unbound in the \
4307                                 SymEnv at compile and no producer binds it (not \
4308                                 data-determined)",
4309                            ))
4310                            .bt());
4311                        }
4312                    },
4313                },
4314            };
4315            OpParams::Matmul {
4316                lhs_batch_dims,
4317                rhs_batch_dims,
4318                m,
4319                n,
4320                k: k_lhs,
4321                m_compute,
4322            }
4323        }
4324        // Phase 7.6 step 4: legacy `Op::FusedLinear` and registry-extended
4325        // `Op::Fused(FUSED_LINEAR, _)` share the same shape contract and
4326        // params encoding (reuses OpParams::Matmul). One body covers both.
4327        op if op_is_fused_linear(op) || op_is_row_scaled_matmul(op) => {
4328            // Inputs: [a, b, bias]. Same shape semantics as MatMul on
4329            // a/b; bias is rank-1 [N] and broadcasts along all leading
4330            // dims. We reuse OpParams::Matmul (kernel reads bias from
4331            // inputs[2] directly).
4332            if node.inputs.len() != 3 {
4333                return Err(Error::Msg(format!(
4334                    "Op::FusedLinear expects 3 inputs (a, b, bias), got {}",
4335                    node.inputs.len(),
4336                ))
4337                .bt());
4338            }
4339            let lhs = input_layout(node.inputs[0]);
4340            let rhs = input_layout(node.inputs[1]);
4341            let bias = input_layout(node.inputs[2]);
4342            let lhs_dims = lhs.shape().dims();
4343            let rhs_dims = rhs.shape().dims();
4344            let bias_dims = bias.shape().dims();
4345            if lhs_dims.len() < 2 || rhs_dims.len() < 2 {
4346                return Err(Error::Msg(format!(
4347                    "Op::FusedLinear requires both a, b rank ≥ 2; got a={:?} b={:?}",
4348                    lhs_dims, rhs_dims,
4349                ))
4350                .bt());
4351            }
4352            if lhs_dims.len() != rhs_dims.len() {
4353                return Err(Error::Msg(format!(
4354                    "Op::FusedLinear: ranks must match (auto-broadcast happens at \
4355                     graph construction time); got a rank {} vs b rank {}",
4356                    lhs_dims.len(),
4357                    rhs_dims.len(),
4358                ))
4359                .bt());
4360            }
4361            let rank = lhs_dims.len();
4362            let batch_rank = rank - 2;
4363            for i in 0..batch_rank {
4364                let la = lhs_dims[i];
4365                let ra = rhs_dims[i];
4366                let ok = la == ra || (ra > 0 && la > ra && la % ra == 0);
4367                if !ok {
4368                    return Err(Error::Msg(format!(
4369                        "Op::FusedLinear: batch dim {i} disallowed (a={la}, b={ra})",
4370                    ))
4371                    .bt());
4372                }
4373            }
4374            let lhs_batch_dims: Vec<usize> = lhs_dims[..batch_rank].to_vec();
4375            let rhs_batch_dims: Vec<usize> = rhs_dims[..batch_rank].to_vec();
4376            let (m, k_lhs) = (lhs_dims[rank - 2], lhs_dims[rank - 1]);
4377            let (k_rhs, n) = (rhs_dims[rank - 2], rhs_dims[rank - 1]);
4378            if k_lhs != k_rhs {
4379                return Err(Error::Msg(format!(
4380                    "Op::FusedLinear: contracting dims disagree — a trailing is \
4381                     [{m}, {k_lhs}], b trailing is [{k_rhs}, {n}]",
4382                ))
4383                .bt());
4384            }
4385            if op_is_row_scaled_matmul(&node.op) {
4386                // The row scale is `[..lhs batch, M, 1]`.
4387                let mut want = lhs_batch_dims.clone();
4388                want.push(m);
4389                want.push(1);
4390                if bias_dims != want.as_slice() {
4391                    return Err(Error::Msg(format!(
4392                        "Op::RowScaledMatMul: row_scale must be {want:?}, got {bias_dims:?}",
4393                    ))
4394                    .bt());
4395                }
4396            } else if bias_dims.len() != 1 || bias_dims[0] != n {
4397                return Err(Error::Msg(format!(
4398                    "Op::FusedLinear: bias must be rank-1 [{n}], got {bias_dims:?}",
4399                ))
4400                .bt());
4401            }
4402            OpParams::Matmul {
4403                lhs_batch_dims,
4404                rhs_batch_dims,
4405                m,
4406                n,
4407                k: k_lhs,
4408                // FusedLinear is always static-M (dense linear layer).
4409                m_compute: MatmulM::All,
4410            }
4411        }
4412        // FusedSoftmaxCrossEntropy: flatten logits `[..., V]` to
4413        // `[n_rows, V]` for the kernel. n_rows is the product of all
4414        // leading dims (≥1 even for rank-1 logits, where targets are
4415        // a scalar). The kernel walks rows internally.
4416        Op::Fused(
4417            _,
4418            fuel_graph::registry::FusedOpParams::FusedSoftmaxCrossEntropy {
4419                reduction,
4420                ignore_index,
4421            },
4422        ) => {
4423            if node.inputs.len() != 2 {
4424                return Err(Error::Msg(format!(
4425                    "FusedSoftmaxCrossEntropy expects 2 inputs (logits, targets), got {}",
4426                    node.inputs.len(),
4427                ))
4428                .bt());
4429            }
4430            let logits_layout = input_layout(node.inputs[0]);
4431            let logits_dims = logits_layout.shape().dims();
4432            if logits_dims.is_empty() {
4433                return Err(Error::Msg(
4434                    "FusedSoftmaxCrossEntropy: logits must have rank ≥ 1".to_string(),
4435                )
4436                .bt());
4437            }
4438            let vocab = *logits_dims.last().unwrap();
4439            let n_rows: usize = logits_dims[..logits_dims.len() - 1]
4440                .iter()
4441                .product::<usize>()
4442                .max(1);
4443            let targets_layout = input_layout(node.inputs[1]);
4444            let target_count: usize = targets_layout
4445                .shape()
4446                .dims()
4447                .iter()
4448                .product::<usize>()
4449                .max(1);
4450            if target_count != n_rows {
4451                return Err(Error::Msg(format!(
4452                    "FusedSoftmaxCrossEntropy: targets element count {target_count} must \
4453                     equal logits row count {n_rows} (logits {logits_dims:?}, targets {:?})",
4454                    targets_layout.shape().dims(),
4455                ))
4456                .bt());
4457            }
4458            OpParams::FusedSoftmaxCrossEntropy {
4459                n_rows,
4460                vocab,
4461                reduction: *reduction,
4462                ignore_index: *ignore_index,
4463            }
4464        }
4465        // CausalConv1d: derive (batch, channels, seq_in, seq_out, kernel)
4466        // from the input layouts. x is `[batch, channels, seq_in]`
4467        // (caller pre-pads with kernel-1 zeros), weight is
4468        // `[channels, 1, kernel]`. seq_out = seq_in - (kernel - 1).
4469        Op::Fused(_, fuel_graph::registry::FusedOpParams::CausalConv1d { use_silu }) => {
4470            if node.inputs.len() != 3 {
4471                return Err(Error::Msg(format!(
4472                    "CausalConv1d expects 3 inputs (x, weight, bias), got {}",
4473                    node.inputs.len(),
4474                ))
4475                .bt());
4476            }
4477            let x_layout = input_layout(node.inputs[0]);
4478            let w_layout = input_layout(node.inputs[1]);
4479            let x_dims = x_layout.shape().dims();
4480            let w_dims = w_layout.shape().dims();
4481            if x_dims.len() != 3 {
4482                return Err(Error::Msg(format!(
4483                    "CausalConv1d: x must be rank 3 [batch, channels, seq+pad], got {x_dims:?}",
4484                ))
4485                .bt());
4486            }
4487            if w_dims.len() != 3 {
4488                return Err(Error::Msg(format!(
4489                    "CausalConv1d: weight must be rank 3 [channels, 1, kernel], got {w_dims:?}",
4490                ))
4491                .bt());
4492            }
4493            let batch = x_dims[0];
4494            let channels = x_dims[1];
4495            let seq_in = x_dims[2];
4496            let kernel = w_dims[2];
4497            if seq_in < kernel - 1 {
4498                return Err(Error::Msg(format!(
4499                    "CausalConv1d: x time dim {seq_in} must be ≥ kernel-1 = {} \
4500                     (caller must pre-pad with kernel-1 zeros)",
4501                    kernel - 1,
4502                ))
4503                .bt());
4504            }
4505            let seq_out = seq_in - (kernel - 1);
4506            OpParams::CausalConv1d {
4507                batch,
4508                channels,
4509                seq_in,
4510                seq_out,
4511                kernel,
4512                use_silu: *use_silu,
4513            }
4514        }
4515        // SelectiveScan: derive (batch, seqlen, dim, dstate) from the
4516        // input layouts. u: [batch, seqlen, dim]; a: [dim, dstate].
4517        Op::Fused(_, fuel_graph::registry::FusedOpParams::SelectiveScan { delta_softplus }) => {
4518            if node.inputs.len() != 5 {
4519                return Err(Error::Msg(format!(
4520                    "SelectiveScan expects 5 inputs (u, delta, a, b, c), got {}",
4521                    node.inputs.len(),
4522                ))
4523                .bt());
4524            }
4525            let u_layout = input_layout(node.inputs[0]);
4526            let a_layout = input_layout(node.inputs[2]);
4527            let u_dims = u_layout.shape().dims();
4528            let a_dims = a_layout.shape().dims();
4529            if u_dims.len() != 3 {
4530                return Err(Error::Msg(format!(
4531                    "SelectiveScan: u must be rank 3 [batch, seqlen, dim], got {u_dims:?}",
4532                ))
4533                .bt());
4534            }
4535            if a_dims.len() != 2 {
4536                return Err(Error::Msg(format!(
4537                    "SelectiveScan: a must be rank 2 [dim, dstate], got {a_dims:?}",
4538                ))
4539                .bt());
4540            }
4541            let batch = u_dims[0];
4542            let seqlen = u_dims[1];
4543            let dim = u_dims[2];
4544            let dstate = a_dims[1];
4545            if a_dims[0] != dim {
4546                return Err(Error::Msg(format!(
4547                    "SelectiveScan: a's first dim {} must equal dim {dim}",
4548                    a_dims[0],
4549                ))
4550                .bt());
4551            }
4552            OpParams::SelectiveScan {
4553                batch,
4554                seqlen,
4555                dim,
4556                dstate,
4557                delta_softplus: *delta_softplus,
4558            }
4559        }
4560        // SsdChunkScan: derive (batch, seqlen, heads, head_dim,
4561        // state_dim) from x and b layouts. x: [batch, seqlen, heads,
4562        // head_dim]; b: [batch, seqlen, heads, state_dim].
4563        Op::Fused(_, fuel_graph::registry::FusedOpParams::SsdChunkScan { chunk_size }) => {
4564            if node.inputs.len() != 5 {
4565                return Err(Error::Msg(format!(
4566                    "SsdChunkScan expects 5 inputs (x, dt, a, b, c), got {}",
4567                    node.inputs.len(),
4568                ))
4569                .bt());
4570            }
4571            let x_layout = input_layout(node.inputs[0]);
4572            let b_layout = input_layout(node.inputs[3]);
4573            let x_dims = x_layout.shape().dims();
4574            let b_dims = b_layout.shape().dims();
4575            if x_dims.len() != 4 {
4576                return Err(Error::Msg(format!(
4577                    "SsdChunkScan: x must be rank 4 [batch, seqlen, heads, head_dim], got {x_dims:?}",
4578                ))
4579                .bt());
4580            }
4581            if b_dims.len() != 4 {
4582                return Err(Error::Msg(format!(
4583                    "SsdChunkScan: b must be rank 4 [batch, seqlen, heads, state_dim], got {b_dims:?}",
4584                ))
4585                .bt());
4586            }
4587            let batch = x_dims[0];
4588            let seqlen = x_dims[1];
4589            let heads = x_dims[2];
4590            let head_dim = x_dims[3];
4591            let state_dim = b_dims[3];
4592            OpParams::SsdChunkScan {
4593                batch,
4594                seqlen,
4595                heads,
4596                head_dim,
4597                state_dim,
4598                chunk_size: *chunk_size,
4599            }
4600        }
4601        // Nf4Matmul: derive (batch, m, n, k) from activations + w_packed
4602        // layouts. activations: [..., m, k] (leading dims flatten into
4603        // batch); w_packed: [n, k/2] U8.
4604        Op::Fused(_, fuel_graph::registry::FusedOpParams::Nf4Matmul { block_size }) => {
4605            if node.inputs.len() != 3 {
4606                return Err(Error::Msg(format!(
4607                    "Nf4Matmul expects 3 inputs (activations, w_packed, absmax), got {}",
4608                    node.inputs.len(),
4609                ))
4610                .bt());
4611            }
4612            let a_layout = input_layout(node.inputs[0]);
4613            let w_layout = input_layout(node.inputs[1]);
4614            let a_dims = a_layout.shape().dims();
4615            let w_dims = w_layout.shape().dims();
4616            if a_dims.len() < 2 {
4617                return Err(Error::Msg(format!(
4618                    "Nf4Matmul: activations must be rank ≥ 2, got {a_dims:?}",
4619                ))
4620                .bt());
4621            }
4622            if w_dims.len() != 2 {
4623                return Err(Error::Msg(format!(
4624                    "Nf4Matmul: w_packed must be rank 2 [n, k/2], got {w_dims:?}",
4625                ))
4626                .bt());
4627            }
4628            let m = a_dims[a_dims.len() - 2];
4629            let k = a_dims[a_dims.len() - 1];
4630            let n = w_dims[0];
4631            let batch: usize = a_dims[..a_dims.len() - 2].iter().product::<usize>().max(1);
4632            if k % 2 != 0 {
4633                return Err(Error::Msg(format!(
4634                    "Nf4Matmul: k={k} must be even (w_packed holds 2 nibbles per byte along k)",
4635                ))
4636                .bt());
4637            }
4638            if k % *block_size != 0 {
4639                return Err(Error::Msg(format!(
4640                    "Nf4Matmul: k={k} must be a multiple of block_size={block_size}",
4641                ))
4642                .bt());
4643            }
4644            if w_dims[1] != k / 2 {
4645                return Err(Error::Msg(format!(
4646                    "Nf4Matmul: w_packed second dim {} must equal k/2 = {}",
4647                    w_dims[1],
4648                    k / 2,
4649                ))
4650                .bt());
4651            }
4652            OpParams::Nf4Matmul {
4653                batch,
4654                m,
4655                n,
4656                k,
4657                block_size: *block_size,
4658            }
4659        }
4660        // TopKLastDim (row 172 item 2): `rows` = product of the leading dims,
4661        // `n` = the last axis, `k` from the node's params (validated at build time).
4662        Op::Fused(fid, fp) if *fid == fuel_graph::registry::FusedOps::TOP_K_LAST_DIM => {
4663            let fuel_graph::registry::FusedOpParams::TopKLastDim { k } = fp else {
4664                return Err(Error::Msg(format!(
4665                    "TopKLastDim: expected FusedOpParams::TopKLastDim, got {fp:?}"
4666                ))
4667                .bt());
4668            };
4669            if node.inputs.len() != 1 {
4670                return Err(Error::Msg(format!(
4671                    "TopKLastDim expects 1 input, got {}",
4672                    node.inputs.len()
4673                ))
4674                .bt());
4675            }
4676            let x = input_layout(node.inputs[0]);
4677            let dims = x.shape().dims();
4678            let Some((&n, lead)) = dims.split_last() else {
4679                return Err(Error::Msg("TopKLastDim: input must be rank >= 1".to_string()).bt());
4680            };
4681            if *k == 0 || *k > n {
4682                return Err(Error::Msg(format!("TopKLastDim: k = {k} must be in 1..={n}")).bt());
4683            }
4684            OpParams::TopKLastDim {
4685                rows: lead.iter().product::<usize>().max(1),
4686                n,
4687                k: *k,
4688            }
4689        }
4690        // MatMulTopK (row 172 item 2 step B): a [.., m, k] @ b [.., k, n], equal
4691        // batch dims, then top_k over n.
4692        Op::Fused(fid, fp) if *fid == fuel_graph::registry::FusedOps::MATMUL_TOP_K => {
4693            let fuel_graph::registry::FusedOpParams::MatMulTopK { k: top_k } = fp else {
4694                return Err(Error::Msg(format!(
4695                    "MatMulTopK: expected FusedOpParams::MatMulTopK, got {fp:?}"
4696                ))
4697                .bt());
4698            };
4699            if node.inputs.len() != 2 {
4700                return Err(Error::Msg(format!(
4701                    "MatMulTopK expects 2 inputs (a, b), got {}",
4702                    node.inputs.len()
4703                ))
4704                .bt());
4705            }
4706            let a = input_layout(node.inputs[0]);
4707            let b = input_layout(node.inputs[1]);
4708            let (ad, bd) = (a.shape().dims(), b.shape().dims());
4709            if ad.len() < 2 || ad.len() != bd.len() || ad[..ad.len() - 2] != bd[..bd.len() - 2] {
4710                return Err(Error::Msg(format!(
4711                    "MatMulTopK: a {ad:?} and b {bd:?} need equal rank >= 2 and equal batch dims"
4712                ))
4713                .bt());
4714            }
4715            let r = ad.len();
4716            let (m, k) = (ad[r - 2], ad[r - 1]);
4717            let (k2, n) = (bd[r - 2], bd[r - 1]);
4718            if k != k2 {
4719                return Err(Error::Msg(format!(
4720                    "MatMulTopK: contracting dims disagree (a trailing [{m}, {k}], b trailing [{k2}, {n}])"
4721                ))
4722                .bt());
4723            }
4724            if *top_k == 0 || *top_k > n {
4725                return Err(Error::Msg(format!("MatMulTopK: k = {top_k} must be in 1..={n}")).bt());
4726            }
4727            OpParams::MatMulTopK {
4728                batch: ad[..r - 2].iter().product::<usize>().max(1),
4729                m,
4730                n,
4731                k,
4732                top_k: *top_k,
4733            }
4734        }
4735        // AwqMatmul: (batch, m, n, k) from activations [..., m, k] and the
4736        // kernel-layout weight [n, k/8]; the padded zeros/scales widths are the
4737        // op's own build-time invariant (checked by `awq_matmul`).
4738        Op::Fused(
4739            _,
4740            fuel_graph::registry::FusedOpParams::AwqMatmul {
4741                group_size,
4742                split_k_iters,
4743            },
4744        ) => {
4745            if node.inputs.len() != 4 {
4746                return Err(Error::Msg(format!(
4747                    "AwqMatmul expects 4 inputs (activations, weight, zeros, scales), got {}",
4748                    node.inputs.len(),
4749                ))
4750                .bt());
4751            }
4752            let a_layout = input_layout(node.inputs[0]);
4753            let w_layout = input_layout(node.inputs[1]);
4754            let a_dims = a_layout.shape().dims();
4755            let w_dims = w_layout.shape().dims();
4756            if a_dims.len() < 2 {
4757                return Err(Error::Msg(format!(
4758                    "AwqMatmul: activations must be rank ≥ 2, got {a_dims:?}",
4759                ))
4760                .bt());
4761            }
4762            if w_dims.len() != 2 {
4763                return Err(Error::Msg(format!(
4764                    "AwqMatmul: weight must be rank 2 [n, k/8], got {w_dims:?}",
4765                ))
4766                .bt());
4767            }
4768            let m = a_dims[a_dims.len() - 2];
4769            let k = a_dims[a_dims.len() - 1];
4770            let n = w_dims[0];
4771            let batch: usize = a_dims[..a_dims.len() - 2].iter().product::<usize>().max(1);
4772            if k % 8 != 0 || w_dims[1] != k / 8 {
4773                return Err(Error::Msg(format!(
4774                    "AwqMatmul: weight second dim {} must equal k/8 for k={k} (a multiple of 8)",
4775                    w_dims[1],
4776                ))
4777                .bt());
4778            }
4779            OpParams::AwqMatmul {
4780                batch,
4781                m,
4782                n,
4783                k,
4784                group_size: *group_size,
4785                split_k_iters: *split_k_iters,
4786            }
4787        }
4788        // Phase 7.6 step 3: SoftmaxLastDim flows through
4789        // `Op::Fused(FusedOps::SOFTMAX_LAST_DIM, _)`. The
4790        // SOFTMAX_LAST_DIM_BACKWARD variant added in step 6
4791        // follow-up shares the same `outer × last_dim` shape
4792        // contract (input 0 is `y` for forward / forward-output
4793        // for backward; both rank-≥1 with last-dim as the
4794        // reduction axis).
4795        op if op_is_softmax_last_dim(op)
4796            || matches!(op, Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM_BACKWARD) =>
4797        {
4798            let il = input_layout(node.inputs[0]);
4799            let dims = il.shape().dims();
4800            if dims.is_empty() {
4801                return Err(Error::Msg("Op::SoftmaxLastDim requires rank ≥ 1".to_string()).bt());
4802            }
4803            let last_dim = *dims.last().unwrap();
4804            let outer_count: usize = dims[..dims.len() - 1].iter().product();
4805            OpParams::SoftmaxLastDim {
4806                outer_count,
4807                last_dim,
4808            }
4809        }
4810        Op::Flip { dim } => {
4811            // Single input. Precompute the flat-3-axis split
4812            // (outer × dim × inner) from the input shape.
4813            if node.inputs.len() != 1 {
4814                return Err(Error::Msg(format!(
4815                    "Op::Flip expects 1 input, got {}",
4816                    node.inputs.len(),
4817                ))
4818                .bt());
4819            }
4820            let in_layout = input_layout(node.inputs[0]);
4821            let in_dims = in_layout.shape().dims();
4822            if *dim >= in_dims.len() {
4823                return Err(Error::Msg(format!(
4824                    "Op::Flip: dim {dim} out of range for rank {}",
4825                    in_dims.len(),
4826                ))
4827                .bt());
4828            }
4829            let outer_count: usize = in_dims[..*dim].iter().product();
4830            let dim_size = in_dims[*dim];
4831            let inner_count: usize = in_dims[*dim + 1..].iter().product();
4832            OpParams::Flip {
4833                outer_count,
4834                dim_size,
4835                inner_count,
4836                axis: *dim,
4837            }
4838        }
4839        Op::Roll { dim, shift } => {
4840            if node.inputs.len() != 1 {
4841                return Err(Error::Msg(format!(
4842                    "Op::Roll expects 1 input, got {}",
4843                    node.inputs.len(),
4844                ))
4845                .bt());
4846            }
4847            let in_layout = input_layout(node.inputs[0]);
4848            let in_dims = in_layout.shape().dims();
4849            if *dim >= in_dims.len() {
4850                return Err(Error::Msg(format!(
4851                    "Op::Roll: dim {dim} out of range for rank {}",
4852                    in_dims.len(),
4853                ))
4854                .bt());
4855            }
4856            let outer_count: usize = in_dims[..*dim].iter().product();
4857            let dim_size = in_dims[*dim];
4858            let inner_count: usize = in_dims[*dim + 1..].iter().product();
4859            OpParams::Roll {
4860                outer_count,
4861                dim_size,
4862                inner_count,
4863                shift: *shift,
4864                axis: *dim,
4865            }
4866        }
4867        Op::CumSum { dim } => {
4868            if node.inputs.len() != 1 {
4869                return Err(Error::Msg(format!(
4870                    "Op::CumSum expects 1 input, got {}",
4871                    node.inputs.len(),
4872                ))
4873                .bt());
4874            }
4875            let in_layout = input_layout(node.inputs[0]);
4876            let in_dims = in_layout.shape().dims();
4877            if *dim >= in_dims.len() {
4878                return Err(Error::Msg(format!(
4879                    "Op::CumSum: dim {dim} out of range for rank {}",
4880                    in_dims.len(),
4881                ))
4882                .bt());
4883            }
4884            let outer_count: usize = in_dims[..*dim].iter().product();
4885            let dim_size = in_dims[*dim];
4886            let inner_count: usize = in_dims[*dim + 1..].iter().product();
4887            OpParams::CumSum {
4888                outer_count,
4889                dim_size,
4890                inner_count,
4891                axis: *dim,
4892            }
4893        }
4894        Op::Triu { diagonal } | Op::Tril { diagonal } => {
4895            if node.inputs.len() != 1 {
4896                return Err(Error::Msg(format!(
4897                    "Op::Triu/Tril expects 1 input, got {}",
4898                    node.inputs.len(),
4899                ))
4900                .bt());
4901            }
4902            let in_layout = input_layout(node.inputs[0]);
4903            let in_dims = in_layout.shape().dims();
4904            if in_dims.len() < 2 {
4905                return Err(Error::Msg(format!(
4906                    "Op::Triu/Tril requires rank >= 2, got {}",
4907                    in_dims.len(),
4908                ))
4909                .bt());
4910            }
4911            let rows = in_dims[in_dims.len() - 2];
4912            let cols = in_dims[in_dims.len() - 1];
4913            let batch_count: usize = in_dims[..in_dims.len() - 2]
4914                .iter()
4915                .product::<usize>()
4916                .max(1);
4917            OpParams::Triangular {
4918                batch_count,
4919                rows,
4920                cols,
4921                diagonal: *diagonal,
4922            }
4923        }
4924        Op::LogSoftmaxLastDim => {
4925            if node.inputs.len() != 1 {
4926                return Err(Error::Msg(format!(
4927                    "Op::LogSoftmaxLastDim expects 1 input, got {}",
4928                    node.inputs.len(),
4929                ))
4930                .bt());
4931            }
4932            let in_layout = input_layout(node.inputs[0]);
4933            let in_dims = in_layout.shape().dims();
4934            if in_dims.is_empty() {
4935                return Err(Error::Msg("Op::LogSoftmaxLastDim requires rank ≥ 1".to_string()).bt());
4936            }
4937            let last_dim = *in_dims.last().unwrap();
4938            let outer_count: usize = in_dims[..in_dims.len() - 1].iter().product();
4939            OpParams::LogSoftmaxLastDim {
4940                outer_count,
4941                last_dim,
4942            }
4943        }
4944        Op::LogSoftmaxLastDimBackward => {
4945            // Inputs: (forward_output_y, upstream_grad). Same shape contract
4946            // as SoftmaxLastDimBackward — last-dim row-wise dispatch.
4947            if node.inputs.len() != 2 {
4948                return Err(Error::Msg(format!(
4949                    "Op::LogSoftmaxLastDimBackward expects 2 inputs, got {}",
4950                    node.inputs.len(),
4951                ))
4952                .bt());
4953            }
4954            let in_layout = input_layout(node.inputs[0]);
4955            let in_dims = in_layout.shape().dims();
4956            if in_dims.is_empty() {
4957                return Err(Error::Msg(
4958                    "Op::LogSoftmaxLastDimBackward requires rank ≥ 1".to_string(),
4959                )
4960                .bt());
4961            }
4962            let last_dim = *in_dims.last().unwrap();
4963            let outer_count: usize = in_dims[..in_dims.len() - 1].iter().product();
4964            OpParams::LogSoftmaxLastDim {
4965                outer_count,
4966                last_dim,
4967            }
4968        }
4969        Op::MaskedFill { value } => {
4970            if node.inputs.len() != 2 {
4971                return Err(Error::Msg(format!(
4972                    "Op::MaskedFill expects 2 inputs (x, mask), got {}",
4973                    node.inputs.len(),
4974                ))
4975                .bt());
4976            }
4977            let fill_bytes = scalar_to_bytes(*value);
4978            OpParams::MaskedFill { fill_bytes }
4979        }
4980        // Op::MaskedFillInplace tracked by the parallel in-place
4981        // binary family session — not in HEAD's Op enum right now.
4982        Op::PadBackward {
4983            in_shape,
4984            padding,
4985            mode,
4986        } => {
4987            // Single input is the upstream gradient; output is the
4988            // input gradient (shape == `in_shape`).
4989            if node.inputs.len() != 1 {
4990                return Err(Error::Msg(format!(
4991                    "Op::PadBackward expects 1 input, got {}",
4992                    node.inputs.len(),
4993                ))
4994                .bt());
4995            }
4996            let in_dims: Vec<usize> = in_shape.dims().to_vec();
4997            // Output of the original forward Pad is the input shape
4998            // of the backward (== upstream's shape).
4999            let out_dims: Vec<usize> = in_dims
5000                .iter()
5001                .zip(padding.iter())
5002                .map(|(&d, &(b, a))| d + b + a)
5003                .collect();
5004            let mode_tag: u8 = match mode {
5005                fuel_graph::PadMode::Constant => 0,
5006                fuel_graph::PadMode::Reflect => 1,
5007                fuel_graph::PadMode::Replicate => 2,
5008            };
5009            OpParams::PadBackward {
5010                in_shape: in_dims,
5011                out_shape: out_dims,
5012                padding: padding.clone(),
5013                mode_tag,
5014            }
5015        }
5016        Op::Pad {
5017            padding,
5018            mode,
5019            value,
5020        } => {
5021            if node.inputs.len() != 1 {
5022                return Err(Error::Msg(format!(
5023                    "Op::Pad expects 1 input, got {}",
5024                    node.inputs.len(),
5025                ))
5026                .bt());
5027            }
5028            let in_layout = input_layout(node.inputs[0]);
5029            let in_dims: Vec<usize> = in_layout.shape().dims().to_vec();
5030            if padding.len() != in_dims.len() {
5031                return Err(Error::Msg(format!(
5032                    "Op::Pad: padding.len() ({}) != input rank ({})",
5033                    padding.len(),
5034                    in_dims.len(),
5035                ))
5036                .bt());
5037            }
5038            let out_dims: Vec<usize> = in_dims
5039                .iter()
5040                .zip(padding.iter())
5041                .map(|(&d, &(b, a))| d + b + a)
5042                .collect();
5043            let mode_tag: u8 = match mode {
5044                fuel_graph::PadMode::Constant => 0,
5045                fuel_graph::PadMode::Reflect => 1,
5046                fuel_graph::PadMode::Replicate => 2,
5047            };
5048            // Encode fill value as bytes for the output dtype. The
5049            // kernel is dtype-agnostic — it just memcopies the
5050            // pattern. Conversion happens once here per node, not
5051            // per element in the kernel.
5052            let fill_bytes = encode_value_to_bytes(node.dtype, *value)?;
5053            OpParams::Pad {
5054                in_shape: in_dims,
5055                out_shape: out_dims,
5056                padding: padding.clone(),
5057                mode_tag,
5058                fill_bytes,
5059            }
5060        }
5061        Op::IndexAdd { dim } => {
5062            // Inputs: (base, indices, src). All same dtype except
5063            // indices is U32. Output shape == base shape.
5064            if node.inputs.len() != 3 {
5065                return Err(Error::Msg(format!(
5066                    "Op::IndexAdd expects 3 inputs (base, indices, src), got {}",
5067                    node.inputs.len(),
5068                ))
5069                .bt());
5070            }
5071            let base_layout = input_layout(node.inputs[0]);
5072            let idx_layout = input_layout(node.inputs[1]);
5073            let src_layout = input_layout(node.inputs[2]);
5074            let base_dims = base_layout.shape().dims();
5075            let idx_dims = idx_layout.shape().dims();
5076            let src_dims = src_layout.shape().dims();
5077            if *dim >= base_dims.len() {
5078                return Err(Error::Msg(format!(
5079                    "Op::IndexAdd: dim {dim} out of range for base rank {}",
5080                    base_dims.len(),
5081                ))
5082                .bt());
5083            }
5084            if idx_dims.len() != 1 {
5085                return Err(Error::Msg(format!(
5086                    "Op::IndexAdd: indices must be rank 1, got {idx_dims:?}",
5087                ))
5088                .bt());
5089            }
5090            if base_dims.len() != src_dims.len() {
5091                return Err(Error::Msg(format!(
5092                    "Op::IndexAdd: base rank ({}) != src rank ({})",
5093                    base_dims.len(),
5094                    src_dims.len(),
5095                ))
5096                .bt());
5097            }
5098            let outer_count: usize = base_dims[..*dim].iter().product();
5099            let base_dim_size = base_dims[*dim];
5100            let inner_count: usize = base_dims[*dim + 1..].iter().product();
5101            let n_indices = idx_dims[0];
5102            OpParams::IndexAdd {
5103                outer_count,
5104                base_dim_size,
5105                n_indices,
5106                inner_count,
5107            }
5108        }
5109        Op::ScatterAdd { dim } => {
5110            if node.inputs.len() != 3 {
5111                return Err(Error::Msg(format!(
5112                    "Op::ScatterAdd expects 3 inputs (base, indices, src), got {}",
5113                    node.inputs.len(),
5114                ))
5115                .bt());
5116            }
5117            let base_layout = input_layout(node.inputs[0]);
5118            let src_layout = input_layout(node.inputs[2]);
5119            let base_shape: Vec<usize> = base_layout.shape().dims().to_vec();
5120            let src_shape: Vec<usize> = src_layout.shape().dims().to_vec();
5121            if base_shape.len() != src_shape.len() {
5122                return Err(Error::Msg(format!(
5123                    "Op::ScatterAdd: base rank ({}) != src rank ({})",
5124                    base_shape.len(),
5125                    src_shape.len(),
5126                ))
5127                .bt());
5128            }
5129            if *dim >= base_shape.len() {
5130                return Err(Error::Msg(format!(
5131                    "Op::ScatterAdd: dim {dim} out of range for rank {}",
5132                    base_shape.len(),
5133                ))
5134                .bt());
5135            }
5136            OpParams::ScatterAdd {
5137                base_shape,
5138                src_shape,
5139                dim: *dim,
5140            }
5141        }
5142        // Phase 7.6 step 5: Rope routes through the registry; the
5143        // legacy `Op::Rope` arm was retired with the variant.
5144        Op::Fused(_, fuel_graph::registry::FusedOpParams::Rope) => {
5145            // Inputs: (x, cos, sin). x is [..., seq, head_dim];
5146            // cos/sin are [seq, head_dim] (validated at graph build).
5147            if node.inputs.len() != 3 {
5148                return Err(Error::Msg(format!(
5149                    "Op::Rope expects 3 inputs (x, cos, sin), got {}",
5150                    node.inputs.len(),
5151                ))
5152                .bt());
5153            }
5154            let x_layout = input_layout(node.inputs[0]);
5155            let x_dims = x_layout.shape().dims();
5156            if x_dims.len() < 2 {
5157                return Err(
5158                    Error::Msg(format!("Op::Rope: x must have rank ≥ 2, got {x_dims:?}",)).bt(),
5159                );
5160            }
5161            let head_dim = *x_dims.last().unwrap();
5162            let seq = x_dims[x_dims.len() - 2];
5163            let outer_count: usize = x_dims[..x_dims.len() - 2].iter().product();
5164            OpParams::Rope {
5165                outer_count,
5166                seq,
5167                head_dim,
5168            }
5169        }
5170        Op::Gather { dim } => {
5171            // inputs[0] = source, inputs[1] = U32 indices (same rank).
5172            if node.inputs.len() != 2 {
5173                return Err(Error::Msg(format!(
5174                    "Op::Gather expects 2 inputs (source, indices), got {}",
5175                    node.inputs.len(),
5176                ))
5177                .bt());
5178            }
5179            let src_layout = input_layout(node.inputs[0]);
5180            let idx_layout = input_layout(node.inputs[1]);
5181            let source_shape: Vec<usize> = src_layout.shape().dims().to_vec();
5182            let output_shape: Vec<usize> = idx_layout.shape().dims().to_vec();
5183            if source_shape.len() != output_shape.len() {
5184                return Err(Error::Msg(format!(
5185                    "Op::Gather: source rank ({}) != indices rank ({})",
5186                    source_shape.len(),
5187                    output_shape.len(),
5188                ))
5189                .bt());
5190            }
5191            if *dim >= source_shape.len() {
5192                return Err(Error::Msg(format!(
5193                    "Op::Gather: dim {dim} out of range for rank {}",
5194                    source_shape.len(),
5195                ))
5196                .bt());
5197            }
5198            OpParams::Gather {
5199                source_shape,
5200                output_shape,
5201                dim: *dim,
5202            }
5203        }
5204        Op::NonZeroIndices { count_sym } => {
5205            // inputs[0] = x (the value tensor). capacity == x.elem_count();
5206            // the bundled output is [indices [capacity] U32 ; count [1] U32].
5207            if node.inputs.len() != 1 {
5208                return Err(Error::Msg(format!(
5209                    "Op::NonZeroIndices expects 1 input, got {}",
5210                    node.inputs.len(),
5211                ))
5212                .bt());
5213            }
5214            let x_layout = input_layout(node.inputs[0]);
5215            let capacity = x_layout.shape().elem_count();
5216            OpParams::NonZeroIndices {
5217                capacity,
5218                count_sym: *count_sym,
5219            }
5220        }
5221        Op::IndexSelect { dim } => {
5222            // inputs[0] = source, inputs[1] = U32 indices (rank 1).
5223            if node.inputs.len() != 2 {
5224                return Err(Error::Msg(format!(
5225                    "Op::IndexSelect expects 2 inputs (source, indices), got {}",
5226                    node.inputs.len(),
5227                ))
5228                .bt());
5229            }
5230            let src_layout = input_layout(node.inputs[0]);
5231            let idx_layout = input_layout(node.inputs[1]);
5232            let src_dims = src_layout.shape().dims();
5233            let idx_dims = idx_layout.shape().dims();
5234            if *dim >= src_dims.len() {
5235                return Err(Error::Msg(format!(
5236                    "Op::IndexSelect: dim {dim} out of range for source rank {}",
5237                    src_dims.len(),
5238                ))
5239                .bt());
5240            }
5241            if idx_dims.len() != 1 {
5242                return Err(Error::Msg(format!(
5243                    "Op::IndexSelect: indices must be rank 1, got shape {idx_dims:?}",
5244                ))
5245                .bt());
5246            }
5247            let outer_count: usize = src_dims[..*dim].iter().product();
5248            let source_dim_size = src_dims[*dim];
5249            let inner_count: usize = src_dims[*dim + 1..].iter().product();
5250            let n_indices = idx_dims[0];
5251            OpParams::IndexSelect {
5252                outer_count,
5253                source_dim_size,
5254                n_indices,
5255                inner_count,
5256            }
5257        }
5258        // Phase 7.6 step 5: legacy `Op::RmsNormLastDim` /
5259        // `Op::LayerNormLastDim` arms retired with the variants;
5260        // both now route through `Op::Fused(NORM_LAST_DIM, _)`.
5261        // Step 6 follow-up extends this arm to also cover the
5262        // backward variants (same outer × last_dim + eps geometry).
5263        Op::Fused(fid, params)
5264            if *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM
5265                || *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM
5266                || *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM_BACKWARD
5267                || *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM_BACKWARD =>
5268        {
5269            let eps = match params {
5270                fuel_graph::registry::FusedOpParams::RmsNormLastDim { eps } => *eps,
5271                fuel_graph::registry::FusedOpParams::LayerNormLastDim { eps } => *eps,
5272                fuel_graph::registry::FusedOpParams::RmsNormLastDimBackward { eps } => *eps,
5273                fuel_graph::registry::FusedOpParams::LayerNormLastDimBackward { eps } => *eps,
5274                _ => {
5275                    return Err(Error::Msg(format!(
5276                        "Op::Fused(NORM_LAST_DIM[_BACKWARD], _) expected \
5277                     RmsNormLastDim[Backward] or LayerNormLastDim[Backward] params, got {params:?}",
5278                    ))
5279                    .bt());
5280                }
5281            };
5282            let il = input_layout(node.inputs[0]);
5283            let dims = il.shape().dims();
5284            if dims.is_empty() {
5285                return Err(Error::Msg(
5286                    "Op::Fused(NORM_LAST_DIM[_BACKWARD], _) requires rank ≥ 1".to_string(),
5287                )
5288                .bt());
5289            }
5290            let last_dim = *dims.last().unwrap();
5291            let outer_count: usize = dims[..dims.len() - 1].iter().product();
5292            OpParams::NormLastDim {
5293                outer_count,
5294                last_dim,
5295                eps,
5296            }
5297        }
5298        // ReduceMaxToBackward: shape pair via the new
5299        // OpParams::ReduceMaxToBackward variant. x's shape is
5300        // `input_shape`; upstream's shape is `output_shape`.
5301        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::REDUCE_MAX_TO_BACKWARD => {
5302            if node.inputs.len() != 2 {
5303                return Err(Error::Msg(format!(
5304                    "Op::Fused(REDUCE_MAX_TO_BACKWARD) expects 2 inputs, got {}",
5305                    node.inputs.len(),
5306                ))
5307                .bt());
5308            }
5309            let x_layout = input_layout(node.inputs[0]);
5310            let up_layout = input_layout(node.inputs[1]);
5311            let input_shape: Vec<usize> = x_layout.shape().dims().to_vec();
5312            let output_shape: Vec<usize> = up_layout.shape().dims().to_vec();
5313            OpParams::ReduceMaxToBackward {
5314                input_shape,
5315                output_shape,
5316            }
5317        }
5318        Op::Concat { dim } => {
5319            // Output's shape: [..., total_dim, ...]. Compute outer
5320            // and inner counts from output_shape[..dim] and
5321            // [dim+1..]; per-input dim sizes from each input's
5322            // layout shape at index `dim`.
5323            if node.inputs.is_empty() {
5324                return Err(Error::Msg("Op::Concat requires at least 1 input".to_string()).bt());
5325            }
5326            let out_dims = node.shape.dims();
5327            if *dim >= out_dims.len() {
5328                return Err(Error::Msg(format!(
5329                    "Op::Concat: dim {dim} out of range for output rank {}",
5330                    out_dims.len(),
5331                ))
5332                .bt());
5333            }
5334            let outer_count: usize = out_dims[..*dim].iter().product();
5335            let inner_count: usize = out_dims[*dim + 1..].iter().product();
5336            let mut input_dim_sizes: Vec<usize> = Vec::with_capacity(node.inputs.len());
5337            for in_id in &node.inputs {
5338                let il = input_layout(*in_id);
5339                let il_dims = il.shape().dims();
5340                if *dim >= il_dims.len() {
5341                    return Err(Error::Msg(format!(
5342                        "Op::Concat: input {in_id:?} has rank {} but concat dim is {dim}",
5343                        il_dims.len(),
5344                    ))
5345                    .bt());
5346                }
5347                input_dim_sizes.push(il_dims[*dim]);
5348            }
5349            OpParams::Concat {
5350                outer_count,
5351                input_dim_sizes,
5352                inner_count,
5353                axis: *dim,
5354            }
5355        }
5356        Op::AddScalar(c) => OpParams::Affine { mul: 1.0, add: *c },
5357        Op::MulScalar(c) => OpParams::Affine { mul: *c, add: 0.0 },
5358        Op::Clamp { min, max } => OpParams::Clamp {
5359            min: *min,
5360            max: *max,
5361        },
5362        Op::PowI(exp) => OpParams::PowI { exp: *exp },
5363        Op::ClampInplace { min, max } => OpParams::Clamp {
5364            min: *min,
5365            max: *max,
5366        },
5367        Op::PowIInplace(exp) => OpParams::PowI { exp: *exp },
5368        // PowI backward — `(x, upstream) → grad_x = exp · x^(exp-1) ·
5369        // upstream`. Pulls the same `exp` as the forward through
5370        // FusedOpParams::PowIBackward (autograd carries it across).
5371        Op::Fused(_, fuel_graph::registry::FusedOpParams::PowIBackward { exp }) => {
5372            OpParams::PowI { exp: *exp }
5373        }
5374        // In-place affine (Phase 3 of the in-place ops infrastructure):
5375        // reuse the existing `OpParams::Affine` payload — the kernel
5376        // side doesn't care whether the destination is fresh or aliases
5377        // the input; the structural decision lives in the executor's
5378        // dedicated `WorkItemKind::InplaceKernel` arm.
5379        Op::Fused(_, fuel_graph::registry::FusedOpParams::InplaceAffine { mul, add }) => {
5380            OpParams::Affine {
5381                mul: *mul,
5382                add: *add,
5383            }
5384        }
5385        // Phase 7.6 step 5: legacy `Op::Conv2D` arm retired with the
5386        // variant; Conv2D routes through `Op::Fused(CONV2D, _)`.
5387        Op::Fused(
5388            _,
5389            fuel_graph::registry::FusedOpParams::Conv2D {
5390                stride,
5391                padding,
5392                groups,
5393            },
5394        ) => {
5395            // Inputs[0] = x [N, Cin, Hin, Win]; inputs[1] = weight
5396            // [Cout, Cin/groups, Kh, Kw]; inputs[2] (optional) = bias [Cout].
5397            // Output (this Node's shape) = [N, Cout, Hout, Wout].
5398            if node.inputs.len() != 2 && node.inputs.len() != 3 {
5399                return Err(Error::Msg(format!(
5400                    "Op::Conv2D expects 2 or 3 inputs, got {}",
5401                    node.inputs.len(),
5402                ))
5403                .bt());
5404            }
5405            let x_layout = input_layout(node.inputs[0]);
5406            let w_layout = input_layout(node.inputs[1]);
5407            let x_dims = x_layout.shape().dims();
5408            let w_dims = w_layout.shape().dims();
5409            if x_dims.len() != 4 || w_dims.len() != 4 {
5410                return Err(Error::Msg(format!(
5411                    "Op::Conv2D requires rank-4 x and weight; got x={x_dims:?} w={w_dims:?}",
5412                ))
5413                .bt());
5414            }
5415            let out_dims = node.shape.dims();
5416            if out_dims.len() != 4 {
5417                return Err(Error::Msg(format!(
5418                    "Op::Conv2D output must be rank 4, got {out_dims:?}",
5419                ))
5420                .bt());
5421            }
5422            let x_shape = [x_dims[0], x_dims[1], x_dims[2], x_dims[3]];
5423            let w_shape = [w_dims[0], w_dims[1], w_dims[2], w_dims[3]];
5424            let out_shape = [out_dims[0], out_dims[1], out_dims[2], out_dims[3]];
5425            OpParams::Conv2D {
5426                x_shape,
5427                w_shape,
5428                out_shape,
5429                stride: *stride,
5430                padding: *padding,
5431                dilation: (1, 1),
5432                groups: *groups,
5433            }
5434        }
5435        Op::Fused(
5436            _,
5437            fuel_graph::registry::FusedOpParams::Conv2DEpilogue {
5438                stride,
5439                padding,
5440                groups,
5441                has_bias,
5442                recipe,
5443                scalars,
5444            },
5445        ) => {
5446            // Inputs x, weight, [bias iff has_bias], then the recipe's extras.
5447            let conv_arity = 2 + usize::from(*has_bias);
5448            if node.inputs.len() < conv_arity {
5449                return Err(Error::Msg(format!(
5450                    "Conv2DEpilogue expects at least {conv_arity} inputs, got {}",
5451                    node.inputs.len(),
5452                ))
5453                .bt());
5454            }
5455            let rank4 = |what: &str, dims: &[usize]| -> Result<[usize; 4]> {
5456                <[usize; 4]>::try_from(dims).map_err(|_| {
5457                    Error::Msg(format!(
5458                        "Conv2DEpilogue: {what} must be rank 4, got {dims:?}"
5459                    ))
5460                    .bt()
5461                })
5462            };
5463            let out_shape = rank4("output", node.shape.dims())?;
5464            // The kernel reads each extra as one element per output element.
5465            for &extra in &node.inputs[conv_arity..] {
5466                let layout = input_layout(extra);
5467                let dims = layout.shape().dims();
5468                if dims != node.shape.dims() {
5469                    return Err(Error::Msg(format!(
5470                        "Conv2DEpilogue: extra operand {dims:?} is not output-shaped {:?}",
5471                        node.shape.dims(),
5472                    ))
5473                    .bt());
5474                }
5475            }
5476            OpParams::Conv2DEpilogue {
5477                x_shape: rank4("x", input_layout(node.inputs[0]).shape().dims())?,
5478                w_shape: rank4("weight", input_layout(node.inputs[1]).shape().dims())?,
5479                out_shape,
5480                stride: *stride,
5481                padding: *padding,
5482                groups: *groups,
5483                has_bias: *has_bias,
5484                recipe: recipe.clone(),
5485                scalars: scalars.clone(),
5486            }
5487        }
5488        // Phase 7.6 step 5 (final): legacy `Op::PagedAttn` arm dropped.
5489        Op::Fused(
5490            _,
5491            fuel_graph::registry::FusedOpParams::PagedAttn {
5492                softmax_scale,
5493                block_size,
5494                softcap,
5495            },
5496        ) => {
5497            // Inputs[0]=q [B,Hq,Sq,D], inputs[1]=k_cache [num_blocks,
5498            // block_size, Hkv, D], inputs[2]=v_cache same shape,
5499            // inputs[3]=block_table [B, max_blocks_per_seq] U32,
5500            // inputs[4]=context_lens [B] U32, inputs[5]=alibi [Hq] (optional).
5501            if node.inputs.len() != 5 && node.inputs.len() != 6 {
5502                return Err(Error::Msg(format!(
5503                    "Op::PagedAttn expects 5 or 6 inputs, got {}",
5504                    node.inputs.len(),
5505                ))
5506                .bt());
5507            }
5508            let q_layout = input_layout(node.inputs[0]);
5509            let kc_layout = input_layout(node.inputs[1]);
5510            let vc_layout = input_layout(node.inputs[2]);
5511            let bt_layout = input_layout(node.inputs[3]);
5512            let q_dims = q_layout.shape().dims();
5513            let kc_dims = kc_layout.shape().dims();
5514            let vc_dims = vc_layout.shape().dims();
5515            let bt_dims = bt_layout.shape().dims();
5516            if q_dims.len() != 4 || kc_dims.len() != 4 || vc_dims.len() != 4 {
5517                return Err(Error::Msg(format!(
5518                    "Op::PagedAttn requires rank-4 q/k_cache/v_cache; \
5519                     got q={q_dims:?} k_cache={kc_dims:?} v_cache={vc_dims:?}",
5520                ))
5521                .bt());
5522            }
5523            if kc_dims != vc_dims {
5524                return Err(Error::Msg(format!(
5525                    "Op::PagedAttn: k_cache {kc_dims:?} and v_cache {vc_dims:?} must match",
5526                ))
5527                .bt());
5528            }
5529            if bt_dims.len() != 2 {
5530                return Err(Error::Msg(format!(
5531                    "Op::PagedAttn: block_table must be rank 2 [B, max_blocks_per_seq], got {bt_dims:?}",
5532                ))
5533                .bt());
5534            }
5535            if kc_dims[1] != *block_size {
5536                return Err(Error::Msg(format!(
5537                    "Op::PagedAttn: k_cache block_size dim ({}) must equal Op's block_size ({})",
5538                    kc_dims[1], block_size,
5539                ))
5540                .bt());
5541            }
5542            OpParams::PagedAttn {
5543                b: q_dims[0],
5544                hq: q_dims[1],
5545                hkv: kc_dims[2],
5546                sq: q_dims[2],
5547                d: q_dims[3],
5548                block_size: *block_size,
5549                max_blocks_per_seq: bt_dims[1],
5550                num_blocks: kc_dims[0],
5551                softmax_scale: *softmax_scale,
5552                softcap: *softcap,
5553            }
5554        }
5555        // Phase 7.6 step 5 (final): legacy `Op::FlashAttn` arm dropped.
5556        Op::Fused(
5557            _,
5558            fuel_graph::registry::FusedOpParams::FlashAttn {
5559                softmax_scale,
5560                causal,
5561                window_size_left,
5562                window_size_right,
5563                softcap,
5564                k_len,
5565            },
5566        ) => {
5567            // Inputs[0]=q [B,Hq,Sq,D], inputs[1]=k [B,Hkv,Sk,D],
5568            // inputs[2]=v [B,Hkv,Sk,D], inputs[3]=alibi_slopes [Hq] (optional).
5569            // `sk` is the PHYSICAL K extent (capacity, for strides/bytes);
5570            // `k_len` (resolved below) is the LOGICAL attended length.
5571            if node.inputs.len() != 3 && node.inputs.len() != 4 {
5572                return Err(Error::Msg(format!(
5573                    "Op::FlashAttn expects 3 or 4 inputs, got {}",
5574                    node.inputs.len(),
5575                ))
5576                .bt());
5577            }
5578            let q_layout = input_layout(node.inputs[0]);
5579            let k_layout = input_layout(node.inputs[1]);
5580            let v_layout = input_layout(node.inputs[2]);
5581            let q_dims = q_layout.shape().dims();
5582            let k_dims = k_layout.shape().dims();
5583            let v_dims = v_layout.shape().dims();
5584            if q_dims.len() != 4 || k_dims.len() != 4 || v_dims.len() != 4 {
5585                return Err(Error::Msg(format!(
5586                    "Op::FlashAttn requires rank-4 q/k/v; got q={q_dims:?} k={k_dims:?} v={v_dims:?}",
5587                ))
5588                .bt());
5589            }
5590            if k_dims != v_dims {
5591                return Err(Error::Msg(format!(
5592                    "Op::FlashAttn: k {k_dims:?} and v {v_dims:?} must share shape",
5593                ))
5594                .bt());
5595            }
5596            if q_dims[0] != k_dims[0] || q_dims[3] != k_dims[3] {
5597                return Err(Error::Msg(format!(
5598                    "Op::FlashAttn: q {q_dims:?} and k {k_dims:?} must share B and D",
5599                ))
5600                .bt());
5601            }
5602            let sk = k_dims[2];
5603            // Resolve the logical attended length. `None` ⇒ attend the
5604            // full K extent (today's behavior). `Some(dyn)` ⇒ resolve
5605            // against the per-pass SymEnv; the resolved length must fit
5606            // the capacity and cover Sq (a valid causal prefix).
5607            let attended_k_len = match k_len {
5608                None => sk,
5609                Some(dyn_k) => {
5610                    let kl = dyn_k.resolve(sym_env).ok_or_else(|| {
5611                        Error::Msg(format!(
5612                            "Op::FlashAttn: dynamic k_len {dyn_k:?} is unbound in the SymEnv at realize",
5613                        ))
5614                        .bt()
5615                    })?;
5616                    if kl > sk {
5617                        return Err(Error::Msg(format!(
5618                            "Op::FlashAttn: resolved k_len ({kl}) exceeds K capacity ({sk})",
5619                        ))
5620                        .bt());
5621                    }
5622                    if kl < q_dims[2] {
5623                        return Err(Error::Msg(format!(
5624                            "Op::FlashAttn: resolved k_len ({kl}) < Sq ({}) — not a valid causal prefix",
5625                            q_dims[2],
5626                        ))
5627                        .bt());
5628                    }
5629                    kl
5630                }
5631            };
5632            OpParams::FlashAttn {
5633                b: q_dims[0],
5634                hq: q_dims[1],
5635                hkv: k_dims[1],
5636                sq: q_dims[2],
5637                sk,
5638                d: q_dims[3],
5639                k_len: attended_k_len,
5640                softmax_scale: *softmax_scale,
5641                causal: *causal,
5642                window_size_left: *window_size_left,
5643                window_size_right: *window_size_right,
5644                softcap: *softcap,
5645            }
5646        }
5647        Op::ReduceSumTo(target_shape) => {
5648            if node.inputs.len() != 1 {
5649                return Err(Error::Msg(format!(
5650                    "Op::ReduceSumTo expects 1 input, got {}",
5651                    node.inputs.len(),
5652                ))
5653                .bt());
5654            }
5655            let in_layout = input_layout(node.inputs[0]);
5656            let input_shape: Vec<usize> = in_layout.shape().dims().to_vec();
5657            let output_shape: Vec<usize> = target_shape.dims().to_vec();
5658            OpParams::ReduceSumTo {
5659                input_shape,
5660                output_shape,
5661            }
5662        }
5663        Op::ReduceMaxTo(target_shape) => {
5664            if node.inputs.len() != 1 {
5665                return Err(Error::Msg(format!(
5666                    "Op::ReduceMaxTo expects 1 input, got {}",
5667                    node.inputs.len(),
5668                ))
5669                .bt());
5670            }
5671            let in_layout = input_layout(node.inputs[0]);
5672            let input_shape: Vec<usize> = in_layout.shape().dims().to_vec();
5673            let output_shape: Vec<usize> = target_shape.dims().to_vec();
5674            OpParams::ReduceMaxTo {
5675                input_shape,
5676                output_shape,
5677            }
5678        }
5679        // Phase 7.6 step 5 (final): legacy `Op::ConvTranspose2D` arm dropped.
5680        Op::Fused(
5681            _,
5682            fuel_graph::registry::FusedOpParams::ConvTranspose2D {
5683                stride,
5684                padding,
5685                output_padding,
5686                dilation,
5687                groups,
5688            },
5689        ) => {
5690            // Inputs[0] = x [N, Cin, Hin, Win]; inputs[1] = weight
5691            // [Cin, Cout/groups, Kh, Kw]; inputs[2] (optional) = bias [Cout].
5692            // Output (this Node's shape) = [N, Cout, Hout, Wout].
5693            if node.inputs.len() != 2 && node.inputs.len() != 3 {
5694                return Err(Error::Msg(format!(
5695                    "Op::ConvTranspose2D expects 2 or 3 inputs, got {}",
5696                    node.inputs.len(),
5697                ))
5698                .bt());
5699            }
5700            let x_layout = input_layout(node.inputs[0]);
5701            let w_layout = input_layout(node.inputs[1]);
5702            let x_dims = x_layout.shape().dims();
5703            let w_dims = w_layout.shape().dims();
5704            if x_dims.len() != 4 || w_dims.len() != 4 {
5705                return Err(Error::Msg(format!(
5706                    "Op::ConvTranspose2D requires rank-4 x and weight; got x={x_dims:?} w={w_dims:?}",
5707                ))
5708                .bt());
5709            }
5710            let out_dims = node.shape.dims();
5711            if out_dims.len() != 4 {
5712                return Err(Error::Msg(format!(
5713                    "Op::ConvTranspose2D output must be rank 4, got {out_dims:?}",
5714                ))
5715                .bt());
5716            }
5717            let x_shape = [x_dims[0], x_dims[1], x_dims[2], x_dims[3]];
5718            let w_shape = [w_dims[0], w_dims[1], w_dims[2], w_dims[3]];
5719            let out_shape = [out_dims[0], out_dims[1], out_dims[2], out_dims[3]];
5720            OpParams::ConvTranspose2D {
5721                x_shape,
5722                w_shape,
5723                out_shape,
5724                stride: *stride,
5725                padding: *padding,
5726                output_padding: *output_padding,
5727                dilation: *dilation,
5728                groups: *groups,
5729            }
5730        }
5731        Op::WriteSlice { ranges, dyn_offset } => {
5732            // inputs[0] = destination (its shape == this node's shape
5733            // since WriteSlice's output adopts the destination's
5734            // Layout). inputs[1] = source slab; its shape is implied
5735            // by `ranges`. The kernel needs the destination shape to
5736            // compute strides for the slab walk.
5737            if node.inputs.len() != 2 {
5738                return Err(Error::Msg(format!(
5739                    "Op::WriteSlice expects 2 inputs (destination, source), got {}",
5740                    node.inputs.len(),
5741                ))
5742                .bt());
5743            }
5744            let dest_dims = node.shape.dims().to_vec();
5745            if ranges.len() != dest_dims.len() {
5746                return Err(Error::Msg(format!(
5747                    "Op::WriteSlice: ranges.len() ({}) must equal destination rank ({})",
5748                    ranges.len(),
5749                    dest_dims.len(),
5750                ))
5751                .bt());
5752            }
5753            // Phase D symbolic extents: when present, resolve the runtime
5754            // start offset against the per-pass SymEnv, overriding
5755            // `ranges[axis].0`. The slab WIDTH on that axis stays
5756            // `ranges[axis].1 - ranges[axis].0`, so the effective range
5757            // becomes `(base, base + width)`. `None` ⇒ fully static, and
5758            // the SymEnv is never consulted (empty-env realize unchanged).
5759            //
5760            // DUAL-PATH (increment 2b — data-determined dynamic shapes):
5761            //  - The offset resolves in the compile-time `sym_env` (static,
5762            //    or an INPUT-determined `cached_len`): bake it into `ranges`
5763            //    now, exactly as before.
5764            //  - It is UNBOUND at compile AND a producer in this graph binds
5765            //    it (`Op::NonZeroIndices`'s count, etc.): it is
5766            //    DATA-DETERMINED — leave `ranges[axis]` as the static
5767            //    placeholder and DEFER, carrying the `DynScalar` in
5768            //    `deferred_dyn_offset`. The `WorkItemKind::WriteSlice`
5769            //    executor arm resolves it from `produced_syms` (after the
5770            //    producer runs) and bounds-checks the resolved range there.
5771            //  - It is unbound AND no producer binds it: a genuine caller
5772            //    error → surface it here (preserves the unbound-error path).
5773            let mut ranges = ranges.clone();
5774            let mut deferred_dyn_offset: Option<(usize, fuel_ir::DynScalar)> = None;
5775            if let Some((axis, off)) = dyn_offset {
5776                if *axis >= ranges.len() {
5777                    return Err(Error::Msg(format!(
5778                        "Op::WriteSlice: dyn_offset axis ({axis}) out of bounds for rank {}",
5779                        ranges.len(),
5780                    ))
5781                    .bt());
5782                }
5783                match off.resolve(sym_env) {
5784                    Some(base) => {
5785                        let (start, end) = ranges[*axis];
5786                        let width = end - start;
5787                        ranges[*axis] = (base, base + width);
5788                    }
5789                    None => {
5790                        let is_data_determined = matches!(off, fuel_ir::DynScalar::Sym(s)
5791                            if graph.binds_data_determined_sym(*s));
5792                        if is_data_determined {
5793                            deferred_dyn_offset = Some((*axis, *off));
5794                        } else {
5795                            return Err(Error::Msg(format!(
5796                                "Op::WriteSlice: dynamic offset {off:?} on axis {axis} is \
5797                                 unbound in the SymEnv at realize (and no producer in the \
5798                                 graph binds it, so it is not data-determined)",
5799                            ))
5800                            .bt());
5801                        }
5802                    }
5803                }
5804            }
5805            for (i, &(start, end)) in ranges.iter().enumerate() {
5806                // The deferred axis still holds its static placeholder; the
5807                // executor bounds-checks the resolved range after producing
5808                // the count. Every other axis is fully known now.
5809                if deferred_dyn_offset.is_some_and(|(a, _)| a == i) {
5810                    continue;
5811                }
5812                if end < start || end > dest_dims[i] {
5813                    return Err(Error::Msg(format!(
5814                        "Op::WriteSlice: ranges[{i}] = ({start}, {end}) invalid \
5815                         for destination dim {i} = {}",
5816                        dest_dims[i],
5817                    ))
5818                    .bt());
5819                }
5820            }
5821            OpParams::WriteSlice {
5822                dest_shape: dest_dims,
5823                ranges,
5824                deferred_dyn_offset,
5825            }
5826        }
5827        Op::WriteSliceRotating {
5828            axis,
5829            modulus,
5830            ranges,
5831        } => {
5832            // inputs[0] = destination, inputs[1] = source slab,
5833            // inputs[2] = dynamic position scalar (U32). The builder
5834            // already validated rank / dtype / shape parity; the
5835            // exec-time check below mirrors WriteSlice for the
5836            // structural invariants the executor depends on.
5837            if node.inputs.len() != 3 {
5838                return Err(Error::Msg(format!(
5839                    "Op::WriteSliceRotating expects 3 inputs (destination, source, position), got {}",
5840                    node.inputs.len(),
5841                ))
5842                .bt());
5843            }
5844            let dest_dims = node.shape.dims().to_vec();
5845            if ranges.len() != dest_dims.len() {
5846                return Err(Error::Msg(format!(
5847                    "Op::WriteSliceRotating: ranges.len() ({}) must equal destination rank ({})",
5848                    ranges.len(),
5849                    dest_dims.len(),
5850                ))
5851                .bt());
5852            }
5853            if *axis >= dest_dims.len() {
5854                return Err(Error::Msg(format!(
5855                    "Op::WriteSliceRotating: axis {axis} out of bounds for rank {}",
5856                    dest_dims.len(),
5857                ))
5858                .bt());
5859            }
5860            if *modulus == 0 || *modulus > dest_dims[*axis] {
5861                return Err(Error::Msg(format!(
5862                    "Op::WriteSliceRotating: modulus {modulus} invalid for dest_shape[{axis}] = {}",
5863                    dest_dims[*axis],
5864                ))
5865                .bt());
5866            }
5867            OpParams::WriteSliceRotating {
5868                dest_shape: dest_dims,
5869                axis: *axis,
5870                modulus: *modulus,
5871                ranges: ranges.clone(),
5872            }
5873        }
5874        Op::WriteSliceDoff { axis, ranges } => {
5875            // inputs[0] = destination, inputs[1] = source slab,
5876            // inputs[2] = device-resident I64 offset scalar. The
5877            // builder validated rank / dtype / static-width parity; the
5878            // exec-time check below mirrors WriteSliceRotating minus the
5879            // modulus (no wrap). Bounds on the *dynamic* offset are the
5880            // caller's contract (device-only, un-checkable here).
5881            if node.inputs.len() != 3 {
5882                return Err(Error::Msg(format!(
5883                    "Op::WriteSliceDoff expects 3 inputs (destination, source, offset), got {}",
5884                    node.inputs.len(),
5885                ))
5886                .bt());
5887            }
5888            let dest_dims = node.shape.dims().to_vec();
5889            if ranges.len() != dest_dims.len() {
5890                return Err(Error::Msg(format!(
5891                    "Op::WriteSliceDoff: ranges.len() ({}) must equal destination rank ({})",
5892                    ranges.len(),
5893                    dest_dims.len(),
5894                ))
5895                .bt());
5896            }
5897            if *axis >= dest_dims.len() {
5898                return Err(Error::Msg(format!(
5899                    "Op::WriteSliceDoff: axis {axis} out of bounds for rank {}",
5900                    dest_dims.len(),
5901                ))
5902                .bt());
5903            }
5904            OpParams::WriteSliceDoff {
5905                dest_shape: dest_dims,
5906                axis: *axis,
5907                ranges: ranges.clone(),
5908            }
5909        }
5910        _ => OpParams::None,
5911    })
5912}
5913
5914/// The unchecked out-of-range index reads of one run (GAP-415).
5915#[cfg(feature = "cuda")]
5916type IndexReads = fuel_cuda_backend::index_read_check::IndexReadChecks;
5917
5918/// Non-CUDA builds note nothing, so there is nothing to check.
5919#[cfg(not(feature = "cuda"))]
5920#[derive(Default)]
5921struct IndexReads {}
5922
5923#[cfg(not(feature = "cuda"))]
5924impl IndexReads {
5925    fn check(&mut self) -> Result<()> {
5926        Ok(())
5927    }
5928}
5929
5930/// Note the index operand of a just-launched CUDA `index_select` or `gather`.
5931#[cfg(feature = "cuda")]
5932fn note_index_read(
5933    reads: &mut IndexReads,
5934    params: &OpParams,
5935    inputs: &[Arc<RwLock<Storage>>],
5936) -> Result<()> {
5937    let (op, numel, bound) = match params {
5938        OpParams::IndexSelect {
5939            source_dim_size,
5940            n_indices,
5941            ..
5942        } => ("index_select", *n_indices, *source_dim_size),
5943        OpParams::Gather {
5944            source_shape,
5945            output_shape,
5946            dim,
5947        } => {
5948            let bound = source_shape.get(*dim).copied().ok_or_else(|| {
5949                Error::Msg(format!("gather: dim {dim} is outside {source_shape:?}")).bt()
5950            })?;
5951            ("gather", output_shape.iter().product(), bound)
5952        }
5953        _ => return Ok(()),
5954    };
5955    let index = inputs
5956        .get(1)
5957        .ok_or_else(|| Error::Msg(format!("{op}: no index operand")).bt())?;
5958    let guard = index.read().map_err(|_| poisoned("index storage"))?;
5959    match &guard.inner {
5960        fuel_memory::BackendStorage::Cuda(c) => reads.note(op, c, numel, bound),
5961        other => Err(Error::Msg(format!(
5962            "{op}: CUDA kernel with a {:?} index operand",
5963            other.backend_id()
5964        ))
5965        .bt()),
5966    }
5967}
5968
5969/// Execute one work item. Three branches by `WorkItemKind`:
5970///
5971/// - `ConstAdopt` — verify cache has an entry pre-seeded by the
5972///   caller; record the layout from the WorkItem.
5973/// - `ViewOf { input }` — clone the input's Storage Arc into the
5974///   output slot (bytes are shared); record the strided layout
5975///   from the WorkItem.
5976/// - `Kernel` — gather input Arcs, allocate the output, run the
5977///   compiled kernel, store the result; record the contiguous
5978///   layout from the WorkItem.
5979///
5980/// Best-effort: prefix a realize-time node error with the failing node's graph
5981/// location — `Graph::describe_node` renders `Node#N (op, out shape, dtype,
5982/// inputs=[...])`, enough to grep-locate the offending op in a large graph. The
5983/// legacy per-node executors (`fuel-graph-executor`, the retired
5984/// `fuel-reference-backend`) wrapped panics this way; the PipelinedExecutor
5985/// surfaces the raw kernel error, so a dtype/shape/OOB failure deep in a model
5986/// arrived with no graph coordinate. On a graph read-lock failure the original
5987/// error passes through unchanged — the location is a navigation aid, never
5988/// worth masking the real error with a lock issue. Zero happy-path cost: only
5989/// the error branch touches the graph.
5990fn with_node_location(graph: &Arc<RwLock<Graph>>, node_id: NodeId, err: Error) -> Error {
5991    match graph.read() {
5992        Ok(g) => err.context(g.describe_node(node_id)),
5993        Err(_) => err,
5994    }
5995}
5996
5997/// Execute one [`WorkItem`] against the cache, returning the node's
5998/// [`CompletionHandle`].
5999///
6000/// Step E A4b-1: the producing arms (Kernel / WriteSlice / WriteSliceRotating /
6001/// in-place / cross-device Copy alloc) return the handle from `execute_compiled`
6002/// *without* waiting it inline — the realize loop stores it in its per-node
6003/// handle map and drains at realize-end. Non-producing arms (const adopt, view,
6004/// slot projection, release marker, contiguize) are pure Arc-clones / host
6005/// allocs whose work is already complete → [`CompletionHandle::Ready`].
6006/// Read a data-determined runtime count from bundle slot 1 of a
6007/// just-realized producer and bind it into the per-pass `SymEnv` under
6008/// `count_sym` — the data-dependent dynamic-shapes seam (increment 2a).
6009/// The producer's bundle is `[indices [capacity] U32 ; count [1] U32]`;
6010/// slot 1's single U32 starts at byte `capacity * 4` (after the
6011/// `capacity`-element U32 primary slot). CPU only for now — device
6012/// backends need a D2H after the completion handle is waited (a documented
6013/// follow-up; the whole data-dependent path is CPU-first). Called AFTER
6014/// `execute_compiled`, whose CPU path returns a `Ready` handle, so the
6015/// bytes are already valid.
6016fn bind_data_determined_count(
6017    arc: &Arc<RwLock<Storage>>,
6018    capacity: usize,
6019    count_sym: fuel_ir::SymId,
6020    produced_syms: &mut SymEnv,
6021) -> Result<()> {
6022    let guard = arc
6023        .read()
6024        .map_err(|_| poisoned("NonZeroIndices output storage"))?;
6025    let count_byte_off = capacity * std::mem::size_of::<u32>();
6026    let end = count_byte_off + std::mem::size_of::<u32>();
6027    // The non-CPU `BackendStorage` variants are cfg-gated; with GPU
6028    // features off, `Cpu` is the only variant and the fallback arm is
6029    // unreachable (a documented CPU-first limitation, not dead logic).
6030    #[allow(unreachable_patterns)]
6031    let count = match &guard.inner {
6032        fuel_memory::BackendStorage::Cpu(cpu_bytes) => {
6033            let bytes = cpu_bytes.bytes();
6034            if end > bytes.len() {
6035                return Err(Error::Msg(format!(
6036                    "NonZeroIndices: count slot byte range [{count_byte_off}..{end}) \
6037                     exceeds bundle byte length {}",
6038                    bytes.len(),
6039                ))
6040                .bt());
6041            }
6042            u32::from_le_bytes(
6043                bytes[count_byte_off..end]
6044                    .try_into()
6045                    .expect("4 bytes → u32"),
6046            )
6047        }
6048        other => {
6049            return Err(Error::Msg(format!(
6050                "NonZeroIndices: data-determined count read is CPU-only today; got \
6051                 BackendStorage::{:?} (device backends need a D2H after the completion \
6052                 handle is waited — a documented follow-up)",
6053                other.backend_id(),
6054            ))
6055            .bt());
6056        }
6057    };
6058    produced_syms.bind(count_sym, count as usize)?;
6059    Ok(())
6060}
6061
6062/// Increment 2b — the consumer half of data-dependent dynamic shapes. When
6063/// a `WriteSlice`'s offset is DATA-DETERMINED (its `SymId` is produced
6064/// mid-pass, so `op_to_op_params` deferred it into
6065/// `OpParams::WriteSlice::deferred_dyn_offset` instead of baking it at
6066/// compile), resolve it HERE from `produced_syms` — populated by the
6067/// producer's execute step (single-threaded topological order guarantees
6068/// the producer already ran). Returns a patched clone of the `CompiledNode`
6069/// with the resolved `ranges` (and `deferred_dyn_offset` cleared) for the
6070/// kernel; `None` when there is nothing to defer (the common path — no
6071/// clone). Bounds-checks the resolved range (deferred past compile).
6072fn resolve_deferred_write_slice(
6073    compiled: &CompiledNode,
6074    produced_syms: &SymEnv,
6075    node_id: NodeId,
6076) -> Result<Option<CompiledNode>> {
6077    let OpParams::WriteSlice {
6078        dest_shape,
6079        ranges,
6080        deferred_dyn_offset,
6081    } = &compiled.op_params
6082    else {
6083        return Ok(None);
6084    };
6085    let Some((axis, off)) = deferred_dyn_offset else {
6086        return Ok(None);
6087    };
6088    let base = off.resolve(produced_syms).ok_or_else(|| {
6089        Error::Msg(format!(
6090            "Op::WriteSlice {node_id:?}: data-determined offset {off:?} on axis {axis} is \
6091             unbound in produced_syms at execute (its producer did not run / bind it)",
6092        ))
6093        .bt()
6094    })?;
6095    let mut ranges = ranges.clone();
6096    let (start, end) = ranges[*axis];
6097    let width = end - start;
6098    let resolved = (base, base + width);
6099    if resolved.1 > dest_shape[*axis] {
6100        return Err(Error::Msg(format!(
6101            "Op::WriteSlice {node_id:?}: resolved data-determined range {resolved:?} on axis \
6102             {axis} exceeds destination dim = {}",
6103            dest_shape[*axis],
6104        ))
6105        .bt());
6106    }
6107    ranges[*axis] = resolved;
6108    let mut patched = compiled.clone();
6109    patched.op_params = OpParams::WriteSlice {
6110        dest_shape: dest_shape.clone(),
6111        ranges,
6112        deferred_dyn_offset: None,
6113    };
6114    Ok(Some(patched))
6115}
6116
6117/// Dynamic-M matmul: when a matmul's row count is DATA-DETERMINED
6118/// (`MatmulM::Deferred`, deferred by `op_to_op_params` because a producer
6119/// binds its `SymId` mid-pass), resolve it HERE from `produced_syms` and
6120/// run the kernel against a patched clone whose `m_compute` is
6121/// `MatmulM::Rows(count)`. Mirrors `resolve_deferred_write_slice`. `None`
6122/// when nothing is deferred (the common path — no clone). The kernel then
6123/// computes exactly `count` rows of the `m`-row capacity buffer.
6124fn resolve_deferred_matmul(
6125    compiled: &CompiledNode,
6126    produced_syms: &SymEnv,
6127    node_id: NodeId,
6128) -> Result<Option<CompiledNode>> {
6129    let OpParams::Matmul {
6130        lhs_batch_dims,
6131        rhs_batch_dims,
6132        m,
6133        n,
6134        k,
6135        m_compute,
6136    } = &compiled.op_params
6137    else {
6138        return Ok(None);
6139    };
6140    let MatmulM::Deferred(dyn_m) = m_compute else {
6141        return Ok(None);
6142    };
6143    let rows = dyn_m.resolve(produced_syms).ok_or_else(|| {
6144        Error::Msg(format!(
6145            "Op::MatMul {node_id:?}: data-determined row count {dyn_m:?} is unbound in \
6146             produced_syms at execute (its producer did not run / bind it)",
6147        ))
6148        .bt()
6149    })?;
6150    if rows > *m {
6151        return Err(Error::Msg(format!(
6152            "Op::MatMul {node_id:?}: resolved row count {rows} exceeds capacity {m}",
6153        ))
6154        .bt());
6155    }
6156    let mut patched = compiled.clone();
6157    patched.op_params = OpParams::Matmul {
6158        lhs_batch_dims: lhs_batch_dims.clone(),
6159        rhs_batch_dims: rhs_batch_dims.clone(),
6160        m: *m,
6161        n: *n,
6162        k: *k,
6163        m_compute: MatmulM::Rows(rows),
6164    };
6165    Ok(Some(patched))
6166}
6167
6168fn execute_work_item(
6169    item: &WorkItem,
6170    cache: &mut StorageCache,
6171    #[cfg_attr(
6172        not(any(feature = "cuda", feature = "vulkan")),
6173        allow(unused_variables)
6174    )]
6175    devices: &mut DeviceRegistry,
6176    layout_cache: &mut HashMap<NodeId, Layout>,
6177    produced_syms: &mut SymEnv,
6178    // Step E A4b open question #4 — "event only where waited": whether
6179    // THIS item's node id is in the realize's `WaitSet` (`will_be_waited`
6180    // in `pipelined.rs`, computed once per item by the caller). Forwarded
6181    // to every `execute_compiled_with_wait_hint` call below so a CUDA
6182    // kernel with no mid-walk reader skips its `Event` entirely.
6183    will_be_waited: bool,
6184    // CapturedRun executor build-out: persistent-output mode. `None` on
6185    // every existing realize path ⇒ byte-identical (fresh alloc, nothing
6186    // recorded). `Some(Record)` records each Kernel output's fixed Arc;
6187    // `Some(Reuse)` reuses the recorded buffer (no alloc — capture-safe)
6188    // and the write-into kernel path writes into it in place. Only the
6189    // `Kernel` arm consults it; every other arm ignores it.
6190    mut persistent: Option<&mut PersistentOutputs>,
6191    // GAP-415: where an index-reading CUDA kernel notes its index operand.
6192    #[cfg_attr(not(feature = "cuda"), allow(unused_variables))] index_reads: Option<
6193        &mut IndexReads,
6194    >,
6195) -> Result<CompletionHandle> {
6196    match &item.kind {
6197        WorkItemKind::ConstAdopt => {
6198            if !cache.contains_key(&item.node_id) {
6199                return Err(Error::Msg(format!(
6200                    "PipelinedExecutor: Const node {:?} not in input cache",
6201                    item.node_id
6202                ))
6203                .bt());
6204            }
6205            // Layout for input cache entries was seeded at realize
6206            // start; refresh from the WorkItem in case the side-table
6207            // was set after seeding.
6208            layout_cache.insert(item.node_id, item.output_layout.clone());
6209            Ok(CompletionHandle::Ready)
6210        }
6211        WorkItemKind::ViewOf { input } => {
6212            let input_arc = cache.get(input).cloned().ok_or_else(|| {
6213                Error::Msg(format!(
6214                    "PipelinedExecutor: view-op input {:?} of {:?} not realized",
6215                    input, item.node_id,
6216                ))
6217                .bt()
6218            })?;
6219            cache.insert(item.node_id, input_arc);
6220            layout_cache.insert(item.node_id, item.output_layout.clone());
6221            Ok(CompletionHandle::Ready)
6222        }
6223        WorkItemKind::SlotView { producer } => {
6224            // Op::View — multi-output projection. Same realization
6225            // shape as ViewOf: clone the producer's Storage Arc into
6226            // the View's cache slot. The WorkItem's output_layout was
6227            // computed at graph-build time by `Tensor::view`, with
6228            // the slot's byte_offset baked into start_offset (in
6229            // slot-dtype-element units). Downstream kernels reading
6230            // the producer's bytes as the slot's dtype starting at
6231            // that offset see the slot's typed window.
6232            let producer_arc = cache.get(producer).cloned().ok_or_else(|| {
6233                Error::Msg(format!(
6234                    "PipelinedExecutor: Op::View producer {:?} of {:?} not realized",
6235                    producer, item.node_id,
6236                ))
6237                .bt()
6238            })?;
6239            cache.insert(item.node_id, producer_arc);
6240            layout_cache.insert(item.node_id, item.output_layout.clone());
6241            Ok(CompletionHandle::Ready)
6242        }
6243        WorkItemKind::SlotOwn { producer, slot } => {
6244            // Op::ViewOwned — allocate a fresh Storage of the slot's
6245            // (shape, dtype) on the producer's device and copy the
6246            // slot's bytes in. Per-backend fast paths:
6247            //   - CPU:    direct &[u8]→&mut[u8] memcpy via CpuStorageBytes
6248            //   - CUDA:   D2D via CudaStorageBytes::slot_copy_to_new
6249            //             (cuMemcpyDtoDAsync with offset src pointer)
6250            //   - Vulkan: vkCmdCopyBuffer via
6251            //             VulkanBackend::slot_copy_to_new_handle
6252            //             (srcOffset/dstOffset/size)
6253            // For backends without a copy-with-offset hook we fall
6254            // back to a host round-trip (`to_host_buffer_dyn` →
6255            // slice → `storage_from_host_buffer_owned_dyn`), which
6256            // works but is wasteful.
6257            let producer_arc = cache.get(producer).cloned().ok_or_else(|| {
6258                Error::Msg(format!(
6259                    "PipelinedExecutor: Op::ViewOwned producer {:?} of {:?} not realized",
6260                    producer, item.node_id,
6261                ))
6262                .bt()
6263            })?;
6264            let new_storage = {
6265                let guard = producer_arc
6266                    .read()
6267                    .map_err(|_| poisoned("ViewOwned producer storage"))?;
6268                let bundle = guard.bundle().ok_or_else(|| {
6269                    Error::Msg(format!(
6270                        "Op::ViewOwned: producer {:?} has no bundle side-table \
6271                         — the multi-output authoring contract requires \
6272                         Storage::with_bundle / new_bundled at allocation \
6273                         time. Node {:?} slot {} cannot resolve its source.",
6274                        producer, item.node_id, slot,
6275                    ))
6276                    .bt()
6277                })?;
6278                let sv = bundle.get(*slot as usize).cloned().ok_or_else(|| {
6279                    Error::Msg(format!(
6280                        "Op::ViewOwned: slot {} out of range for producer {:?} \
6281                         (bundle has {} slots)",
6282                        slot,
6283                        producer,
6284                        bundle.len(),
6285                    ))
6286                    .bt()
6287                })?;
6288                use fuel_memory::BackendStorage;
6289                match &guard.inner {
6290                    BackendStorage::Cpu(cpu_bytes) => {
6291                        let src_bytes = cpu_bytes.bytes();
6292                        let end = sv.byte_offset + sv.len_bytes();
6293                        if end > src_bytes.len() {
6294                            return Err(Error::Msg(format!(
6295                                "Op::ViewOwned: slot {} byte range [{}..{}) \
6296                                 exceeds producer's CPU byte length {}",
6297                                slot,
6298                                sv.byte_offset,
6299                                end,
6300                                src_bytes.len(),
6301                            ))
6302                            .bt());
6303                        }
6304                        let owned = fuel_cpu_backend::CpuStorageBytes::from_bytes(
6305                            &src_bytes[sv.byte_offset..end],
6306                        );
6307                        fuel_memory::Storage::new(BackendStorage::Cpu(owned), sv.dtype)
6308                    }
6309                    #[cfg(feature = "cuda")]
6310                    BackendStorage::Cuda(cuda_bytes) => {
6311                        let dst = cuda_bytes.slot_copy_to_new(sv.byte_offset, sv.len_bytes())?;
6312                        fuel_memory::Storage::new(BackendStorage::Cuda(dst), sv.dtype)
6313                    }
6314                    #[cfg(feature = "vulkan")]
6315                    BackendStorage::Vulkan(vk_bytes) => {
6316                        let backend = vk_bytes.backend().ok_or_else(|| {
6317                            Error::Msg(format!(
6318                                "Op::ViewOwned: producer {:?} is on Vulkan but \
6319                                 its storage has no VulkanBackend handle. \
6320                                 Storages flowing through the pipelined executor \
6321                                 must be constructed via alloc_bytes_handle / \
6322                                 upload_bytes_handle so the bundle's slot extraction \
6323                                 path can reach the backend.",
6324                                producer,
6325                            ))
6326                            .bt()
6327                        })?;
6328                        let dst = backend.slot_copy_to_new_handle(
6329                            vk_bytes,
6330                            sv.byte_offset,
6331                            sv.len_bytes(),
6332                        )?;
6333                        fuel_memory::Storage::new(BackendStorage::Vulkan(dst), sv.dtype)
6334                    }
6335                    #[allow(unreachable_patterns)]
6336                    _ => {
6337                        return Err(Error::Msg(format!(
6338                            "Op::ViewOwned: producer {:?} is on a backend \
6339                             without a slot-copy-with-offset hook \
6340                             (CPU + CUDA + Vulkan wired). Add a per-backend \
6341                             `slot_copy_to_new`-equivalent and extend the \
6342                             match arm.",
6343                            producer,
6344                        ))
6345                        .bt());
6346                    }
6347                }
6348            };
6349            cache.insert(item.node_id, Arc::new(RwLock::new(new_storage)));
6350            layout_cache.insert(item.node_id, item.output_layout.clone());
6351            // A4b-1: Op::ViewOwned's slot copy (CUDA D2D) is same-stream; its
6352            // completion is carried by the realize-end full-stream sync in
6353            // `to_cpu_bytes` (unchanged) — `Ready` here is behavior-preserving.
6354            Ok(CompletionHandle::Ready)
6355        }
6356        WorkItemKind::WriteSlice { dest, source } => {
6357            let compiled = item.compiled.as_ref().ok_or_else(|| {
6358                Error::Msg(format!(
6359                    "PipelinedExecutor: WriteSlice work item {:?} has no compiled node",
6360                    item.node_id,
6361                ))
6362                .bt()
6363            })?;
6364            // Increment 2b: if the offset is DATA-DETERMINED, resolve it from
6365            // the producer-bound `produced_syms` and run the kernel against
6366            // the patched (resolved-range) node. `None` on the common path.
6367            let patched_ws = resolve_deferred_write_slice(compiled, produced_syms, item.node_id)?;
6368            let compiled = patched_ws.as_ref().unwrap_or(compiled);
6369            let dest_arc = cache.get(dest).cloned().ok_or_else(|| {
6370                Error::Msg(format!(
6371                    "PipelinedExecutor: WriteSlice destination {:?} of {:?} not realized",
6372                    dest, item.node_id,
6373                ))
6374                .bt()
6375            })?;
6376            let source_arc = cache.get(source).cloned().ok_or_else(|| {
6377                Error::Msg(format!(
6378                    "PipelinedExecutor: WriteSlice source {:?} of {:?} not realized",
6379                    source, item.node_id,
6380                ))
6381                .bt()
6382            })?;
6383            let dest_layout = layout_cache.get(dest).cloned().ok_or_else(|| {
6384                Error::Msg(format!(
6385                    "PipelinedExecutor: WriteSlice destination {:?} of {:?} has no cached layout",
6386                    dest, item.node_id,
6387                ))
6388                .bt()
6389            })?;
6390            let source_layout = layout_cache.get(source).cloned().ok_or_else(|| {
6391                Error::Msg(format!(
6392                    "PipelinedExecutor: WriteSlice source {:?} of {:?} has no cached layout",
6393                    source, item.node_id,
6394                ))
6395                .bt()
6396            })?;
6397            // v1 contract: destination must be contiguous + zero
6398            // offset. Strided dests would force the kernel to walk
6399            // both source and dest strides; defer until KV cache
6400            // exposes a non-contig dest. Source CAN be non-contig —
6401            // we auto-contiguize it here so the kernel sees a flat
6402            // slab.
6403            if !dest_layout.is_contiguous() || dest_layout.start_offset() != 0 {
6404                return Err(Error::Msg(format!(
6405                    "Op::WriteSlice (Phase E.3.2 v1): destination {:?} must be \
6406                     contiguous + zero-offset; got Layout {:?}",
6407                    dest, dest_layout,
6408                ))
6409                .bt());
6410            }
6411            let source_arc_contig = {
6412                let s_dtype = source_arc
6413                    .read()
6414                    .map_err(|_| poisoned("WriteSlice source storage"))?
6415                    .dtype;
6416                let s_len_bytes = source_arc
6417                    .read()
6418                    .map_err(|_| poisoned("WriteSlice source storage"))?
6419                    .inner
6420                    .len_bytes();
6421                let layout_bytes = source_layout.shape().elem_count() * s_dtype.size_in_bytes();
6422                let bytes_match_shape = s_len_bytes == layout_bytes;
6423                let already_contig = source_layout.is_contiguous()
6424                    && source_layout.start_offset() == 0
6425                    && bytes_match_shape;
6426                if already_contig {
6427                    source_arc
6428                } else {
6429                    auto_contiguize(&source_arc, &source_layout)?
6430                }
6431            };
6432            let source_layout_kernel = fuel_ir::Layout::contiguous(source_layout.shape().clone());
6433            // The kernel sees inputs=[source] and outputs=[dest_arc].
6434            // The dest input slot is intentionally absent — the kernel
6435            // doesn't read from dest; it only writes to its bytes
6436            // through the output slot's write lock.
6437            let input_arcs = vec![source_arc_contig];
6438            let mut output_arcs = vec![dest_arc.clone()];
6439            let kernel_layouts = vec![source_layout_kernel, dest_layout.clone()];
6440            // A4b-1: defer the wait — return the handle to the realize loop.
6441            let handle = execute_compiled_with_wait_hint(
6442                compiled,
6443                &input_arcs,
6444                &mut output_arcs,
6445                &kernel_layouts,
6446                will_be_waited,
6447            )?;
6448            // Adopt the dest Arc at this WriteSlice node's slot. The
6449            // realize loop's destructive_input cleanup evicts the
6450            // dest's own NodeId from the cache afterward — downstream
6451            // readers go through this node's NodeId.
6452            cache.insert(item.node_id, dest_arc);
6453            layout_cache.insert(item.node_id, item.output_layout.clone());
6454            Ok(handle)
6455        }
6456        WorkItemKind::WriteSliceRotating {
6457            dest,
6458            source,
6459            position,
6460        } => {
6461            // Same shape as WriteSlice but with a position input.
6462            // Kernel sees `[source, position]` as inputs; `dest` is the
6463            // pre-allocated output buffer (in-place adoption).
6464            let compiled = item.compiled.as_ref().ok_or_else(|| {
6465                Error::Msg(format!(
6466                    "PipelinedExecutor: WriteSliceRotating work item {:?} has no compiled node",
6467                    item.node_id,
6468                ))
6469                .bt()
6470            })?;
6471            let dest_arc = cache.get(dest).cloned().ok_or_else(|| {
6472                Error::Msg(format!(
6473                    "PipelinedExecutor: WriteSliceRotating destination {:?} of {:?} not realized",
6474                    dest, item.node_id,
6475                ))
6476                .bt()
6477            })?;
6478            let source_arc = cache.get(source).cloned().ok_or_else(|| {
6479                Error::Msg(format!(
6480                    "PipelinedExecutor: WriteSliceRotating source {:?} of {:?} not realized",
6481                    source, item.node_id,
6482                ))
6483                .bt()
6484            })?;
6485            let position_arc = cache.get(position).cloned().ok_or_else(|| {
6486                Error::Msg(format!(
6487                    "PipelinedExecutor: WriteSliceRotating position {:?} of {:?} not realized",
6488                    position, item.node_id,
6489                ))
6490                .bt()
6491            })?;
6492            let dest_layout = layout_cache.get(dest).cloned().ok_or_else(|| {
6493                Error::Msg(format!(
6494                    "PipelinedExecutor: WriteSliceRotating destination {:?} of {:?} has no cached layout",
6495                    dest, item.node_id,
6496                ))
6497                .bt()
6498            })?;
6499            let source_layout = layout_cache.get(source).cloned().ok_or_else(|| {
6500                Error::Msg(format!(
6501                    "PipelinedExecutor: WriteSliceRotating source {:?} of {:?} has no cached layout",
6502                    source, item.node_id,
6503                ))
6504                .bt()
6505            })?;
6506            // v1: destination contiguous + zero offset (same as WriteSlice).
6507            if !dest_layout.is_contiguous() || dest_layout.start_offset() != 0 {
6508                return Err(Error::Msg(format!(
6509                    "Op::WriteSliceRotating (v1): destination {:?} must be \
6510                     contiguous + zero-offset; got Layout {:?}",
6511                    dest, dest_layout,
6512                ))
6513                .bt());
6514            }
6515            let source_arc_contig = {
6516                let s_dtype = source_arc
6517                    .read()
6518                    .map_err(|_| poisoned("WriteSliceRotating source storage"))?
6519                    .dtype;
6520                let s_len_bytes = source_arc
6521                    .read()
6522                    .map_err(|_| poisoned("WriteSliceRotating source storage"))?
6523                    .inner
6524                    .len_bytes();
6525                let layout_bytes = source_layout.shape().elem_count() * s_dtype.size_in_bytes();
6526                let bytes_match_shape = s_len_bytes == layout_bytes;
6527                let already_contig = source_layout.is_contiguous()
6528                    && source_layout.start_offset() == 0
6529                    && bytes_match_shape;
6530                if already_contig {
6531                    source_arc
6532                } else {
6533                    auto_contiguize(&source_arc, &source_layout)?
6534                }
6535            };
6536            let source_layout_kernel = fuel_ir::Layout::contiguous(source_layout.shape().clone());
6537            let position_layout = fuel_ir::Layout::contiguous(fuel_ir::Shape::from_dims(&[]));
6538            let input_arcs = vec![source_arc_contig, position_arc];
6539            let mut output_arcs = vec![dest_arc.clone()];
6540            let kernel_layouts = vec![source_layout_kernel, position_layout, dest_layout.clone()];
6541            // A4b-1: defer the wait — return the handle to the realize loop.
6542            let handle = execute_compiled_with_wait_hint(
6543                compiled,
6544                &input_arcs,
6545                &mut output_arcs,
6546                &kernel_layouts,
6547                will_be_waited,
6548            )?;
6549            cache.insert(item.node_id, dest_arc);
6550            layout_cache.insert(item.node_id, item.output_layout.clone());
6551            Ok(handle)
6552        }
6553        WorkItemKind::WriteSliceDoff {
6554            dest,
6555            source,
6556            offset,
6557        } => {
6558            // Same shape as WriteSliceRotating: kernel sees
6559            // `[source, offset]` as inputs; `dest` is the pre-allocated
6560            // output buffer (in-place adoption). The offset (rank-0
6561            // I64) is passed through as a kernel input — the CUDA
6562            // wrapper threads its device pointer straight to the kernel
6563            // (no D2H), which is what makes a captured graph replay at
6564            // the host-updated position.
6565            let compiled = item.compiled.as_ref().ok_or_else(|| {
6566                Error::Msg(format!(
6567                    "PipelinedExecutor: WriteSliceDoff work item {:?} has no compiled node",
6568                    item.node_id,
6569                ))
6570                .bt()
6571            })?;
6572            let dest_arc = cache.get(dest).cloned().ok_or_else(|| {
6573                Error::Msg(format!(
6574                    "PipelinedExecutor: WriteSliceDoff destination {:?} of {:?} not realized",
6575                    dest, item.node_id,
6576                ))
6577                .bt()
6578            })?;
6579            let source_arc = cache.get(source).cloned().ok_or_else(|| {
6580                Error::Msg(format!(
6581                    "PipelinedExecutor: WriteSliceDoff source {:?} of {:?} not realized",
6582                    source, item.node_id,
6583                ))
6584                .bt()
6585            })?;
6586            let offset_arc = cache.get(offset).cloned().ok_or_else(|| {
6587                Error::Msg(format!(
6588                    "PipelinedExecutor: WriteSliceDoff offset {:?} of {:?} not realized",
6589                    offset, item.node_id,
6590                ))
6591                .bt()
6592            })?;
6593            let dest_layout = layout_cache.get(dest).cloned().ok_or_else(|| {
6594                Error::Msg(format!(
6595                    "PipelinedExecutor: WriteSliceDoff destination {:?} of {:?} has no cached layout",
6596                    dest, item.node_id,
6597                ))
6598                .bt()
6599            })?;
6600            let source_layout = layout_cache.get(source).cloned().ok_or_else(|| {
6601                Error::Msg(format!(
6602                    "PipelinedExecutor: WriteSliceDoff source {:?} of {:?} has no cached layout",
6603                    source, item.node_id,
6604                ))
6605                .bt()
6606            })?;
6607            // v1: destination contiguous + zero offset (same as WriteSlice).
6608            if !dest_layout.is_contiguous() || dest_layout.start_offset() != 0 {
6609                return Err(Error::Msg(format!(
6610                    "Op::WriteSliceDoff (v1): destination {:?} must be \
6611                     contiguous + zero-offset; got Layout {:?}",
6612                    dest, dest_layout,
6613                ))
6614                .bt());
6615            }
6616            let source_arc_contig = {
6617                let s_dtype = source_arc
6618                    .read()
6619                    .map_err(|_| poisoned("WriteSliceDoff source storage"))?
6620                    .dtype;
6621                let s_len_bytes = source_arc
6622                    .read()
6623                    .map_err(|_| poisoned("WriteSliceDoff source storage"))?
6624                    .inner
6625                    .len_bytes();
6626                let layout_bytes = source_layout.shape().elem_count() * s_dtype.size_in_bytes();
6627                let bytes_match_shape = s_len_bytes == layout_bytes;
6628                let already_contig = source_layout.is_contiguous()
6629                    && source_layout.start_offset() == 0
6630                    && bytes_match_shape;
6631                if already_contig {
6632                    source_arc
6633                } else {
6634                    auto_contiguize(&source_arc, &source_layout)?
6635                }
6636            };
6637            let source_layout_kernel = fuel_ir::Layout::contiguous(source_layout.shape().clone());
6638            let offset_layout = fuel_ir::Layout::contiguous(fuel_ir::Shape::from_dims(&[]));
6639            let input_arcs = vec![source_arc_contig, offset_arc];
6640            let mut output_arcs = vec![dest_arc.clone()];
6641            let kernel_layouts = vec![source_layout_kernel, offset_layout, dest_layout.clone()];
6642            // A4b-1: defer the wait — return the handle to the realize loop.
6643            let handle = execute_compiled_with_wait_hint(
6644                compiled,
6645                &input_arcs,
6646                &mut output_arcs,
6647                &kernel_layouts,
6648                will_be_waited,
6649            )?;
6650            cache.insert(item.node_id, dest_arc);
6651            layout_cache.insert(item.node_id, item.output_layout.clone());
6652            Ok(handle)
6653        }
6654        WorkItemKind::Alloc { target_location } => {
6655            // Op::Alloc { target }: allocate a fresh, zero-init storage
6656            // on target_location. No inputs, no kernel call — direct
6657            // executor dispatch. For non-CPU targets the per-backend
6658            // device handle comes from the `DeviceRegistry` the caller
6659            // handed the realize (a `*_with_devices` entry point).
6660            // Used only by the Vulkan arm below (alloc_bytes_handle); a
6661            // default-feature build sees it unused. GAP-229: 68161981's
6662            // unused_variables --fix renamed it `_n_bytes` at default
6663            // features and broke `--features vulkan` (E0425). Guard the
6664            // decline instead of the name so the binding stays usable.
6665            #[cfg_attr(not(feature = "vulkan"), allow(unused_variables))]
6666            let n_bytes = item.elem_count * item.dtype.size_in_bytes();
6667            let alloced: Storage = match target_location {
6668                // CPU has no separate uninit alloc primitive in safe
6669                // Rust (`vec![0; n]` is the canonical path). Op::Alloc
6670                // on CPU returns zero-init storage; the following
6671                // Op::ZeroFill is a redundant memset the optimizer
6672                // can elide and LLVM folds away regardless.
6673                DeviceLocation::Cpu => fuel_memory::alloc_cpu_zeroed(item.dtype, item.elem_count)?,
6674                #[cfg(feature = "cuda")]
6675                DeviceLocation::Cuda { gpu_id } => {
6676                    let cuda_dev = devices.cuda(*gpu_id).ok_or_else(|| {
6677                        Error::Msg(format!(
6678                            "Op::Alloc on Cuda {{ gpu_id: {} }}: no CUDA \
6679                             device registered for this place. Hand the device to \
6680                             the realize in a `DeviceRegistry` (a `*_with_devices` \
6681                             entry point).",
6682                            gpu_id,
6683                        ))
6684                        .bt()
6685                    })?;
6686                    // Phase 3a follow-up: true uninit alloc via
6687                    // baracuda alpha.30's unsafe alloc. The bytes are
6688                    // uninit until a subsequent Op::ZeroFill or full-
6689                    // overwrite op runs. The byte-storage Arc has no
6690                    // typed-slice accessor that would dereference
6691                    // uninit bytes.
6692                    let cuda_bytes =
6693                        fuel_cuda_backend::CudaStorageBytes::alloc_uninit(&cuda_dev, n_bytes)?;
6694                    Storage::new(fuel_memory::BackendStorage::Cuda(cuda_bytes), item.dtype)
6695                }
6696                #[cfg(not(feature = "cuda"))]
6697                DeviceLocation::Cuda { .. } => {
6698                    return Err(Error::Msg(
6699                        "Op::Alloc on Cuda but fuel-storage wasn't built \
6700                         with --features cuda"
6701                            .to_string(),
6702                    )
6703                    .bt());
6704                }
6705                #[cfg(feature = "vulkan")]
6706                DeviceLocation::Vulkan { gpu_id } => {
6707                    let backend = devices.vulkan(*gpu_id).ok_or_else(|| {
6708                        Error::Msg(format!(
6709                            "Op::Alloc on Vulkan {{ gpu_id: {} }}: no Vulkan \
6710                             device registered for this place. Hand the device to \
6711                             the realize in a `DeviceRegistry` (a `*_with_devices` \
6712                             entry point).",
6713                            gpu_id,
6714                        ))
6715                        .bt()
6716                    })?;
6717                    // Phase 3a follow-up: true uninit alloc. The old
6718                    // `upload_bytes_handle(vec![0u8; n])` host-staged
6719                    // zeros (~2× the bandwidth of a device-side fill);
6720                    // we now allocate uninit and rely on a paired
6721                    // Op::ZeroFill (vkCmdFillBuffer) for the
6722                    // initialization. Faster KV-cache init on Vulkan.
6723                    let vk_bytes = backend.alloc_bytes_handle(n_bytes)?;
6724                    Storage::new(fuel_memory::BackendStorage::Vulkan(vk_bytes), item.dtype)
6725                }
6726                #[cfg(not(feature = "vulkan"))]
6727                DeviceLocation::Vulkan { .. } => {
6728                    return Err(Error::Msg(
6729                        "Op::Alloc on Vulkan but fuel-storage wasn't built \
6730                         with --features vulkan"
6731                            .to_string(),
6732                    )
6733                    .bt());
6734                }
6735                other => {
6736                    return Err(Error::Msg(format!(
6737                        "Op::Alloc on {:?}: target not yet wired (CPU + \
6738                         CUDA + Vulkan land in Phase 3a of bridge-retirement; \
6739                         Metal extends when its byte-storage substrate is \
6740                         ready).",
6741                        other,
6742                    ))
6743                    .bt());
6744                }
6745            };
6746            cache.insert(item.node_id, Arc::new(RwLock::new(alloced)));
6747            layout_cache.insert(item.node_id, item.output_layout.clone());
6748            Ok(CompletionHandle::Ready)
6749        }
6750        WorkItemKind::Iota {
6751            len,
6752            target_location,
6753        } => {
6754            // Op::Iota { len }: 0-input F32 position generator
6755            // [0.0, 1.0, …, (len-1)]. Direct executor dispatch (no kernel /
6756            // binding-table lookup), like WorkItemKind::Alloc. Generated on the host, then, for a
6757            // CUDA target, uploaded (an Iota is a tiny index constant: a device kernel would cost a
6758            // launch to save a few hundred bytes of transfer). The decomposed PAGED_ATTN recipe
6759            // (GAP-380) is the CUDA consumer; a build without the `cuda` feature, or any other
6760            // non-CPU backend, still errors rather than guessing.
6761            #[cfg(feature = "cuda")]
6762            if item.target_backend == BackendId::Cuda {
6763                let gpu_id = match target_location {
6764                    Some(DeviceLocation::Cuda { gpu_id }) => *gpu_id,
6765                    _ => 0,
6766                };
6767                let cuda_dev = devices.cuda(gpu_id).ok_or_else(|| {
6768                    Error::Msg(format!(
6769                        "Op::Iota on Cuda {{ gpu_id: {gpu_id} }}: no CUDA device registered for                          this place. Hand the device to the realize via a `*_with_devices` entry point."
6770                    ))
6771                    .bt()
6772                })?;
6773                let bytes: Vec<u8> = (0..*len).flat_map(|i| (i as f32).to_le_bytes()).collect();
6774                let cuda_bytes =
6775                    fuel_cuda_backend::CudaStorageBytes::from_cpu_bytes(&cuda_dev, &bytes)?;
6776                let st = Storage::new(fuel_memory::BackendStorage::Cuda(cuda_bytes), item.dtype);
6777                cache.insert(item.node_id, Arc::new(RwLock::new(st)));
6778                layout_cache.insert(item.node_id, item.output_layout.clone());
6779                return Ok(CompletionHandle::Ready);
6780            }
6781            #[cfg(not(feature = "cuda"))]
6782            let _ = target_location;
6783            if item.target_backend != BackendId::Cpu {
6784                return Err(Error::Msg(format!(
6785                    "WorkItemKind::Iota: only CPU is wired today, got {:?}",
6786                    item.target_backend,
6787                ))
6788                .bt());
6789            }
6790            let v: Vec<f32> = (0..*len).map(|i| i as f32).collect();
6791            let iota = fuel_memory::from_slice_cpu(&v);
6792            cache.insert(item.node_id, Arc::new(RwLock::new(iota)));
6793            layout_cache.insert(item.node_id, item.output_layout.clone());
6794            Ok(CompletionHandle::Ready)
6795        }
6796        WorkItemKind::ZeroFill => {
6797            // Op::ZeroFill: in-place zero the input's bytes. Output
6798            // adopts the input's Storage Arc (same Storage; bytes
6799            // are mutated). Direct per-backend dispatch — no kernel
6800            // call, no binding-table lookup.
6801            if item.inputs.len() != 1 {
6802                return Err(Error::Msg(format!(
6803                    "PipelinedExecutor: ZeroFill work item {:?} expects \
6804                     1 input, got {}",
6805                    item.node_id,
6806                    item.inputs.len(),
6807                ))
6808                .bt());
6809            }
6810            let src_id = item.inputs[0];
6811            let src_arc = cache.get(&src_id).cloned().ok_or_else(|| {
6812                Error::Msg(format!(
6813                    "PipelinedExecutor: ZeroFill input {:?} of {:?} \
6814                     not realized",
6815                    src_id, item.node_id,
6816                ))
6817                .bt()
6818            })?;
6819            // Per-backend in-place fill. Acquired the write lock once
6820            // for the duration of the fill — kernels on async backends
6821            // (CUDA / Vulkan) issue the memset and return; the fence
6822            // happens when downstream readers acquire the read lock
6823            // through the executor's standard synchronization path.
6824            {
6825                let mut guard = src_arc
6826                    .write()
6827                    .map_err(|_| poisoned("ZeroFill destination storage"))?;
6828                match &mut guard.inner {
6829                    fuel_memory::BackendStorage::Cpu(c) => {
6830                        let bytes = c.bytes_mut();
6831                        bytes.fill(0);
6832                    }
6833                    #[cfg(feature = "cuda")]
6834                    fuel_memory::BackendStorage::Cuda(c) => {
6835                        c.zero_async()?;
6836                    }
6837                    #[cfg(feature = "vulkan")]
6838                    fuel_memory::BackendStorage::Vulkan(v) => {
6839                        let backend = v
6840                            .backend()
6841                            .ok_or_else(|| {
6842                                Error::Msg(
6843                                    "Op::ZeroFill on Vulkan: input has no \
6844                                 attached backend handle. Storage must \
6845                                 come from VulkanBackend::alloc_bytes_handle \
6846                                 / upload_bytes_handle."
6847                                        .to_string(),
6848                                )
6849                                .bt()
6850                            })?
6851                            .clone();
6852                        backend.fill_bytes_zero(v)?;
6853                    }
6854                    #[allow(unreachable_patterns)]
6855                    other => {
6856                        return Err(Error::Msg(format!(
6857                            "Op::ZeroFill: backend not wired ({other:?}); \
6858                             CPU + CUDA + Vulkan covered, Metal extends \
6859                             when its byte-storage substrate is ready.",
6860                        ))
6861                        .bt());
6862                    }
6863                }
6864            }
6865            // Adopt the (now-zero) Storage Arc at this node's slot.
6866            // Downstream readers go through `node_id`; the original
6867            // input's NodeId is evicted from the cache by the
6868            // realize loop's destructive_input cleanup.
6869            cache.insert(item.node_id, src_arc);
6870            layout_cache.insert(item.node_id, item.output_layout.clone());
6871            // A4b-1: ZeroFill's CUDA memset is same-stream (and Op::Alloc
6872            // typically zero-inits, so this is usually elided). Its completion
6873            // is carried by the realize-end full-stream sync in `to_cpu_bytes`
6874            // (unchanged) and same-stream ordering — `Ready` is behavior-preserving.
6875            Ok(CompletionHandle::Ready)
6876        }
6877        WorkItemKind::Copy { target_location } | WorkItemKind::Move { target_location } => {
6878            // Op::Copy / Op::Move { target }: kernel lookup at
6879            // (OpKind::Copy, [dt, dt], source_backend) — the wrapper
6880            // downloads from its own residency into a freshly-
6881            // allocated output on `target_location`. We auto-
6882            // contiguize the input first so the kernel always sees
6883            // the logical view's bytes (a transpose-view source
6884            // materializes into a contiguous buffer before download).
6885            //
6886            // Move shares this entire data-movement half; its
6887            // destructive half (release the source) is driven by the
6888            // realize loop's `destructive_input` cleanup after this
6889            // arm returns — see `WorkItemKind::Move`.
6890            let op_label = if matches!(item.kind, WorkItemKind::Move { .. }) {
6891                "Move"
6892            } else {
6893                "Copy"
6894            };
6895            let compiled = item.compiled.as_ref().ok_or_else(|| {
6896                Error::Msg(format!(
6897                    "PipelinedExecutor: {op_label} work item {:?} has no compiled node",
6898                    item.node_id,
6899                ))
6900                .bt()
6901            })?;
6902            if item.inputs.len() != 1 {
6903                return Err(Error::Msg(format!(
6904                    "PipelinedExecutor: {op_label} work item {:?} expects 1 input, got {}",
6905                    item.node_id,
6906                    item.inputs.len(),
6907                ))
6908                .bt());
6909            }
6910            let src_id = item.inputs[0];
6911            let src_arc = cache.get(&src_id).cloned().ok_or_else(|| {
6912                Error::Msg(format!(
6913                    "PipelinedExecutor: {op_label} input {:?} of {:?} not realized",
6914                    src_id, item.node_id,
6915                ))
6916                .bt()
6917            })?;
6918            // Multi-output Option C guard: Op::Copy on a bundled
6919            // producer would silently drop the bundle metadata on
6920            // the destination, and the auto-contiguize step below
6921            // would treat the bundle as a flat slot-0-shaped buffer
6922            // and corrupt non-primary slots. Until the per-backend
6923            // whole-bundle-Copy hook lands, point callers at the
6924            // supported per-slot path:
6925            // Op::View → Op::Copy → Op::ViewOwned.
6926            //
6927            // Exception: when the immediate input is an Op::View
6928            // projection (its layout's byte extent is strictly less
6929            // than the bundle's total bytes), the View has already
6930            // narrowed the slab. auto-contiguize walks the View's
6931            // layout and produces a flat slot-shaped buffer that's
6932            // correctly sized — no data loss, no slot corruption.
6933            // The guard only fires when the Copy targets the bundle
6934            // root directly.
6935            {
6936                let guard = src_arc
6937                    .read()
6938                    .map_err(|_| poisoned("Copy source storage"))?;
6939                if guard.is_bundled() {
6940                    let layout_bytes_for_guard = layout_cache
6941                        .get(&src_id)
6942                        .map(|l| l.shape().elem_count() * guard.dtype.size_in_bytes())
6943                        .unwrap_or(usize::MAX);
6944                    let bundle_bytes = guard.inner.len_bytes();
6945                    let is_whole_bundle = layout_bytes_for_guard >= bundle_bytes;
6946                    if is_whole_bundle {
6947                        return Err(Error::Msg(format!(
6948                            "PipelinedExecutor: Op::{op_label} on a bundled producer \
6949                             ({:?}) is not yet supported (Option C followup). \
6950                             Use Op::View → Op::Copy → Op::ViewOwned for \
6951                             per-slot cross-device moves, or wait for the \
6952                             per-backend whole-bundle-Copy hook.",
6953                            src_id,
6954                        ))
6955                        .bt());
6956                    }
6957                }
6958            }
6959            let src_layout = layout_cache.get(&src_id).cloned().ok_or_else(|| {
6960                Error::Msg(format!(
6961                    "PipelinedExecutor: {op_label} input {:?} of {:?} has no cached layout",
6962                    src_id, item.node_id,
6963                ))
6964                .bt()
6965            })?;
6966            let src_dtype = src_arc
6967                .read()
6968                .map_err(|_| poisoned("Copy source storage"))?
6969                .dtype;
6970            let src_len_bytes = src_arc
6971                .read()
6972                .map_err(|_| poisoned("Copy source storage"))?
6973                .inner
6974                .len_bytes();
6975            let layout_bytes = src_layout.shape().elem_count() * src_dtype.size_in_bytes();
6976            let bytes_match_shape = src_len_bytes == layout_bytes;
6977            let already_contig =
6978                src_layout.is_contiguous() && src_layout.start_offset() == 0 && bytes_match_shape;
6979            let src_input = if already_contig {
6980                src_arc
6981            } else {
6982                auto_contiguize(&src_arc, &src_layout)?
6983            };
6984            let kernel_input_layout = fuel_ir::Layout::contiguous(src_layout.shape().clone());
6985            // CapturedRun build-out (4b-ζ): in Reuse (capture/replay) mode,
6986            // reuse the fixed-address buffer recorded during the warm run
6987            // instead of allocating — device allocation is illegal inside a
6988            // capture scope. Only a same-device CUDA target_location ever
6989            // reaches Reuse mode for a Copy node in practice: capture_decode's
6990            // validation loop rejects every Cpu/Vulkan target_location before
6991            // a capture scope is ever entered (Move is rejected unconditionally
6992            // there too), so this arm trusts that invariant rather than
6993            // re-deriving it — the `DeviceLocation::Cuda` guard below is just
6994            // belt-and-suspenders for any other Reuse-mode caller.
6995            let reuse_arc = match &persistent {
6996                Some(p) if p.mode == PersistentMode::Reuse => match target_location {
6997                    DeviceLocation::Cuda { .. } => p.map.get(&item.node_id).cloned(),
6998                    _ => None,
6999                },
7000                _ => None,
7001            };
7002            // Allocate the output on `target_location`. Phase 2
7003            // covered D2H (target=Cpu); Phase 3b extends to H2D
7004            // (target=Cuda / Vulkan from a CPU source). For non-CPU
7005            // targets the device handle comes from the caller's
7006            // `DeviceRegistry` (a `*_with_devices` entry point), as for
7007            // Op::Alloc.
7008            // Used only by the Vulkan arm below (alloc_bytes_handle); a
7009            // default-feature build sees it unused. GAP-229: 68161981's
7010            // unused_variables --fix renamed it `_n_bytes` at default
7011            // features and broke `--features vulkan` (E0425). Guard the
7012            // decline instead of the name so the binding stays usable.
7013            #[cfg_attr(not(feature = "vulkan"), allow(unused_variables))]
7014            let n_bytes = item.elem_count * item.dtype.size_in_bytes();
7015            let input_arcs = vec![src_input];
7016            let mut output_arcs = if let Some(arc) = reuse_arc {
7017                vec![arc]
7018            } else {
7019                let output = match target_location {
7020                    DeviceLocation::Cpu => {
7021                        fuel_memory::alloc_cpu_zeroed(item.dtype, item.elem_count)?
7022                    }
7023                    #[cfg(feature = "cuda")]
7024                    DeviceLocation::Cuda { gpu_id } => {
7025                        let cuda_dev = devices.cuda(*gpu_id).ok_or_else(|| {
7026                            Error::Msg(format!(
7027                                "Op::{op_label} on Cuda {{ gpu_id: {} }}: no CUDA \
7028                                 device registered for this place. Hand the device to \
7029                                 the realize in a `DeviceRegistry` (a `*_with_devices` \
7030                                 entry point) before an H2D Op::{op_label}.",
7031                                gpu_id,
7032                            ))
7033                            .bt()
7034                        })?;
7035                        let cuda_bytes =
7036                            fuel_cuda_backend::CudaStorageBytes::alloc_uninit(&cuda_dev, n_bytes)?;
7037                        Storage::new(fuel_memory::BackendStorage::Cuda(cuda_bytes), item.dtype)
7038                    }
7039                    #[cfg(not(feature = "cuda"))]
7040                    DeviceLocation::Cuda { .. } => {
7041                        return Err(Error::Msg(format!(
7042                            "Op::{op_label} target Cuda but fuel-storage wasn't built \
7043                             with --features cuda",
7044                        ))
7045                        .bt());
7046                    }
7047                    #[cfg(feature = "vulkan")]
7048                    DeviceLocation::Vulkan { gpu_id } => {
7049                        let backend = devices.vulkan(*gpu_id).ok_or_else(|| {
7050                            Error::Msg(format!(
7051                                "Op::{op_label} on Vulkan {{ gpu_id: {} }}: no Vulkan \
7052                                 device registered for this place. Hand the device to \
7053                                 the realize in a `DeviceRegistry` (a `*_with_devices` \
7054                                 entry point) before an H2D Op::{op_label}.",
7055                                gpu_id,
7056                            ))
7057                            .bt()
7058                        })?;
7059                        let vk_bytes = backend.alloc_bytes_handle(n_bytes)?;
7060                        Storage::new(fuel_memory::BackendStorage::Vulkan(vk_bytes), item.dtype)
7061                    }
7062                    #[cfg(not(feature = "vulkan"))]
7063                    DeviceLocation::Vulkan { .. } => {
7064                        return Err(Error::Msg(format!(
7065                            "Op::{op_label} target Vulkan but fuel-storage wasn't built \
7066                             with --features vulkan",
7067                        ))
7068                        .bt());
7069                    }
7070                    other => {
7071                        return Err(Error::Msg(format!(
7072                            "PipelinedExecutor: Op::{op_label} target_location {:?} not yet \
7073                             wired (CPU + CUDA + Vulkan covered; Metal extends when \
7074                             its byte-storage substrate is ready).",
7075                            other
7076                        ))
7077                        .bt());
7078                    }
7079                };
7080                vec![Arc::new(RwLock::new(output))]
7081            };
7082            let kernel_layouts = vec![kernel_input_layout, item.output_layout.clone()];
7083            // A4b-1: defer the wait — return the handle to the realize loop.
7084            let handle = execute_compiled_with_wait_hint(
7085                compiled,
7086                &input_arcs,
7087                &mut output_arcs,
7088                &kernel_layouts,
7089                will_be_waited,
7090            )?;
7091            let arc = output_arcs.into_iter().next().expect("one output");
7092            // CapturedRun build-out (4b-ζ): Record (warm) mode remembers this
7093            // node's fixed output buffer so the capture run reuses the
7094            // identical device address. No-op in Reuse mode (the buffer came
7095            // FROM the map) and in None mode. Mirrors the Kernel arm's
7096            // Record-mode snapshot (above) exactly.
7097            if let Some(p) = persistent.as_deref_mut()
7098                && p.mode == PersistentMode::Record
7099            {
7100                p.map.insert(item.node_id, Arc::clone(&arc));
7101            }
7102            cache.insert(item.node_id, arc);
7103            layout_cache.insert(item.node_id, item.output_layout.clone());
7104            Ok(handle)
7105        }
7106        WorkItemKind::ReleaseMarker => {
7107            // Emit a zero-byte CPU storage at the Release node's
7108            // slot. Per Op::Release's contract the marker is never
7109            // read — this exists so any downstream cache lookup of
7110            // `release_id` resolves rather than failing. The actual
7111            // deallocation of `inputs[0]` is driven by the realize
7112            // loop's `destructive_input` cleanup (Phase B).
7113            let marker = fuel_memory::alloc_cpu_zeroed(item.dtype, 0)?;
7114            cache.insert(item.node_id, Arc::new(RwLock::new(marker)));
7115            layout_cache.insert(item.node_id, item.output_layout.clone());
7116            Ok(CompletionHandle::Ready)
7117        }
7118        WorkItemKind::ContiguizeOf { input } => {
7119            let input_arc = cache.get(input).cloned().ok_or_else(|| {
7120                Error::Msg(format!(
7121                    "PipelinedExecutor: reshape input {:?} of {:?} not realized",
7122                    input, item.node_id,
7123                ))
7124                .bt()
7125            })?;
7126            let input_layout = layout_cache.get(input).cloned().ok_or_else(|| {
7127                Error::Msg(format!(
7128                    "PipelinedExecutor: reshape input {:?} of {:?} has no cached layout",
7129                    input, item.node_id,
7130                ))
7131                .bt()
7132            })?;
7133            // CapturedRun build-out (4b-γ): in Reuse (capture/replay) mode,
7134            // reuse the fixed-address buffer recorded during the warm run —
7135            // device allocation is illegal inside a capture scope. Always
7136            // write-into when reusing (skip the zero-copy-vs-allocate
7137            // branch entirely): a given ContiguizeOf node's zero-copy-ness
7138            // is a static layout/stride property, identical across the warm
7139            // and capture passes (both replay the same compiled item list
7140            // with the same static layouts per capture_decode's own
7141            // design), so if this node ever needed the map entry it
7142            // allocated on warm too and the entry is guaranteed present.
7143            let reuse_arc = match &persistent {
7144                Some(p) if p.mode == PersistentMode::Reuse => p.map.get(&item.node_id).cloned(),
7145                _ => None,
7146            };
7147            let out_arc = if let Some(dest_arc) = reuse_arc {
7148                contiguize_into(&dest_arc, &input_arc, &input_layout)?;
7149                dest_arc
7150            } else if input_layout.is_contiguous() && input_layout.start_offset() == 0 {
7151                // Zero-copy when the input is already contiguous + zero
7152                // offset — never allocates, so Record mode has nothing to
7153                // record for this node (no fixed address to reuse).
7154                input_arc
7155            } else {
7156                // Allocate + copy via the contiguize kernel.
7157                let arc = auto_contiguize(&input_arc, &input_layout)?;
7158                if let Some(p) = persistent.as_deref_mut()
7159                    && p.mode == PersistentMode::Record
7160                {
7161                    p.map.insert(item.node_id, Arc::clone(&arc));
7162                }
7163                arc
7164            };
7165            cache.insert(item.node_id, out_arc);
7166            layout_cache.insert(item.node_id, item.output_layout.clone());
7167            // A4b-1: a materializing contiguize (CUDA) is same-stream; its
7168            // completion is carried by the realize-end full-stream sync in
7169            // `to_cpu_bytes` (unchanged) — `Ready` here is behavior-preserving.
7170            Ok(CompletionHandle::Ready)
7171        }
7172        WorkItemKind::Kernel => {
7173            let compiled = item.compiled.as_ref().ok_or_else(|| {
7174                Error::Msg(format!(
7175                    "PipelinedExecutor: Kernel work item {:?} has no compiled node",
7176                    item.node_id,
7177                ))
7178                .bt()
7179            })?;
7180            // Dynamic-M matmul (sparse MoE): resolve a DATA-DETERMINED row
7181            // count from the producer-bound `produced_syms` and run against
7182            // the patched (resolved-M) node. `None` on the common path.
7183            let patched_mm = resolve_deferred_matmul(compiled, produced_syms, item.node_id)?;
7184            let compiled = patched_mm.as_ref().unwrap_or(compiled);
7185            // Gather input Arcs from the cache, auto-contiguizing
7186            // any input whose layout is non-contiguous (typically
7187            // produced by an upstream metadata-only view op).
7188            // Today's kernels assume contiguous; this pass keeps
7189            // that invariant true at every kernel call site.
7190            //
7191            // We assemble a parallel `kernel_layouts` vec — the layout
7192            // of the bytes the kernel actually receives. After
7193            // auto-contiguize, that's `Layout::contiguous(shape)` for
7194            // the input's shape; for inputs already contiguous we use
7195            // the cached layout directly. Output layout comes last.
7196            let mut input_arcs: Vec<Arc<RwLock<Storage>>> = Vec::with_capacity(item.inputs.len());
7197            let mut kernel_layouts: Vec<fuel_ir::Layout> =
7198                Vec::with_capacity(item.inputs.len() + 1);
7199            // The kernel's `strided_input` cap lets non-contiguous
7200            // inputs (broadcast, transpose, etc.) flow through without
7201            // materialization — the kernel walks strides itself. Inputs
7202            // with non-zero `start_offset` still go through auto-
7203            // Contiguize today; offset honoring on the byte buffer is
7204            // a separate concern from stride support.
7205            let kernel_handles_strided = compiled.caps.strided_input;
7206            let t_gather = crate::compiled::op_profile::PhaseTimer::start("kernel.gather_inputs");
7207            for in_id in &item.inputs {
7208                let in_arc = cache.get(in_id).cloned().ok_or_else(|| {
7209                    Error::Msg(format!(
7210                        "PipelinedExecutor: input {:?} of {:?} not realized",
7211                        in_id, item.node_id,
7212                    ))
7213                    .bt()
7214                })?;
7215                let in_layout = layout_cache.get(in_id).cloned().ok_or_else(|| {
7216                    Error::Msg(format!(
7217                        "PipelinedExecutor: input {:?} of {:?} has no cached layout",
7218                        in_id, item.node_id,
7219                    ))
7220                    .bt()
7221                })?;
7222                // "Already contig" means more than `is_contiguous()`:
7223                // the LAYOUT's element count must also match the
7224                // STORAGE's byte count for shape-validating kernels
7225                // (concat_cpu, etc.) that read `storage.len_bytes()`.
7226                // A first-N slice view has `is_contiguous() == true`
7227                // (strides match canonical [1] for shape [N]) but its
7228                // storage is the parent's full bytes — too big. In
7229                // that case we auto-contiguize to materialize only
7230                // the view's portion as a fresh storage.
7231                //
7232                // Same constraint applies to strided_ok: kernels that
7233                // declare strided support can walk strided inputs, but
7234                // the byte count check at the kernel surface still
7235                // assumes storage.len_bytes() == layout.elem_count() *
7236                // dtype.size_bytes(). Until kernels universally trust
7237                // layout over storage, we conservatively materialize.
7238                let in_dtype = in_arc.read().map_err(|_| poisoned("input storage"))?.dtype;
7239                let in_len_bytes = in_arc
7240                    .read()
7241                    .map_err(|_| poisoned("input storage"))?
7242                    .inner
7243                    .len_bytes();
7244                let layout_bytes = in_layout.shape().elem_count() * in_dtype.size_in_bytes();
7245                let bytes_match_shape = in_len_bytes == layout_bytes;
7246                let already_contig =
7247                    in_layout.is_contiguous() && in_layout.start_offset() == 0 && bytes_match_shape;
7248                let strided_ok =
7249                    kernel_handles_strided && in_layout.start_offset() == 0 && bytes_match_shape;
7250                if already_contig || strided_ok {
7251                    input_arcs.push(in_arc);
7252                    kernel_layouts.push(in_layout);
7253                } else {
7254                    let contig_arc = auto_contiguize(&in_arc, &in_layout)?;
7255                    input_arcs.push(contig_arc);
7256                    kernel_layouts.push(fuel_ir::Layout::contiguous(in_layout.shape().clone()));
7257                }
7258            }
7259            drop(t_gather);
7260            kernel_layouts.push(item.output_layout.clone());
7261
7262            // Allocate output on the target backend. For GPU backends
7263            // we derive the device handle from the first input —
7264            // every kernel has ≥1 input (Op::Const is handled via
7265            // ConstAdopt, never via Kernel), and an input on the
7266            // target backend carries its own device. This avoids
7267            // threading a device handle through `realize`.
7268            //
7269            // Multi-output (Option C, item 3): when the WorkItem
7270            // carries an `output_bundle`, size the allocation to
7271            // span every slot's bytes (primary-dtype-element count
7272            // rounded up from the bundle's total byte span) and
7273            // attach the bundle metadata after allocation.
7274            let (alloc_elem_count, bundle_to_attach) = match &item.output_bundle {
7275                Some(bundle) => {
7276                    let dtype_bytes = item.dtype.size_in_bytes().max(1);
7277                    let total_bytes = bundle.iter().fold(0usize, |acc, s| {
7278                        let end = s.byte_offset.saturating_add(s.len_bytes());
7279                        acc.max(end)
7280                    });
7281                    let elems = total_bytes.div_ceil(dtype_bytes);
7282                    (elems, Some(Arc::clone(bundle)))
7283                }
7284                None => (item.elem_count, None),
7285            };
7286            // CapturedRun build-out: in Reuse (capture/replay) mode, reuse the
7287            // FIXED-ADDRESS buffer recorded during the warm run instead of
7288            // allocating — device allocation is illegal inside a capture scope,
7289            // and reusing the same address is what makes the captured graph's
7290            // baked kernel arguments valid on replay. In Record (warm) or None
7291            // mode, allocate as usual (below).
7292            let reuse_arc = match &persistent {
7293                Some(p) if p.mode == PersistentMode::Reuse => {
7294                    Some(p.map.get(&item.node_id).cloned().ok_or_else(|| {
7295                        Error::Msg(format!(
7296                            "PipelinedExecutor: capture (reuse) mode has no persistent \
7297                             output buffer for kernel node {:?}; the warm (record) run \
7298                             must realize every kernel node before capture",
7299                            item.node_id,
7300                        ))
7301                        .bt()
7302                    })?)
7303                }
7304                _ => None,
7305            };
7306            let t_alloc = crate::compiled::op_profile::PhaseTimer::start("kernel.alloc_output");
7307            let mut output_arcs = if let Some(arc) = reuse_arc {
7308                vec![arc]
7309            } else {
7310                let output = match item.target_backend {
7311                    BackendId::Cpu => fuel_memory::alloc_cpu_zeroed(item.dtype, alloc_elem_count)?,
7312                    #[cfg(feature = "cuda")]
7313                    BackendId::Cuda => {
7314                        let first_in = input_arcs.first().ok_or_else(|| {
7315                            Error::Msg(format!(
7316                                "PipelinedExecutor: kernel {:?} on Cuda has no inputs; \
7317                             cannot derive device for output allocation",
7318                                item.node_id,
7319                            ))
7320                            .bt()
7321                        })?;
7322                        let guard = first_in.read().map_err(|_| poisoned("input storage"))?;
7323                        let cuda_in = match &guard.inner {
7324                            fuel_memory::BackendStorage::Cuda(c) => c,
7325                            other => {
7326                                return Err(Error::Msg(format!(
7327                                    "PipelinedExecutor: kernel {:?} target_backend=Cuda but \
7328                                 input has BackendStorage::{:?}; mixed-backend kernels \
7329                                 require an explicit Op::Copy first",
7330                                    item.node_id,
7331                                    other.backend_id(),
7332                                ))
7333                                .bt());
7334                            }
7335                        };
7336                        let n_bytes = alloc_elem_count * item.dtype.size_in_bytes();
7337                        let cuda_bytes =
7338                            fuel_cuda_backend::CudaStorageBytes::alloc(cuda_in.device(), n_bytes)?;
7339                        fuel_memory::Storage::new(
7340                            fuel_memory::BackendStorage::Cuda(cuda_bytes),
7341                            item.dtype,
7342                        )
7343                    }
7344                    #[cfg(feature = "vulkan")]
7345                    BackendId::Vulkan => {
7346                        // Mirror the CUDA path: derive the backend handle
7347                        // from the first input's `VulkanStorageBytes::backend()`.
7348                        // Vulkan catch-up V.1.B (2026-05-21) — requires
7349                        // inputs constructed via `alloc_bytes_handle` /
7350                        // `upload_bytes_handle` so they carry the
7351                        // `Arc<VulkanBackend>` (mirroring CUDA's
7352                        // `Arc<CudaDevice>`).
7353                        let first_in = input_arcs.first().ok_or_else(|| {
7354                            Error::Msg(format!(
7355                                "PipelinedExecutor: kernel {:?} on Vulkan has no inputs; \
7356                             cannot derive backend handle for output allocation",
7357                                item.node_id,
7358                            ))
7359                            .bt()
7360                        })?;
7361                        let guard = first_in.read().map_err(|_| poisoned("input storage"))?;
7362                        let vk_in = match &guard.inner {
7363                            fuel_memory::BackendStorage::Vulkan(v) => v,
7364                            other => {
7365                                return Err(Error::Msg(format!(
7366                                    "PipelinedExecutor: kernel {:?} target_backend=Vulkan but \
7367                                 input has BackendStorage::{:?}; mixed-backend kernels \
7368                                 require an explicit Op::Copy first",
7369                                    item.node_id,
7370                                    other.backend_id(),
7371                                ))
7372                                .bt());
7373                            }
7374                        };
7375                        let backend = vk_in.backend().ok_or_else(|| {
7376                            Error::Msg(format!(
7377                                "PipelinedExecutor: Vulkan kernel {:?} input has no backend \
7378                             handle. Storages flowing through the pipelined executor's \
7379                             Vulkan path must be constructed via \
7380                             VulkanBackend::alloc_bytes_handle / upload_bytes_handle \
7381                             (not the legacy alloc_bytes / upload_bytes which leave \
7382                             VulkanStorageBytes::backend = None).",
7383                                item.node_id,
7384                            ))
7385                            .bt()
7386                        })?;
7387                        let n_bytes = alloc_elem_count * item.dtype.size_in_bytes();
7388                        let vk_bytes = backend.alloc_bytes_handle(n_bytes)?;
7389                        fuel_memory::Storage::new(
7390                            fuel_memory::BackendStorage::Vulkan(vk_bytes),
7391                            item.dtype,
7392                        )
7393                    }
7394                    other => {
7395                        return Err(Error::Msg(format!(
7396                            "PipelinedExecutor: target_backend {:?} output allocation \
7397                         not yet implemented (CPU + CUDA + Vulkan wired; Metal extends later)",
7398                            other
7399                        ))
7400                        .bt());
7401                    }
7402                };
7403                // Attach bundle metadata when this is a multi-output op.
7404                // The kernel sees the allocated bytes; the bundle lives
7405                // at the Storage wrapper level so downstream Op::View /
7406                // Op::ViewOwned can resolve their slot windows.
7407                let output = match bundle_to_attach {
7408                    Some(bundle) => output.with_bundle(bundle)?,
7409                    None => output,
7410                };
7411                vec![Arc::new(RwLock::new(output))]
7412            };
7413            drop(t_alloc);
7414
7415            // A4b-1: defer the wait — return the handle to the realize loop.
7416            let t_launch =
7417                crate::compiled::op_profile::PhaseTimer::start("kernel.execute_compiled");
7418            let handle = execute_compiled_with_wait_hint(
7419                compiled,
7420                &input_arcs,
7421                &mut output_arcs,
7422                &kernel_layouts,
7423                will_be_waited,
7424            )?;
7425            drop(t_launch);
7426            #[cfg(feature = "cuda")]
7427            if item.target_backend == BackendId::Cuda
7428                && let Some(reads) = index_reads
7429            {
7430                note_index_read(reads, &compiled.op_params, &input_arcs)?;
7431            }
7432
7433            let arc = output_arcs.into_iter().next().expect("one output");
7434
7435            // CapturedRun build-out: Record (warm) mode remembers this node's
7436            // fixed output buffer so the capture run reuses the identical
7437            // device address. No-op in Reuse mode (the buffer came FROM the
7438            // map) and in None mode.
7439            if let Some(p) = persistent
7440                && p.mode == PersistentMode::Record
7441            {
7442                p.map.insert(item.node_id, Arc::clone(&arc));
7443            }
7444
7445            // Data-determined dynamic-shapes seam (increment 2a): a
7446            // producer that computes a runtime count publishes it into the
7447            // per-pass `SymEnv` so downstream ops can consume it as a
7448            // dynamic extent. `Op::NonZeroIndices` writes its count into
7449            // bundle slot 1; read it back and bind `count_sym`. This is the
7450            // FIRST op to bind a *data-determined* symbol mid-realize (all
7451            // prior binds are host-known before realize). Single-threaded:
7452            // the executor runs items topologically, so this bind precedes
7453            // any consumer's execute-time resolution.
7454            if let OpParams::NonZeroIndices {
7455                capacity,
7456                count_sym,
7457            } = &compiled.op_params
7458            {
7459                bind_data_determined_count(&arc, *capacity, *count_sym, produced_syms)?;
7460            }
7461
7462            cache.insert(item.node_id, arc);
7463            layout_cache.insert(item.node_id, item.output_layout.clone());
7464            Ok(handle)
7465        }
7466        WorkItemKind::InplaceKernel { target_idx } => {
7467            let compiled = item.compiled.as_ref().ok_or_else(|| {
7468                Error::Msg(format!(
7469                    "PipelinedExecutor: InplaceKernel work item {:?} has no compiled node",
7470                    item.node_id,
7471                ))
7472                .bt()
7473            })?;
7474            let target_id = *item.inputs.get(*target_idx).ok_or_else(|| {
7475                Error::Msg(format!(
7476                    "PipelinedExecutor: InplaceKernel work item {:?} target_idx={} \
7477                     out of bounds (inputs.len()={})",
7478                    item.node_id,
7479                    target_idx,
7480                    item.inputs.len(),
7481                ))
7482                .bt()
7483            })?;
7484            let target_arc = cache.get(&target_id).cloned().ok_or_else(|| {
7485                Error::Msg(format!(
7486                    "PipelinedExecutor: InplaceKernel target {:?} of {:?} not realized",
7487                    target_id, item.node_id,
7488                ))
7489                .bt()
7490            })?;
7491            let target_layout = layout_cache.get(&target_id).cloned().ok_or_else(|| {
7492                Error::Msg(format!(
7493                    "PipelinedExecutor: InplaceKernel target {:?} of {:?} has no cached layout",
7494                    target_id, item.node_id,
7495                ))
7496                .bt()
7497            })?;
7498            // v1 contract: target must be contiguous + zero offset.
7499            // Strided in-place targets would force the kernel to walk
7500            // strides for writes too; defer until a concrete consumer
7501            // needs it (mirrors `Op::WriteSlice`'s v1 dest contract).
7502            if !target_layout.is_contiguous() || target_layout.start_offset() != 0 {
7503                return Err(Error::Msg(format!(
7504                    "InplaceKernel (Phase 3 v1): target {:?} must be contiguous + \
7505                     zero-offset; got Layout {:?}",
7506                    target_id, target_layout,
7507                ))
7508                .bt());
7509            }
7510            // Kernel sees inputs=[non-target IR inputs in order] and
7511            // outputs=[target_arc]. For unary in-place (1 IR input at
7512            // target_idx=0) the input vec is empty, matching the
7513            // original Phase 3e contract. For binary in-place
7514            // (target_idx=0, 2 IR inputs) the wrapper sees the
7515            // non-destructive RHS as `inputs[0]`. The wrapper acquires
7516            // outputs[0]'s write lock and mutates through its
7517            // bytes_mut(). Layout vector contains the kernel's
7518            // inputs+outputs layouts in that order.
7519            let mut input_arcs: Vec<Arc<RwLock<Storage>>> = Vec::new();
7520            let mut kernel_layouts: Vec<Layout> = Vec::new();
7521            for (i, &input_id) in item.inputs.iter().enumerate() {
7522                if i == *target_idx {
7523                    continue;
7524                }
7525                let arc = cache.get(&input_id).cloned().ok_or_else(|| {
7526                    Error::Msg(format!(
7527                        "PipelinedExecutor: InplaceKernel non-target input {:?} of {:?} \
7528                         not realized",
7529                        input_id, item.node_id,
7530                    ))
7531                    .bt()
7532                })?;
7533                let lay = layout_cache.get(&input_id).cloned().ok_or_else(|| {
7534                    Error::Msg(format!(
7535                        "PipelinedExecutor: InplaceKernel non-target input {:?} of {:?} \
7536                         has no cached layout",
7537                        input_id, item.node_id,
7538                    ))
7539                    .bt()
7540                })?;
7541                input_arcs.push(arc);
7542                kernel_layouts.push(lay);
7543            }
7544            let mut output_arcs = vec![target_arc.clone()];
7545            kernel_layouts.push(target_layout.clone());
7546            // A4b-1: defer the wait — return the handle to the realize loop.
7547            let handle = execute_compiled_with_wait_hint(
7548                compiled,
7549                &input_arcs,
7550                &mut output_arcs,
7551                &kernel_layouts,
7552                will_be_waited,
7553            )?;
7554            // Adopt the target Arc at this node's slot. The realize
7555            // loop's destructive_input cleanup evicts the target's own
7556            // NodeId from the cache afterward.
7557            cache.insert(item.node_id, target_arc);
7558            layout_cache.insert(item.node_id, item.output_layout.clone());
7559            Ok(handle)
7560        }
7561    }
7562}
7563
7564fn poisoned(what: &'static str) -> Error {
7565    Error::Msg(format!("PipelinedExecutor: {} poisoned", what)).bt()
7566}
7567
7568/// Step E A4b-1: record a node's [`CompletionHandle`] in the executor's
7569/// per-node handle map.
7570///
7571/// `Ready` handles (CPU / Vulkan / view-and-alloc arms) carry no async work, so
7572/// we DON'T store them — keeping the map to genuinely-pending entries makes the
7573/// realize-end empty-after-drain assert (open question #6) meaningful and keeps
7574/// the drain O(pending) rather than O(nodes). A re-used NodeId (in-place adopt
7575/// re-keys an existing slot) waits the prior handle first so nothing leaks.
7576#[inline]
7577/// ROADMAP row 158: after a kernel node was submitted, add its compile-time estimate to the device it
7578/// landed on. The device comes from the OUTPUT storage (the same source `produce_pending` reads), so a
7579/// node stamped for one backend but realized elsewhere is priced where it actually runs. Nothing is added
7580/// for a non-kernel item, a CPU output, a `0` estimate, or a storage that cannot name its device.
7581fn feed_backlog(
7582    ledger: &mut crate::dispatch::BacklogLedger,
7583    cache: &StorageCache,
7584    item: &WorkItem,
7585) {
7586    // OFF by default (`FUEL_BACKLOG_FEED`, `set_backlog_feed_enabled`): see `dispatch::BACKLOG_FEED_ENV`.
7587    if !crate::dispatch::backlog_feed_enabled() {
7588        return;
7589    }
7590    // Take back what the GPU has already finished first, so the picker reads QUEUED work, not everything
7591    // this realize has submitted so far.
7592    ledger.retire_completed();
7593    let Some(compiled) = item.compiled.as_ref() else {
7594        return;
7595    };
7596    if !matches!(item.kind, WorkItemKind::Kernel) || compiled.est_ns == 0 {
7597        return;
7598    }
7599    let Some(arc) = cache.get(&item.node_id) else {
7600        return;
7601    };
7602    let Ok(guard) = arc.read() else {
7603        return;
7604    };
7605    if let Some(loc) = guard.inner.location() {
7606        match completion_probe(&guard.inner) {
7607            Some(done) if !crate::dispatch::backlog_retire_disabled() => {
7608                ledger.add_until(loc, compiled.est_ns, done)
7609            }
7610            _ => ledger.add(loc, compiled.est_ns),
7611        }
7612    }
7613}
7614
7615/// A non-blocking "has the work just submitted into this storage finished?" probe, from the backend that
7616/// holds it (ROADMAP row 158): Vulkan reads its dispatch clock against the count stamped now, after the
7617/// kernel was recorded; CUDA records an event on the device stream now and queries it. `None` for a backend
7618/// with no probe (the estimate then stays until the end of the realize).
7619fn completion_probe(
7620    inner: &fuel_memory::BackendStorage,
7621) -> Option<Box<dyn Fn() -> bool + Send + Sync>> {
7622    match inner {
7623        #[cfg(feature = "vulkan")]
7624        fuel_memory::BackendStorage::Vulkan(v) => {
7625            let clock = v.backend()?.dispatch_clock();
7626            let stamp = clock.recorded();
7627            Some(Box::new(move || clock.retired() >= stamp))
7628        }
7629        #[cfg(feature = "cuda")]
7630        fuel_memory::BackendStorage::Cuda(c) => {
7631            let ev = c.record_completion_event().ok()?;
7632            // A failed query counts as finished: a fault surfaces at the realize's own sync, and the
7633            // estimate must not stay on the backlog because the probe could not answer.
7634            Some(Box::new(move || ev.is_complete().unwrap_or(true)))
7635        }
7636        #[allow(unreachable_patterns)]
7637        _ => None,
7638    }
7639}
7640
7641fn store_handle(
7642    handles: &mut HashMap<NodeId, CompletionHandle>,
7643    node_id: NodeId,
7644    handle: CompletionHandle,
7645) {
7646    if matches!(handle, CompletionHandle::Ready) {
7647        // A prior pending handle at this slot must still be waited (don't drop a
7648        // Pending silently). In practice NodeIds are unique per realize, so this
7649        // is just defensive.
7650        if let Some(prev) = handles.remove(&node_id) {
7651            let _ = prev.wait();
7652        }
7653        return;
7654    }
7655    if let Some(prev) = handles.insert(node_id, handle) {
7656        let _ = prev.wait();
7657    }
7658}
7659
7660/// Step E A4b-3: the FINER cross-device producer wait.
7661///
7662/// Before dispatching a cross-device `Op::Copy` / `Op::Move` WorkItem, the
7663/// executor calls this on the copy's single source input. It removes the
7664/// source producer's [`CompletionHandle`] from the map and waits it — so the
7665/// specific producer P is complete before the D2H reads P's device buffer,
7666/// WITHOUT draining the whole source device (the conservative pre-A4b-3
7667/// behavior, where `to_cpu_bytes`'s `device.synchronize()` blocked on ALL
7668/// in-flight work on that device — including the OTHER sub-DAG's independent
7669/// work A4b-4 wants to overlap).
7670///
7671/// - **CUDA producer** → waits P's recorded `Event` (`cuEventSynchronize`):
7672///   fires after P + its already-ordered stream predecessors, nothing else.
7673/// - **Absent / `Ready` producer** (CPU producer, or a Vulkan producer — which
7674///   under A4b-2 is `Ready` mid-walk because nothing is submitted until
7675///   realize-end) → no-op. A Vulkan SOURCE's own ordering is handled inside
7676///   `download_bytes` (it `force_flush`es the open batch then reads), so there
7677///   is no mid-walk Vulkan handle to wait here; the cross-device Vulkan→CPU hop
7678///   stays correct without one.
7679///
7680/// Removing the handle here (rather than waiting it again at realize-end) keeps
7681/// `drain_handles`' post-drain empty-map assert meaningful and avoids a
7682/// double-wait. Waiting it twice would be harmless (`cuEventSynchronize` on an
7683/// already-signalled event is a fast no-op), but the consume-once contract is
7684/// cleaner. The producing node's *storage* stays in the cache for downstream
7685/// readers; only its completion handle is consumed.
7686fn wait_producer_handle(
7687    handles: &mut HashMap<NodeId, CompletionHandle>,
7688    producer: NodeId,
7689) -> Result<()> {
7690    if let Some(handle) = handles.remove(&producer) {
7691        handle.wait()?;
7692    }
7693    Ok(())
7694}
7695
7696/// Step E A4b-1: realize-end drain — wait every outstanding async handle, then
7697/// clear the map.
7698///
7699/// **Event-recording / wait strategy (A4b-1 §1.2).** CUDA has one stream per
7700/// device, and an `Event` recorded after a node's launch signals when that
7701/// node *and all prior stream work* have completed. So once the
7702/// latest-recorded event on a device has signalled, every earlier event on that
7703/// device is already signalled too: waiting them is a non-blocking
7704/// `cuEventQuery` fast-path, not N host stalls. We therefore wait every stored
7705/// handle (correct + simple).
7706///
7707/// **Open question #4 — "event only where waited" — RESOLVED.** Recording an
7708/// `Event` for every node was measured negligible on a 32-op synthetic, but
7709/// real decode graphs run 150-200+ ops; `pipelined`'s `WaitSet` pre-scan (see
7710/// `compiler_work_and_wait_set_for` / `build_wait_set`) now restricts event
7711/// production to the nodes some later cross-device `Copy`/`Move` will
7712/// individually wait — same-device-only ("elided") nodes get
7713/// `CompletionHandle::Ready` with no `cuEventCreate`/`cuEventRecord` at all
7714/// (`execute_compiled_with_wait_hint`). This drain therefore now retires only
7715/// the (typically few) wait-set handles that were never consumed mid-walk by
7716/// `wait_producer_handle`; it is no longer sufficient on its own to guarantee
7717/// every enqueued CUDA kernel has completed — `sync_active_cuda_devices` below
7718/// covers the elided remainder. We keep a per-node handle (rather than a
7719/// single per-device event) for the wait-set members because A4b-3's finer
7720/// cross-device wait needs to wait a *specific producer's* completion — the
7721/// per-node handle is that seam.
7722fn drain_handles(handles: &mut HashMap<NodeId, CompletionHandle>) -> Result<()> {
7723    for (_node, handle) in handles.drain() {
7724        handle.wait()?;
7725    }
7726    // Open question #6: once handles are stored instead of `wait`ed inline, the
7727    // `#[must_use]` on `CompletionHandle` can't catch a leaked (never-waited)
7728    // handle at the call site. The drain consumes the whole map, so it is empty
7729    // here by construction; assert it to catch a future leak (e.g. a new
7730    // dispatch path that forgets to thread its handle through `store_handle`).
7731    debug_assert!(
7732        handles.is_empty(),
7733        "A4b-1: handle map must be empty after drain"
7734    );
7735    Ok(())
7736}
7737
7738/// Step E A4b open question #4 step 3 — the realize-end complement to the
7739/// "event only where waited" elision. Because most CUDA nodes in a long
7740/// single-device chain no longer record an `Event` (see `drain_handles`'s
7741/// doc), this does ONE blanket `cuStreamSynchronize` per CUDA device that
7742/// still holds LIVE storage in `cache` — the realize target(s) plus any
7743/// surviving intermediates — instead of relying on per-node handles to cover
7744/// them.
7745///
7746/// **Why this is safe + sufficient.** CUDA has one stream per device, and
7747/// this executor dispatches strictly sequentially (one work item at a time,
7748/// in topological order) — so by the time a live node's own kernel was
7749/// launched, every same-device ancestor it depends on was ALREADY enqueued
7750/// earlier on the SAME stream. Stream ordering (not a host wait) guarantees
7751/// those ancestors run to completion no later than the live node's own
7752/// kernel. Syncing the live node's device therefore flushes its entire
7753/// same-device dependency chain, elided or not. Cross-device ancestors are
7754/// unaffected by elision — they always went through an `Op::Copy`/`Move`,
7755/// whose producer is in the `WaitSet` and was already waited explicitly at
7756/// the cross-device boundary (`wait_producer_handle`), mid-walk.
7757///
7758/// **Why evicted (non-live) intermediates don't need this.** A node whose
7759/// storage was evicted before realize-end (the `destructive_input` cleanup)
7760/// is never read by anything this realize returns; A3's stream-ordered
7761/// alloc/free already makes its eventual completion safe without a host
7762/// wait (the driver serializes the free after the freeing stream position,
7763/// same as any other stream-ordered op) — nothing to synchronize for.
7764///
7765/// No-op when `cache` holds no CUDA storage (CPU/Vulkan-only realize).
7766#[cfg(feature = "cuda")]
7767fn sync_active_cuda_devices(cache: &StorageCache) -> Result<()> {
7768    let mut devices: HashMap<fuel_ir::DeviceLocation, fuel_cuda_backend::CudaDevice> =
7769        HashMap::new();
7770    for arc in cache.values() {
7771        let guard = arc
7772            .read()
7773            .map_err(|_| poisoned("cache storage (cuda realize-end sync scan)"))?;
7774        if let fuel_memory::BackendStorage::Cuda(c) = &guard.inner {
7775            devices
7776                .entry(c.device().location())
7777                .or_insert_with(|| c.device().clone());
7778        }
7779    }
7780    for dev in devices.values() {
7781        dev.synchronize()?;
7782    }
7783    Ok(())
7784}
7785
7786/// Non-CUDA builds never produce CUDA storage, so there is nothing to sync —
7787/// keeps the call site unconditional across both feature configurations.
7788#[cfg(not(feature = "cuda"))]
7789fn sync_active_cuda_devices(_cache: &StorageCache) -> Result<()> {
7790    Ok(())
7791}
7792
7793/// Step E A4b-2: a Vulkan [`Completion`](crate::compiled::Completion) over an
7794/// in-flight (submitted, not-yet-waited) batch. `wait` blocks on the batch's
7795/// fence (`vkWaitForFences`) — which fires when the whole submitted command
7796/// buffer has retired on the single compute queue — then releases the batch
7797/// (frees the CB / descriptor sets / transient buffers / retired pool, all now
7798/// idle on the GPU).
7799///
7800/// The fence is per-BATCH, not per-node: one `submit_pending` flushes every op
7801/// recorded since the last submit, so this single handle covers a contiguous run
7802/// of Vulkan nodes (the A2 batching win, preserved — fewer fences, larger
7803/// submissions). `backend` keeps the [`VulkanBackend`] alive so the
7804/// post-fence pool retire + the `DeviceInner` the batch's resources reference
7805/// outlive the wait.
7806///
7807/// `Send` (required by `Completion`): every owned field is `Send` — `Fence` /
7808/// `CommandBuffer` / `DescriptorSet` / `Buffer` / `Allocation` / `CommandPool`
7809/// are all `Send` in vulkane (Arc-of-`DeviceInner` + explicit `unsafe impl`s),
7810/// and `Arc<VulkanBackend>` is `Send + Sync`.
7811/// Step E B1: `batch` is an `Option` ONLY so [`Drop`] can coexist with the
7812/// by-value `into_wait` consume. A type with a `Drop` impl cannot be
7813/// destructured by move (`let VulkanCompletion { backend, batch } = self`,
7814/// E0509), so `into_wait` `take()`s the batch out of the `Option` instead of
7815/// moving it out of the struct, then lets the normal `Drop` run. In every
7816/// reachable state the batch is `Some` until exactly one `into_wait` consumes it.
7817#[cfg(feature = "vulkan")]
7818struct VulkanCompletion {
7819    backend: Arc<fuel_vulkan_backend::VulkanBackend>,
7820    batch: Option<fuel_vulkan_backend::SubmittedBatch>,
7821    /// The device this submitted batch counts against in the in-flight counter
7822    /// (Step E B1). `Drop` decrements this slot.
7823    loc: fuel_ir::DeviceLocation,
7824}
7825
7826/// Step E A4b-4: the element type of the executor's in-flight-Vulkan-batch list.
7827/// A [`VulkanCompletion`] on a Vulkan build; a zero-sized placeholder otherwise
7828/// so the realize loops carry one `Vec<InflightVulkan>` local without `cfg` on
7829/// every use site (the helpers `eager_submit_all_vulkan` / `drain_inflight_vulkan`
7830/// are the only code that ever pushes/drains it, and they are `cfg`-gated).
7831#[cfg(feature = "vulkan")]
7832type InflightVulkan = VulkanCompletion;
7833#[cfg(not(feature = "vulkan"))]
7834type InflightVulkan = ();
7835
7836/// Step E A4b-4: is the cross-device copy's SOURCE buffer Vulkan-resident?
7837///
7838/// Used at the cross-device `Op::Copy`/`Op::Move` boundary to decide whether the
7839/// executor must wait the in-flight Vulkan batches before the copy. A Vulkan→CPU
7840/// D2H reads the source on the host, and the Vulkan `download` path only
7841/// `force_flush`es the OPEN batch (never the executor's eagerly-submitted
7842/// in-flight ones), so for a VULKAN source we must `drain_inflight_vulkan` first
7843/// to read completed data. For a CUDA / CPU source we must NOT wait Vulkan — the
7844/// copy doesn't read any Vulkan buffer, and waiting Vulkan there would needlessly
7845/// serialize the independent Vulkan sub-DAG (killing the overlap A4b-4 exists to
7846/// win). Returns `false` when the producer's storage isn't in the cache (treated
7847/// as not-Vulkan → no Vulkan wait; the CUDA/CPU producer handle still covers it).
7848#[cfg(feature = "vulkan")]
7849fn copy_source_is_vulkan(cache: &StorageCache, producer: NodeId) -> Result<bool> {
7850    if let Some(arc) = cache.get(&producer) {
7851        let guard = arc
7852            .read()
7853            .map_err(|_| poisoned("storage lock probing copy-source backend"))?;
7854        return Ok(matches!(
7855            guard.inner,
7856            fuel_memory::BackendStorage::Vulkan(_)
7857        ));
7858    }
7859    Ok(false)
7860}
7861
7862#[cfg(not(feature = "vulkan"))]
7863#[inline]
7864fn copy_source_is_vulkan(_cache: &StorageCache, _producer: NodeId) -> Result<bool> {
7865    Ok(false)
7866}
7867
7868#[cfg(feature = "vulkan")]
7869impl crate::compiled::Completion for VulkanCompletion {
7870    fn wait(self: Box<Self>) -> Result<()> {
7871        // Move the whole `VulkanCompletion` out of the `Box` (allowed even with a
7872        // `Drop` impl — it's a full move, not a destructure) and consume by value.
7873        (*self).into_wait()
7874    }
7875}
7876
7877#[cfg(feature = "vulkan")]
7878impl VulkanCompletion {
7879    /// Build the handle for an eagerly-submitted Vulkan batch and register it as
7880    /// one in-flight batch on `loc` (Step E B1). The matching decrement is in
7881    /// [`Drop`]. `loc` is the backend's `DeviceLocation::Vulkan { gpu_id }`.
7882    fn new(
7883        backend: Arc<fuel_vulkan_backend::VulkanBackend>,
7884        batch: fuel_vulkan_backend::SubmittedBatch,
7885        loc: fuel_ir::DeviceLocation,
7886    ) -> Self {
7887        crate::dispatch::inflight_inc(loc);
7888        Self {
7889            backend,
7890            batch: Some(batch),
7891            loc,
7892        }
7893    }
7894
7895    /// Block on this batch's fence, retire pools, then free the batch. Consumes
7896    /// `self` by value (the by-value sibling of the boxed `Completion::wait`),
7897    /// used by the executor's `inflight_vulkan` drain (A4b-4) where we hold the
7898    /// `VulkanCompletion` unboxed in a `Vec`.
7899    ///
7900    /// Step E B1: `take()`s the batch out of the `Option` (NOT a destructure
7901    /// move — that's illegal with a `Drop` impl) and waits it; the in-flight
7902    /// decrement then rides `self`'s `Drop` as this returns. So a wait-consume
7903    /// and a bare drop (e.g. an error unwinding before the wait) BOTH decrement
7904    /// exactly once, and `into_wait` never double-counts.
7905    fn into_wait(mut self) -> Result<()> {
7906        // `wait_submitted` consumes the batch by value: waits the fence, retires
7907        // pools, then drops the batch (UAF-safe — nothing the in-flight CB
7908        // references frees before the fence signals). After a `new` the batch is
7909        // always `Some`; `take` leaves `None` so `Drop` doesn't touch it again.
7910        if let Some(batch) = self.batch.take() {
7911            self.backend.wait_submitted(batch)?;
7912        }
7913        Ok(())
7914        // `self` drops here → `inflight_dec(self.loc)`.
7915    }
7916
7917    /// Step E A2.1 (deferred-deletion): retain an evicted DATA buffer until THIS
7918    /// in-flight batch's fence signals, then free it post-fence (on the batch's
7919    /// `Drop` — guaranteed post-fence by follow-on #2). Delegates to
7920    /// [`fuel_vulkan_backend::SubmittedBatch::retain_buffer`].
7921    ///
7922    /// The executor calls this for every in-flight batch when it evicts a Vulkan
7923    /// buffer those batches' CBs may read, INSTEAD of host-blocking on a drain.
7924    /// `batch` is `Some` in every reachable mid-walk state (it is `take`n only by
7925    /// `into_wait`/`wait`, which consume the whole `VulkanCompletion`), so the
7926    /// retain always lands on a live in-flight batch.
7927    fn retain_data(&mut self, buf: std::sync::Arc<fuel_vulkan_backend::VulkanBuffer>) {
7928        if let Some(batch) = self.batch.as_mut() {
7929            batch.retain_buffer(buf);
7930        }
7931    }
7932}
7933
7934#[cfg(feature = "vulkan")]
7935impl Drop for VulkanCompletion {
7936    fn drop(&mut self) {
7937        // The single in-flight decrement for a Vulkan batch — fires whether the
7938        // batch was waited (`into_wait` / `wait`) or merely dropped (error
7939        // unwind), so the per-device count returns to baseline. Relaxed +
7940        // saturating (a scheduling hint, never a correctness gate).
7941        crate::dispatch::inflight_dec(self.loc);
7942    }
7943}
7944
7945/// Step E A4b-4 — eager Vulkan submission during the walk (the OVERLAP enabler).
7946///
7947/// Submits each DISTINCT Vulkan backend's currently-open batch WITHOUT waiting,
7948/// pushing the resulting in-flight [`VulkanCompletion`]s onto `inflight` so the
7949/// executor waits them later (at the in-flight-lifetime guard / realize-end). An
7950/// empty open batch yields `None` and is skipped (idempotent).
7951///
7952/// This is what makes a Vulkan sub-DAG actually START on the iGPU while the
7953/// executor records/dispatches the next (CUDA) chunk — without it the Vulkan
7954/// batch sits merely *recorded* until realize-end and never overlaps the CUDA
7955/// stream (design §5). Called ONLY on a genuinely multi-backend realize (gated by
7956/// the executor's `multi_backend` flag); on a single-device graph it is never
7957/// reached, so pure-Vulkan stays byte-identical to A4b-2 (one realize-end submit).
7958///
7959/// **Whole-chunk granularity (UAF/race-safety, design §4 + the Vulkan
7960/// single-queue OOO-completion semantics).** We submit only at chunk boundaries
7961/// and before a cross-device wait — never mid-chunk — so the batch handed to the
7962/// GPU is a COMPLETE contiguous run of Vulkan nodes with all its intra-CB
7963/// dependency barriers (`recorder.rs` `vkCmdPipelineBarrier`) already in place.
7964/// Vulkan only guarantees that batches on one queue BEGIN in submission order;
7965/// they may overlap / complete out of order, so a split mid-chunk would lose the
7966/// write-before-read ordering for ops that read an earlier op's buffer in the
7967/// SAME chunk. By submitting whole chunks and re-syncing (`drain_inflight_vulkan`)
7968/// before any later Vulkan op records, before any cross-device copy, and before
7969/// any Vulkan-referenced eviction, no in-flight batch is ever read or freed while
7970/// still running.
7971#[cfg(feature = "vulkan")]
7972fn eager_submit_all_vulkan(
7973    cache: &StorageCache,
7974    inflight: &mut Vec<VulkanCompletion>,
7975) -> Result<()> {
7976    // Collect distinct Vulkan backends referenced by the cache (dedup by gpu_id).
7977    let mut seen: Vec<usize> = Vec::new();
7978    let mut backends: Vec<Arc<fuel_vulkan_backend::VulkanBackend>> = Vec::new();
7979    for arc in cache.values() {
7980        let guard = arc
7981            .read()
7982            .map_err(|_| poisoned("storage lock during eager vulkan submit"))?;
7983        if let fuel_memory::BackendStorage::Vulkan(v) = &guard.inner
7984            && let Some(backend) = v.backend()
7985            && !seen.contains(&backend.gpu_id)
7986        {
7987            seen.push(backend.gpu_id);
7988            backends.push(backend.clone());
7989        }
7990    }
7991    for backend in backends {
7992        // Step E B1: the per-device location for the in-flight counter. A batch
7993        // submitted here is one in-flight unit on this iGPU until its handle's
7994        // `Drop` (after `drain_inflight_vulkan` / realize-end).
7995        let loc = DeviceLocation::Vulkan {
7996            gpu_id: backend.gpu_id,
7997        };
7998        if let Some(batch) = backend.submit_pending()? {
7999            inflight.push(VulkanCompletion::new(backend, batch, loc));
8000        }
8001    }
8002    Ok(())
8003}
8004
8005#[cfg(not(feature = "vulkan"))]
8006#[inline]
8007fn eager_submit_all_vulkan(
8008    _cache: &StorageCache,
8009    _inflight: &mut Vec<InflightVulkan>,
8010) -> Result<()> {
8011    Ok(())
8012}
8013
8014/// Step E A4b-4 — wait every in-flight (eagerly-submitted) Vulkan batch, then
8015/// clear the list. The re-sync half of [`eager_submit_all_vulkan`].
8016///
8017/// Each `into_wait` blocks on the batch fence (`vkWaitForFences`), retires the
8018/// backend's descriptor pools, and frees the batch (CB / descriptor sets /
8019/// transient buffers / retired command pool — all now idle on the GPU). After
8020/// this returns, NO submitted Vulkan command buffer is still executing, so it is
8021/// safe to (a) record a new Vulkan op that may read a just-produced buffer,
8022/// (b) D2H-copy a Vulkan buffer on the host, or (c) free a buffer a batch read.
8023///
8024/// Because the eager submit happened at the PRIOR chunk boundary and an
8025/// intervening (e.g. CUDA) chunk has since been recorded/dispatched, the fence is
8026/// typically already signalled here — the wait is a fast no-op, and the iGPU work
8027/// genuinely overlapped the other device's stream. Waiting the Vulkan fence does
8028/// NOT touch the CUDA stream, so the other device keeps running (concurrency
8029/// preserved — design §5 "the per-device guards don't cross-stall").
8030#[cfg(feature = "vulkan")]
8031fn drain_inflight_vulkan(inflight: &mut Vec<VulkanCompletion>) -> Result<()> {
8032    for vc in inflight.drain(..) {
8033        vc.into_wait()?;
8034    }
8035    Ok(())
8036}
8037
8038#[cfg(not(feature = "vulkan"))]
8039#[inline]
8040fn drain_inflight_vulkan(_inflight: &mut Vec<InflightVulkan>) -> Result<()> {
8041    Ok(())
8042}
8043
8044/// Step E A4b-2: the realize-end Vulkan drain, SPLIT into submit-then-wait.
8045///
8046/// Replaces A2's `force_flush_all_vulkan` (which submitted + waited atomically
8047/// inside `force_flush`). For each DISTINCT Vulkan backend referenced by the
8048/// cache, `submit_pending` submits the still-open batch WITHOUT waiting (→ a
8049/// `SubmittedBatch`), wraps it in the executor's [`VulkanCompletion`] handle, and
8050/// `wait`s it. Net for a pure-Vulkan realize: the batch still accumulates across
8051/// the whole walk (the per-op path keeps returning `Ready`; no eager submit —
8052/// that is A4b-4) and is submitted ONCE here, then waited — **byte-identical to
8053/// A2**, same single submission at realize-end, just split through the handle.
8054///
8055/// Idempotent across repeated cache arcs: the first `submit_pending` on a backend
8056/// returns `Some(batch)`; subsequent calls on the same backend see an empty batch
8057/// and return `None` (skipped) — exactly the `force_flush` idempotence A2 relied
8058/// on. No-op for a non-Vulkan build.
8059#[cfg(feature = "vulkan")]
8060fn drain_vulkan_pending(cache: &StorageCache) -> Result<()> {
8061    use crate::compiled::CompletionHandle;
8062    for arc in cache.values() {
8063        let backend = {
8064            let guard = arc
8065                .read()
8066                .map_err(|_| poisoned("storage lock during vulkan submit_pending"))?;
8067            match &guard.inner {
8068                fuel_memory::BackendStorage::Vulkan(v) => v.backend().cloned(),
8069                _ => None,
8070            }
8071        };
8072        let Some(backend) = backend else { continue };
8073        // Submit the open batch (if any) without waiting, then wait via the
8074        // completion handle. Empty batch → None → nothing to wait.
8075        // Step E B1: `new` increments the in-flight counter for this device;
8076        // `handle.wait()` waits + drops the `VulkanCompletion`, decrementing it
8077        // — a balanced submit/retire even on this transient realize-end path.
8078        let loc = DeviceLocation::Vulkan {
8079            gpu_id: backend.gpu_id,
8080        };
8081        if let Some(batch) = backend.submit_pending()? {
8082            let handle: CompletionHandle =
8083                CompletionHandle::Pending(Box::new(VulkanCompletion::new(backend, batch, loc)));
8084            handle.wait()?;
8085        }
8086    }
8087    Ok(())
8088}
8089
8090#[cfg(not(feature = "vulkan"))]
8091fn drain_vulkan_pending(_cache: &StorageCache) -> Result<()> {
8092    Ok(())
8093}
8094
8095/// Step E A2: force the Vulkan backend behind `arc` (if any) to submit + WAIT
8096/// its open batch — the blocking drain before freeing a buffer the batch may
8097/// reference (a destructive eviction) so a recorded-but-unsubmitted command never
8098/// reads freed memory. No-op for non-Vulkan storage, an empty batch, or a
8099/// non-Vulkan build.
8100///
8101/// **Retained for the SINGLE-DEVICE path (byte-identical to pre-A2.1).** A2.1's
8102/// deferred-deletion ([`defer_evicted_vulkan_buffer`]) replaces this only on a
8103/// MULTI-backend realize, where eager-submit + in-flight tracking + the
8104/// realize-end `drain_inflight_vulkan` are all live. On a single-device Vulkan
8105/// realize the A4b machinery is gated off (`multi_backend == false`): the
8106/// cross-batch RAW guard (`pipelined.rs:832`) does not run, so a later Vulkan op
8107/// reading a buffer an eager-submitted batch wrote could race (separate
8108/// submissions only BEGIN in order, may overlap). The blocking `force_flush`
8109/// (submit + wait) is the coherent eviction drain there — exactly the original
8110/// behavior — so single-device stays byte-identical and UAF-safe.
8111#[cfg(feature = "vulkan")]
8112fn force_flush_vulkan(arc: &Arc<RwLock<Storage>>) -> Result<()> {
8113    let guard = arc
8114        .read()
8115        .map_err(|_| poisoned("storage lock during vulkan force_flush"))?;
8116    if let fuel_memory::BackendStorage::Vulkan(v) = &guard.inner
8117        && let Some(backend) = v.backend()
8118    {
8119        backend.force_flush()?;
8120    }
8121    Ok(())
8122}
8123
8124#[cfg(not(feature = "vulkan"))]
8125fn force_flush_vulkan(_arc: &Arc<RwLock<Storage>>) -> Result<()> {
8126    Ok(())
8127}
8128
8129/// Step E A2.1 — DEFERRED-DELETION of a Vulkan data buffer evicted while Vulkan
8130/// work is in flight (the throughput refinement that REPLACES the eviction-time
8131/// drain on a MULTI-backend realize). Called at the per-NodeId destructive
8132/// eviction (`Op::Release`/`Op::Move` cleanup) for the buffer about to leave the
8133/// cache, INSTEAD of `drain_inflight_vulkan` + `force_flush` (two host-blocking
8134/// fence waits) — so the iGPU work the executor was overlapping with CUDA is not
8135/// stalled at every eviction.
8136///
8137/// Two classes of Vulkan reader can hold a reference to `destroyed`'s buffer at
8138/// the eviction:
8139///   1. the **in-flight** `SubmittedBatch`es in `inflight` (submitted CBs, each
8140///      fenced), and
8141///   2. the **open**, not-yet-submitted recorder batch (recorded commands, NO
8142///      fence yet).
8143///
8144/// We make BOTH fence-gated without blocking the host:
8145///   - `eager_submit_all_vulkan` submits the open batch WITHOUT waiting, turning
8146///     it into one more in-flight `SubmittedBatch` (now fenced) pushed onto
8147///     `inflight`. (Whole-chunk granularity — UAF/race-safe per its contract; at a
8148///     destructive eviction the open batch is a contiguous Vulkan run.)
8149///   - We then move a refcount clone of the evicted buffer's `Arc<VulkanBuffer>`
8150///     into EVERY in-flight batch (conservative: we cannot cheaply map
8151///     buffer→batch, exactly the reason the old drain waited *all* of them). Each
8152///     batch frees its retained clone POST-fence on `Drop` (follow-on #2).
8153///
8154/// After this returns the caller `cache.remove`s `destroyed`; the cache's
8155/// `Arc<RwLock<Storage>>` drops, but the buffer's recycler
8156/// (`VulkanBuffer::drop`) reclaims it only when its LAST `Arc` drops — and the
8157/// retained clones keep it alive until their owning batches' fences signal. So the
8158/// GPU's last read of the buffer strictly precedes the free (NO use-after-free),
8159/// the host never blocks at the eviction (the iGPU keeps overlapping CUDA — the
8160/// throughput win), and every batch (hence every retained buffer) is drained by
8161/// realize-end at the latest (`drain_inflight_vulkan`, `pipelined.rs:916/1238`,
8162/// runs unconditionally → NO leak).
8163///
8164/// **Multi-backend only** (the call site gates `if multi_backend`). On a
8165/// single-device realize the open batch is drained by the blocking
8166/// [`force_flush_vulkan`] instead (byte-identical to pre-A2.1; see its doc for
8167/// why the deferred path is unsafe without the cross-batch RAW guard). No-op for a
8168/// non-Vulkan storage, an empty open + no in-flight batches, or a non-Vulkan build.
8169/// Open-batch size (dispatches) at which a deferred eviction submits the batch so the
8170/// GPU runs it while the host keeps recording.
8171#[cfg(feature = "vulkan")]
8172const EVICT_SUBMIT_MIN_DISPATCHES: usize = 48;
8173
8174#[cfg(feature = "vulkan")]
8175fn defer_evicted_vulkan_buffer(
8176    cache: &StorageCache,
8177    destroyed: NodeId,
8178    inflight: &mut Vec<VulkanCompletion>,
8179) -> Result<()> {
8180    // Pull the evicted buffer's device Arc (and its backend) out of the cache BEFORE
8181    // it is removed. Non-Vulkan storage, a host-evicted (no device buffer) Vulkan
8182    // storage, or an absent entry → nothing to retain (no Vulkan reader can hold a
8183    // device buffer).
8184    let (buf, backend) = {
8185        let Some(arc) = cache.get(&destroyed) else {
8186            return Ok(());
8187        };
8188        let guard = arc
8189            .read()
8190            .map_err(|_| poisoned("storage lock during deferred-eviction retain"))?;
8191        match &guard.inner {
8192            fuel_memory::BackendStorage::Vulkan(v) => (v.device_buffer_arc(), v.backend().cloned()),
8193            _ => (None, None),
8194        }
8195    };
8196    let Some(buf) = buf else { return Ok(()) };
8197
8198    // The OPEN batch may hold recorded-but-unsubmitted commands that read `destroyed`:
8199    // retain the buffer on the open batch itself (freed post-fence once that batch is
8200    // submitted and waited). This neither submits nor waits — it used to eager-submit
8201    // here, i.e. one queue submit per eviction (61 per Qwen3 decode step).
8202    // Whether the open batch held recorded work (so the retain above actually kept a reader's
8203    // buffer alive instead of blocking): read BEFORE the eager submit below empties it.
8204    let retained_in_open_batch = backend.as_ref().is_some_and(|b| b.open_batch_len() > 0);
8205    if let Some(backend) = &backend {
8206        backend.retain_in_open_batch(buf.clone());
8207    }
8208    // Retain a clone of the evicted buffer in EVERY in-flight batch. Each frees it
8209    // POST-fence on `Drop` — the buffer outlives the GPU's last read with no host
8210    // block. Conservative over all batches (no cheap buffer→batch map); over-retention
8211    // only lengthens the lifetime, never a UAF, and all batches drain by realize-end.
8212    for vc in inflight.iter_mut() {
8213        vc.retain_data(buf.clone());
8214    }
8215    // Keep the GPU fed: submit the open batch once it has grown by a chunk.
8216    if let Some(backend) = backend
8217        && backend.open_batch_len() >= EVICT_SUBMIT_MIN_DISPATCHES
8218    {
8219        eager_submit_all_vulkan(cache, inflight)?;
8220    }
8221    // Step E A2.1 — throughput-observability. Count a DEFERRED retain that
8222    // actually replaced a host block: an evicted Vulkan buffer retained onto ≥1
8223    // in-flight batch (the open-batch eager-submit and/or pre-existing in-flight
8224    // batches). Pre-A2.1 every such site host-blocked (`force_flush` and/or
8225    // `drain_inflight_vulkan`); now it does not. A test reads
8226    // [`deferred_eviction_retains`] to assert the deferred path fired without a
8227    // drain (deterministic — no wall-clock, which is noisy on this box). When
8228    // `inflight` is empty AND the open batch was empty there was genuinely no in-flight/open
8229    // Vulkan reader to wait for, so no host block was avoided (and none was needed) — not
8230    // counted. A retain onto a non-empty OPEN batch counts (GAP-371: the counter used to look
8231    // only at in-flight batches, so an eviction inside the still-open batch, which is the
8232    // common single-chunk case, never advanced it even though it avoided the host block).
8233    if retained_in_open_batch || !inflight.is_empty() {
8234        DEFERRED_EVICTION_RETAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8235    }
8236    Ok(())
8237}
8238
8239/// Step E A2.1 — cumulative count of deferred-deletion retains that replaced a
8240/// host-blocking eviction drain (an evicted Vulkan buffer retained onto ≥1
8241/// in-flight batch instead of waiting it). Process-global, `Relaxed` — a pure
8242/// test/telemetry observation, never a correctness gate (mirrors the B1 in-flight
8243/// counter idiom). Read by the live deferred-eviction throughput test.
8244#[cfg(feature = "vulkan")]
8245pub static DEFERRED_EVICTION_RETAINS: std::sync::atomic::AtomicUsize =
8246    std::sync::atomic::AtomicUsize::new(0);
8247
8248/// Read the A2.1 deferred-eviction-retain counter (see
8249/// [`DEFERRED_EVICTION_RETAINS`]). `pub` so the live throughput test can assert a
8250/// deferred retain fired (the eviction did NOT host-block on a Vulkan fence).
8251#[cfg(feature = "vulkan")]
8252pub fn deferred_eviction_retains() -> usize {
8253    DEFERRED_EVICTION_RETAINS.load(std::sync::atomic::Ordering::Relaxed)
8254}
8255
8256#[cfg(not(feature = "vulkan"))]
8257#[inline]
8258fn defer_evicted_vulkan_buffer(
8259    _cache: &StorageCache,
8260    _destroyed: NodeId,
8261    _inflight: &mut Vec<InflightVulkan>,
8262) -> Result<()> {
8263    Ok(())
8264}
8265
8266/// Materialize a contiguous Storage Arc from a non-contiguous one.
8267/// Allocates a fresh buffer on the input's backend and copies the
8268/// strided / offset / broadcast input into it via the backend's
8269/// contiguize kernel. The returned Arc is a brand-new buffer; the
8270/// caller is responsible for replacing the cache entry only for the
8271/// duration of one kernel call (the upstream view op's output stays
8272/// in the cache so other consumers still see the strided view).
8273///
8274/// Stage 4 of Layout-on-Node — auto-Contiguize.
8275fn auto_contiguize(arc: &Arc<RwLock<Storage>>, layout: &Layout) -> Result<Arc<RwLock<Storage>>> {
8276    let in_guard = arc
8277        .read()
8278        .map_err(|_| poisoned("input storage lock during auto_contiguize"))?;
8279    let dtype = in_guard.dtype;
8280    let dtype_size = dtype.size_in_bytes();
8281    let new_storage = match &in_guard.inner {
8282        fuel_memory::BackendStorage::Cpu(c) => {
8283            let new_bytes = fuel_cpu_backend::byte_kernels::contiguize_cpu(c, layout, dtype_size)?;
8284            Storage::new(fuel_memory::BackendStorage::Cpu(new_bytes), dtype)
8285        }
8286        #[cfg(feature = "cuda")]
8287        fuel_memory::BackendStorage::Cuda(c) => {
8288            // Native baracuda contiguize (alpha.29). Byte-width-
8289            // dispatched: 1/2/4/8/16 byte elements all route to the
8290            // appropriate kernel. Handles signed strides (Flip),
8291            // zero strides (BroadcastTo), and non-zero element offset.
8292            //
8293            // Three host-side fast paths bake into the baracuda
8294            // launchers: already-contiguous → single cuMemcpyDtoDAsync;
8295            // innermost-stride-1 → per-outer-coord run copy; generic
8296            // → one thread per output element. Retires the prior
8297            // D2H → CPU contiguize_cpu → H2D fallback (two device
8298            // round-trips per non-contig input).
8299            let contig = fuel_cuda_backend::baracuda::contiguize::contiguize_to_fresh(
8300                c, layout, dtype_size,
8301            )?;
8302            Storage::new(fuel_memory::BackendStorage::Cuda(contig), dtype)
8303        }
8304        #[cfg(feature = "vulkan")]
8305        fuel_memory::BackendStorage::Vulkan(v) => {
8306            // Native `strided_copy_signed_*` kernel when it applies (2/4/8-byte
8307            // elements; see `contiguize_vulkan`). Otherwise the V.1.B host round trip:
8308            // D2H → CPU contiguize_cpu → H2D, which forces a flush and a wait
8309            // per call.
8310            let backend = v.backend().ok_or_else(|| {
8311                Error::Msg(
8312                    "auto_contiguize: Vulkan input has no backend handle. \
8313                     Storages flowing through the pipelined executor's Vulkan \
8314                     path must be constructed via VulkanBackend::alloc_bytes_handle \
8315                     / upload_bytes_handle (not the legacy alloc_bytes / \
8316                     upload_bytes which leave VulkanStorageBytes::backend = None)."
8317                        .to_string(),
8318                )
8319                .bt()
8320            })?;
8321            if let Some(native) = fuel_vulkan_backend::contiguize_vulkan(v, layout, dtype_size)? {
8322                return Ok(Arc::new(RwLock::new(Storage::new(
8323                    fuel_memory::BackendStorage::Vulkan(native),
8324                    dtype,
8325                ))));
8326            }
8327            let _t = crate::compiled::op_profile::PhaseTimer::start(
8328                "auto_contiguize.vulkan_host_roundtrip",
8329            );
8330            let host_bytes = backend.download_bytes(v)?;
8331            let host_cpu = fuel_cpu_backend::byte_storage::CpuStorageBytes::from_bytes(&host_bytes);
8332            let contig_cpu =
8333                fuel_cpu_backend::byte_kernels::contiguize_cpu(&host_cpu, layout, dtype_size)?;
8334            let host_contig_bytes = contig_cpu.bytes().to_vec();
8335            let vk_bytes = backend.upload_bytes_handle(&host_contig_bytes)?;
8336            Storage::new(fuel_memory::BackendStorage::Vulkan(vk_bytes), dtype)
8337        }
8338        #[allow(unreachable_patterns)]
8339        _ => {
8340            return Err(Error::Msg(
8341                "auto_contiguize: backend not wired (CPU + CUDA + Vulkan are \
8342                 wired today; Metal extends this match when its byte-storage \
8343                 substrate lands)"
8344                    .to_string(),
8345            )
8346            .bt());
8347        }
8348    };
8349    Ok(Arc::new(RwLock::new(new_storage)))
8350}
8351
8352/// Write-into sibling of [`auto_contiguize`] (CapturedRun executor
8353/// build-out, 4b-γ): materializes a contiguous copy of `arc` at `layout`
8354/// INTO `dest`'s EXISTING buffer instead of allocating a fresh one — the
8355/// path `WorkItemKind::ContiguizeOf`'s Reuse-mode branch needs (device
8356/// allocation is illegal inside a capture scope). `dest` must already be
8357/// sized to the contiguized output's byte count — true by construction,
8358/// since the persistent map only ever holds a buffer THIS SAME code path
8359/// (the warm-run `auto_contiguize` allocation) sized.
8360///
8361/// CUDA-only today: `PersistentOutputs::reuse` (Reuse mode) is only ever
8362/// constructed inside [`PipelinedExecutor::capture_decode`], which is
8363/// `#[cfg(feature = "cuda")]`-gated and validates every compute node
8364/// targets `Cuda` — a CPU or Vulkan storage can never actually reach this
8365/// function in practice. Per this project's "never panic on production
8366/// paths" rule, the other backends still surface a typed gap rather than
8367/// silently mishandling it (never a crash).
8368#[cfg_attr(not(feature = "cuda"), allow(unused_variables))]
8369fn contiguize_into(
8370    dest: &Arc<RwLock<Storage>>,
8371    arc: &Arc<RwLock<Storage>>,
8372    layout: &Layout,
8373) -> Result<()> {
8374    let in_guard = arc
8375        .read()
8376        .map_err(|_| poisoned("input storage lock during contiguize_into"))?;
8377    match &in_guard.inner {
8378        #[cfg(feature = "cuda")]
8379        fuel_memory::BackendStorage::Cuda(src_cuda) => {
8380            let dtype_size = in_guard.dtype.size_in_bytes();
8381            let mut dest_guard = dest
8382                .write()
8383                .map_err(|_| poisoned("dest storage lock during contiguize_into"))?;
8384            let dest_cuda = match &mut dest_guard.inner {
8385                fuel_memory::BackendStorage::Cuda(d) => d,
8386                other => {
8387                    return Err(Error::Msg(format!(
8388                        "contiguize_into: dest is BackendStorage::{:?}, not Cuda",
8389                        other.backend_id(),
8390                    ))
8391                    .bt());
8392                }
8393            };
8394            fuel_cuda_backend::baracuda::contiguize::contiguize_into(
8395                src_cuda, layout, dest_cuda, dtype_size,
8396            )
8397        }
8398        #[allow(unreachable_patterns)]
8399        _ => Err(Error::Msg(
8400            "contiguize_into: only CUDA is wired (PersistentOutputs::reuse / \
8401             capture_decode is CUDA-only today — no CPU/Vulkan consumer exists \
8402             yet; extend this match if one appears)"
8403                .to_string(),
8404        )
8405        .bt()),
8406    }
8407}
8408
8409#[cfg(test)]
8410mod backend_neutral_tests {
8411    use super::*;
8412
8413    #[test]
8414    fn only_deviceless_items_are_backend_neutral() {
8415        let n = NodeId(0);
8416        // Adopting an input-cache entry or aliasing a producer touches no device.
8417        assert!(is_backend_neutral(&WorkItemKind::ConstAdopt));
8418        assert!(is_backend_neutral(&WorkItemKind::ViewOf { input: n }));
8419        assert!(is_backend_neutral(&WorkItemKind::SlotView { producer: n }));
8420        // Contiguize runs on its input's backend; its own `target_backend` is a
8421        // placeholder, so it must not count as a backend switch.
8422        assert!(is_backend_neutral(&WorkItemKind::ContiguizeOf { input: n }));
8423        // Sabotage siblings: anything that runs a kernel of its own or moves bytes
8424        // across devices is NOT, so a real backend switch still arms the
8425        // chunk-boundary logic.
8426        assert!(!is_backend_neutral(&WorkItemKind::Kernel));
8427        assert!(!is_backend_neutral(&WorkItemKind::Copy {
8428            target_location: DeviceLocation::Cpu
8429        }));
8430        assert!(!is_backend_neutral(&WorkItemKind::WriteSlice {
8431            dest: n,
8432            source: n
8433        }));
8434    }
8435}
8436
8437#[cfg(test)]
8438mod tests {
8439    // ---- GAP-380 (a2): the plan-time arm guard ----------------------------------------------
8440
8441    fn iota_graph(backend: BackendId) -> (Graph, NodeId) {
8442        let mut g = Graph::new();
8443        let id = g.push(Node {
8444            op: Op::Iota { len: 4 },
8445            inputs: vec![],
8446            shape: fuel_ir::Shape::from_dims(&[4]),
8447            dtype: DType::F32,
8448        });
8449        g.set_target_backend(id, backend);
8450        (g, id)
8451    }
8452
8453    #[test]
8454    fn an_iota_on_a_backend_with_no_arm_fails_at_plan_time_naming_node_and_op() {
8455        let (g, id) = iota_graph(BackendId::Vulkan);
8456        let err = check_direct_arms_wired(&g, &[id])
8457            .expect_err("Vulkan has no Iota arm")
8458            .to_string();
8459        assert!(
8460            err.contains(&format!("Node#{}", id.0)),
8461            "names the node: {err}"
8462        );
8463        assert!(err.contains("Iota"), "names the op: {err}");
8464        assert!(err.contains("Vulkan"), "names the backend: {err}");
8465    }
8466
8467    /// Sabotage siblings: the same guard passes where the arm IS wired, so the red above is the
8468    /// missing arm and not the guard rejecting everything.
8469    #[test]
8470    fn an_iota_on_cpu_passes_the_arm_guard_and_other_ops_are_not_direct_dispatched() {
8471        let (g, id) = iota_graph(BackendId::Cpu);
8472        check_direct_arms_wired(&g, &[id]).expect("CPU Iota is wired");
8473        assert_eq!(
8474            direct_arm_wired(&Op::Add, BackendId::Cuda),
8475            None,
8476            "Add goes through the binding table"
8477        );
8478        assert_eq!(
8479            direct_arm_wired(&Op::Iota { len: 1 }, BackendId::Cpu),
8480            Some(true)
8481        );
8482        assert_eq!(
8483            direct_arm_wired(&Op::Iota { len: 1 }, BackendId::Cuda),
8484            Some(cfg!(feature = "cuda")),
8485            "the CUDA arm is wired exactly when the cuda feature compiles it"
8486        );
8487    }
8488
8489    use super::*;
8490    use fuel_graph::Node;
8491    use fuel_ir::Shape;
8492
8493    /// Task 5 (C6): `Op::Scan` has no native kernel in Phase 1 — it is
8494    /// always lowered/re-fused before execution — so `op_to_op_kind` must
8495    /// fall through its `_ => None` wildcard for it, exactly like any other
8496    /// not-yet-wired op. Regression lock, not born-red: this is expected to
8497    /// pass immediately.
8498    #[test]
8499    fn scan_has_no_dispatch_op_kind() {
8500        use fuel_graph::{Op, ScanEmit};
8501        assert_eq!(
8502            crate::pipelined::op_to_op_kind(&Op::Scan {
8503                n_carries: 1,
8504                n_xs: 0,
8505                bound: 2,
8506                emit: ScanEmit::All,
8507                early_exit: None
8508            }),
8509            None,
8510        );
8511    }
8512
8513    /// Step E A4b open question #4 — "event only where waited", step 1.
8514    /// `build_wait_set` collects exactly the producers of `Op::Copy`/`Move`
8515    /// nodes in the order: a same-device-only node (never copied/moved) must
8516    /// be ABSENT, and the Copy's own node id must not appear either (it is
8517    /// not its own producer).
8518    #[test]
8519    fn build_wait_set_collects_only_cross_device_copy_producers() {
8520        let mut g = Graph::new();
8521        let const_id = g.push(Node {
8522            op: Op::Const,
8523            inputs: vec![],
8524            shape: Shape::from_dims(&[4]),
8525            dtype: DType::F32,
8526        });
8527        // Same-device-only consumer of const_id — never fed into a Copy/Move.
8528        let same_device_id = g.push(Node {
8529            op: Op::Contiguize,
8530            inputs: vec![const_id],
8531            shape: Shape::from_dims(&[4]),
8532            dtype: DType::F32,
8533        });
8534        // A cross-device Copy whose producer is `same_device_id`.
8535        let copy_id = g.push(Node {
8536            op: Op::Copy {
8537                target: DeviceLocation::Cuda { gpu_id: 0 },
8538            },
8539            inputs: vec![same_device_id],
8540            shape: Shape::from_dims(&[4]),
8541            dtype: DType::F32,
8542        });
8543        let order = vec![const_id, same_device_id, copy_id];
8544
8545        let set = build_wait_set(&g, &order);
8546        assert!(
8547            set.contains(&same_device_id),
8548            "the Copy's producer must be in the wait set"
8549        );
8550        assert!(
8551            !set.contains(&const_id),
8552            "a node with no Copy/Move consumer must be absent from the wait set"
8553        );
8554        assert!(
8555            !set.contains(&copy_id),
8556            "the Copy node itself is not its own producer"
8557        );
8558        assert_eq!(
8559            set.len(),
8560            1,
8561            "only the one true cross-device producer is in the set"
8562        );
8563    }
8564
8565    /// A `Move` producer is collected the same way as a `Copy` producer.
8566    #[test]
8567    fn build_wait_set_collects_move_producers_too() {
8568        let mut g = Graph::new();
8569        let const_id = g.push(Node {
8570            op: Op::Const,
8571            inputs: vec![],
8572            shape: Shape::from_dims(&[4]),
8573            dtype: DType::F32,
8574        });
8575        let move_id = g.push(Node {
8576            op: Op::Move {
8577                target: DeviceLocation::Cpu,
8578            },
8579            inputs: vec![const_id],
8580            shape: Shape::from_dims(&[4]),
8581            dtype: DType::F32,
8582        });
8583        let order = vec![const_id, move_id];
8584
8585        let set = build_wait_set(&g, &order);
8586        assert!(
8587            set.contains(&const_id),
8588            "the Move's producer must be in the wait set"
8589        );
8590        assert_eq!(set.len(), 1);
8591    }
8592
8593    /// A CPU-only order (no `Op::Copy`/`Op::Move` anywhere) yields an empty
8594    /// wait set — every node in it is eligible for elision.
8595    #[test]
8596    fn build_wait_set_is_empty_for_cpu_only_order() {
8597        let mut g = Graph::new();
8598        let const_id = g.push(Node {
8599            op: Op::Const,
8600            inputs: vec![],
8601            shape: Shape::from_dims(&[4]),
8602            dtype: DType::F32,
8603        });
8604        let contig_id = g.push(Node {
8605            op: Op::Contiguize,
8606            inputs: vec![const_id],
8607            shape: Shape::from_dims(&[4]),
8608            dtype: DType::F32,
8609        });
8610        let order = vec![const_id, contig_id];
8611
8612        let set = build_wait_set(&g, &order);
8613        assert!(
8614            set.is_empty(),
8615            "a CPU-only order (no Copy/Move) yields an empty wait set"
8616        );
8617    }
8618
8619    /// `will_be_waited`'s two arms: the conservative `None` fallback (the
8620    /// `OrderSource::Streaming` case) is always `true`; a `Some(set)` checks
8621    /// membership.
8622    #[test]
8623    fn will_be_waited_none_is_conservative_true_for_any_node() {
8624        let ws: WaitSet = None;
8625        assert!(will_be_waited(&ws, NodeId(0)));
8626        assert!(will_be_waited(&ws, NodeId(12345)));
8627    }
8628
8629    #[test]
8630    fn will_be_waited_some_checks_membership() {
8631        let mut set = HashSet::new();
8632        set.insert(NodeId(3));
8633        let ws: WaitSet = Some(set);
8634        assert!(will_be_waited(&ws, NodeId(3)), "member must be waited");
8635        assert!(!will_be_waited(&ws, NodeId(4)), "non-member must be elided");
8636    }
8637
8638    /// A4b-1 test double: a `Completion` whose `wait` flips a shared flag, so a
8639    /// test can observe whether the drain actually waited it.
8640    struct FlagCompletion(std::sync::Arc<std::sync::atomic::AtomicUsize>);
8641    impl crate::compiled::Completion for FlagCompletion {
8642        fn wait(self: Box<Self>) -> Result<()> {
8643            self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
8644            Ok(())
8645        }
8646    }
8647
8648    /// A4b-1: `store_handle` keeps only `Pending` handles (so the post-drain
8649    /// empty-map assert is meaningful and the drain is O(pending)), and
8650    /// `drain_handles` waits each pending handle exactly once then empties the map.
8651    #[test]
8652    fn handle_map_stores_pending_and_drains_once() {
8653        use std::sync::Arc as StdArc;
8654        use std::sync::atomic::{AtomicUsize, Ordering};
8655
8656        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
8657
8658        // Ready handles are not stored.
8659        store_handle(&mut handles, NodeId(1), CompletionHandle::Ready);
8660        assert!(handles.is_empty(), "Ready handles must not be stored");
8661
8662        // Two pending handles are stored and each waited once on drain.
8663        let waited = StdArc::new(AtomicUsize::new(0));
8664        store_handle(
8665            &mut handles,
8666            NodeId(2),
8667            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8668        );
8669        store_handle(
8670            &mut handles,
8671            NodeId(3),
8672            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8673        );
8674        assert_eq!(handles.len(), 2);
8675
8676        drain_handles(&mut handles).expect("drain");
8677        assert_eq!(
8678            waited.load(Ordering::SeqCst),
8679            2,
8680            "each pending handle waited once"
8681        );
8682        assert!(handles.is_empty(), "map empty after drain");
8683    }
8684
8685    /// A4b-1: re-keying a NodeId with a new Pending handle waits the prior one
8686    /// (no leaked async work), and storing `Ready` over a prior Pending also
8687    /// waits it. Defensive — NodeIds are unique per realize in practice.
8688    #[test]
8689    fn handle_map_rekey_waits_previous() {
8690        use std::sync::Arc as StdArc;
8691        use std::sync::atomic::{AtomicUsize, Ordering};
8692
8693        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
8694        let waited = StdArc::new(AtomicUsize::new(0));
8695
8696        store_handle(
8697            &mut handles,
8698            NodeId(7),
8699            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8700        );
8701        // Re-key with another Pending → prior is waited.
8702        store_handle(
8703            &mut handles,
8704            NodeId(7),
8705            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8706        );
8707        assert_eq!(
8708            waited.load(Ordering::SeqCst),
8709            1,
8710            "rekey waited the prior pending"
8711        );
8712
8713        // Store Ready over the live Pending → it is waited too.
8714        store_handle(&mut handles, NodeId(7), CompletionHandle::Ready);
8715        assert_eq!(
8716            waited.load(Ordering::SeqCst),
8717            2,
8718            "Ready-over-Pending waited it"
8719        );
8720        assert!(handles.is_empty());
8721
8722        drain_handles(&mut handles).expect("drain empty");
8723    }
8724
8725    /// A4b-3: `wait_producer_handle` waits the named producer's handle EXACTLY
8726    /// once and removes it from the map (the finer cross-device source-drain
8727    /// consumes the producer's completion before the Copy reads its buffer), and
8728    /// is a no-op for an absent producer (CPU / Vulkan-`Ready` source, or an
8729    /// already-consumed handle). The realize-end drain then waits only what
8730    /// remains — no double-wait.
8731    #[test]
8732    fn wait_producer_handle_consumes_named_handle_once() {
8733        use std::sync::Arc as StdArc;
8734        use std::sync::atomic::{AtomicUsize, Ordering};
8735
8736        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
8737        let waited = StdArc::new(AtomicUsize::new(0));
8738
8739        // Two producers in flight; the Copy's source is NodeId(2).
8740        store_handle(
8741            &mut handles,
8742            NodeId(2),
8743            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8744        );
8745        store_handle(
8746            &mut handles,
8747            NodeId(5),
8748            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8749        );
8750
8751        // Absent producer → no-op (a CPU/Vulkan-Ready source has no handle).
8752        wait_producer_handle(&mut handles, NodeId(99)).expect("absent is no-op");
8753        assert_eq!(
8754            waited.load(Ordering::SeqCst),
8755            0,
8756            "absent producer waited nothing"
8757        );
8758        assert_eq!(handles.len(), 2);
8759
8760        // The cross-device copy's source: waited once, removed from the map.
8761        wait_producer_handle(&mut handles, NodeId(2)).expect("wait source");
8762        assert_eq!(
8763            waited.load(Ordering::SeqCst),
8764            1,
8765            "source producer waited once"
8766        );
8767        assert!(!handles.contains_key(&NodeId(2)), "source handle consumed");
8768        assert!(
8769            handles.contains_key(&NodeId(5)),
8770            "unrelated handle untouched"
8771        );
8772
8773        // Re-waiting the (now absent) source is a no-op — no double-wait.
8774        wait_producer_handle(&mut handles, NodeId(2)).expect("re-wait is no-op");
8775        assert_eq!(waited.load(Ordering::SeqCst), 1, "no double-wait");
8776
8777        // Realize-end drain waits only the remaining unrelated producer.
8778        drain_handles(&mut handles).expect("drain");
8779        assert_eq!(
8780            waited.load(Ordering::SeqCst),
8781            2,
8782            "drain waited the remaining one"
8783        );
8784        assert!(handles.is_empty());
8785    }
8786
8787    /// Op::Contiguize on a contiguous-already input is zero-copy:
8788    /// the executor adopts the input Storage Arc unchanged.
8789    #[test]
8790    fn op_contiguize_zero_copy_on_contiguous_input() {
8791        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
8792
8793        let graph = Arc::new(RwLock::new(Graph::new()));
8794        let (const_id, contig_id) = {
8795            let mut g = graph.write().unwrap();
8796            let const_id = g.push(Node {
8797                op: Op::Const,
8798                inputs: vec![],
8799                shape: Shape::from_dims(&[2, 2]),
8800                dtype: DType::F32,
8801            });
8802            let contig_id = g.push(Node {
8803                op: Op::Contiguize,
8804                inputs: vec![const_id],
8805                shape: Shape::from_dims(&[2, 2]),
8806                dtype: DType::F32,
8807            });
8808            // No need to set target_backend on Contiguize — the
8809            // executor inherits or defaults to CPU.
8810            (const_id, contig_id)
8811        };
8812
8813        let mut inputs = StorageCache::new();
8814        let input_arc = Arc::new(RwLock::new(storage));
8815        let input_arc_for_compare = Arc::clone(&input_arc);
8816        inputs.insert(const_id, input_arc);
8817
8818        let (result_arc, _) =
8819            PipelinedExecutor::realize(graph, contig_id, inputs).expect("realize");
8820
8821        // Same Arc → zero-copy adoption. Compare by raw pointer.
8822        assert!(
8823            Arc::ptr_eq(&result_arc, &input_arc_for_compare),
8824            "Op::Contiguize on contiguous input must adopt the input Arc (zero copy)",
8825        );
8826    }
8827
8828    /// Op::Contiguize on a strided input (here: a transposed view)
8829    /// materializes a fresh contiguous Storage. The output bytes
8830    /// reflect the strided view's logical content, not the input
8831    /// storage's underlying memory order.
8832    #[test]
8833    fn op_contiguize_materializes_on_strided_input() {
8834        // 2x3 row-major: [[1,2,3],[4,5,6]] → transpose → 3x2:
8835        // [[1,4],[2,5],[3,6]]. The transposed view shares the
8836        // original buffer; Op::Contiguize on the transpose
8837        // materializes contiguous bytes matching the transposed
8838        // logical order.
8839        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
8840
8841        let graph = Arc::new(RwLock::new(Graph::new()));
8842        let (const_id, _transpose_id, contig_id) = {
8843            let mut g = graph.write().unwrap();
8844            let const_id = g.push(Node {
8845                op: Op::Const,
8846                inputs: vec![],
8847                shape: Shape::from_dims(&[2, 3]),
8848                dtype: DType::F32,
8849            });
8850            let transpose_id = g.push(Node {
8851                op: Op::Transpose,
8852                inputs: vec![const_id],
8853                shape: Shape::from_dims(&[3, 2]),
8854                dtype: DType::F32,
8855            });
8856            let contig_id = g.push(Node {
8857                op: Op::Contiguize,
8858                inputs: vec![transpose_id],
8859                shape: Shape::from_dims(&[3, 2]),
8860                dtype: DType::F32,
8861            });
8862            (const_id, transpose_id, contig_id)
8863        };
8864
8865        let mut inputs = StorageCache::new();
8866        inputs.insert(const_id, Arc::new(RwLock::new(storage)));
8867
8868        let (result_arc, _) =
8869            PipelinedExecutor::realize(graph, contig_id, inputs).expect("realize");
8870
8871        let guard = result_arc.read().unwrap();
8872        let cpu = if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
8873            c
8874        } else {
8875            panic!("expected Cpu storage");
8876        };
8877        let typed: &[f32] = cpu.as_slice().expect("f32 cast");
8878        // Transposed logical order: [1,4,2,5,3,6].
8879        assert_eq!(
8880            typed,
8881            &[1.0, 4.0, 2.0, 5.0, 3.0, 6.0],
8882            "contiguized transpose must reflect logical (transposed) byte order",
8883        );
8884    }
8885
8886    /// E2E: 3-node graph (Const + Const + Add), pre-seeded inputs,
8887    /// realized through the compiler+executor thread pair, returns
8888    /// expected sum bytes.
8889    #[test]
8890    fn pipelined_realize_const_const_add() {
8891        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
8892        let rhs_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
8893
8894        let graph = Arc::new(RwLock::new(Graph::new()));
8895        let (lhs_id, rhs_id, add_id) = {
8896            let mut g = graph.write().unwrap();
8897            let lhs_id = g.push(Node {
8898                op: Op::Const,
8899                inputs: vec![],
8900                shape: Shape::from_dims(&[3]),
8901                dtype: DType::F32,
8902            });
8903            let rhs_id = g.push(Node {
8904                op: Op::Const,
8905                inputs: vec![],
8906                shape: Shape::from_dims(&[3]),
8907                dtype: DType::F32,
8908            });
8909            let add_id = g.push(Node {
8910                op: Op::Add,
8911                inputs: vec![lhs_id, rhs_id],
8912                shape: Shape::from_dims(&[3]),
8913                dtype: DType::F32,
8914            });
8915            g.set_target_backend(add_id, BackendId::Cpu);
8916            (lhs_id, rhs_id, add_id)
8917        };
8918
8919        let mut inputs = StorageCache::new();
8920        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
8921        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
8922
8923        let (result_arc, _result_layout) =
8924            PipelinedExecutor::realize(graph, add_id, inputs).expect("realize");
8925
8926        let guard = result_arc.read().unwrap();
8927        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
8928            let typed: &[f32] = c.as_slice().expect("f32 cast");
8929            assert_eq!(typed, &[11.0, 22.0, 33.0]);
8930        } else {
8931            panic!("expected CPU output");
8932        }
8933    }
8934
8935    /// PR-C1 behavior contract: `realize_with_optimized_route` with an
8936    /// **empty** route (the no-pressure / no-telemetry case) is
8937    /// byte-identical to `realize_with_optimized` (arm-0). On a branchless
8938    /// graph the route has no branches to resolve, so both must produce
8939    /// the same bytes — realize is unchanged from Phase B.
8940    #[test]
8941    fn realize_with_optimized_route_empty_equals_arm0() {
8942        use crate::optimize::OptimizedGraph;
8943
8944        let build = || {
8945            let graph = Arc::new(RwLock::new(Graph::new()));
8946            let (lhs_id, rhs_id, add_id) = {
8947                let mut g = graph.write().unwrap();
8948                let lhs_id = g.push(Node {
8949                    op: Op::Const,
8950                    inputs: vec![],
8951                    shape: Shape::from_dims(&[3]),
8952                    dtype: DType::F32,
8953                });
8954                let rhs_id = g.push(Node {
8955                    op: Op::Const,
8956                    inputs: vec![],
8957                    shape: Shape::from_dims(&[3]),
8958                    dtype: DType::F32,
8959                });
8960                let add_id = g.push(Node {
8961                    op: Op::Add,
8962                    inputs: vec![lhs_id, rhs_id],
8963                    shape: Shape::from_dims(&[3]),
8964                    dtype: DType::F32,
8965                });
8966                g.set_target_backend(add_id, BackendId::Cpu);
8967                (lhs_id, rhs_id, add_id)
8968            };
8969            let mut inputs = StorageCache::new();
8970            inputs.insert(
8971                lhs_id,
8972                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
8973                    1.0_f32, 2.0, 3.0,
8974                ]))),
8975            );
8976            inputs.insert(
8977                rhs_id,
8978                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
8979                    10.0_f32, 20.0, 30.0,
8980                ]))),
8981            );
8982            (graph, add_id, inputs)
8983        };
8984
8985        let read_bytes = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8986            let guard = arc.read().unwrap();
8987            match &guard.inner {
8988                fuel_memory::BackendStorage::Cpu(c) => {
8989                    c.as_slice::<f32>().expect("f32 cast").to_vec()
8990                }
8991                _ => panic!("expected CPU output"),
8992            }
8993        };
8994
8995        // Stamp the fixture with the LIVE topology generation rather than a
8996        // hard-coded 0. The executor's chunk-boundary check compares the plan's
8997        // stamped generation against `topology_generation()`; a real
8998        // `OptimizedGraph` carries the generation snapshotted at optimize time
8999        // (`plan.rs` `compile_plan`, which reads it *after* the bindings table
9000        // is warm), so it already reflects every registered backend. Force
9001        // `global_bindings()` init here so any feature-gated auto-registration
9002        // has run and settled the counter before we read it — otherwise a stale
9003        // read would be bumped out from under us the first time realize warms
9004        // the bindings. Under default features this is 0; under
9005        // `--features vulkan`, `register_derived_gpu_caps` bumps it to 1.
9006        drop(global_bindings());
9007        let live_gen = crate::dispatch::topology_generation();
9008
9009        // Arm-0 path.
9010        let (g_a, add_a, in_a) = build();
9011        let opt_a = OptimizedGraph {
9012            roots: vec![add_a],
9013            generation: live_gen,
9014            placements: None,
9015            eviction: None,
9016        };
9017        let (arm0_arc, _) = PipelinedExecutor::realize_with_optimized(g_a, add_a, in_a, &opt_a)
9018            .expect("arm-0 realize");
9019        let arm0 = read_bytes(&arm0_arc);
9020
9021        // Empty-route path — must match arm-0 exactly.
9022        let (g_r, add_r, in_r) = build();
9023        let opt_r = OptimizedGraph {
9024            roots: vec![add_r],
9025            generation: live_gen,
9026            placements: None,
9027            eviction: None,
9028        };
9029        let empty_route = PickedRoute::new();
9030        let (route_arc, _) =
9031            PipelinedExecutor::realize_with_optimized_route(g_r, add_r, in_r, &opt_r, &empty_route)
9032                .expect("empty-route realize");
9033        let routed = read_bytes(&route_arc);
9034
9035        assert_eq!(arm0, vec![11.0, 22.0, 33.0]);
9036        assert_eq!(
9037            routed, arm0,
9038            "an empty route realizes byte-identically to arm-0 (Phase B contract)",
9039        );
9040    }
9041
9042    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
9043    /// §5): [`PipelinedExecutor::realize_with_optimized_picking_cached_env`]
9044    /// over a shared `order_cache` must (a) realize byte-identically to the
9045    /// uncached arm-0 path, on both the cold (empty cache) and warm
9046    /// (populated cache) call, and (b) actually populate the cache on the
9047    /// first call rather than silently never using it.
9048    #[test]
9049    fn realize_with_optimized_picking_cached_env_matches_arm0_cold_and_warm() {
9050        use crate::optimize::OptimizedGraph;
9051        use std::sync::OnceLock;
9052
9053        let build = || {
9054            let graph = Arc::new(RwLock::new(Graph::new()));
9055            let (lhs_id, rhs_id, add_id) = {
9056                let mut g = graph.write().unwrap();
9057                let lhs_id = g.push(Node {
9058                    op: Op::Const,
9059                    inputs: vec![],
9060                    shape: Shape::from_dims(&[3]),
9061                    dtype: DType::F32,
9062                });
9063                let rhs_id = g.push(Node {
9064                    op: Op::Const,
9065                    inputs: vec![],
9066                    shape: Shape::from_dims(&[3]),
9067                    dtype: DType::F32,
9068                });
9069                let add_id = g.push(Node {
9070                    op: Op::Add,
9071                    inputs: vec![lhs_id, rhs_id],
9072                    shape: Shape::from_dims(&[3]),
9073                    dtype: DType::F32,
9074                });
9075                g.set_target_backend(add_id, BackendId::Cpu);
9076                (lhs_id, rhs_id, add_id)
9077            };
9078            let mut inputs = StorageCache::new();
9079            inputs.insert(
9080                lhs_id,
9081                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9082                    1.0_f32, 2.0, 3.0,
9083                ]))),
9084            );
9085            inputs.insert(
9086                rhs_id,
9087                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9088                    10.0_f32, 20.0, 30.0,
9089                ]))),
9090            );
9091            (graph, add_id, inputs)
9092        };
9093        let read_bytes = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9094            let guard = arc.read().unwrap();
9095            match &guard.inner {
9096                fuel_memory::BackendStorage::Cpu(c) => {
9097                    c.as_slice::<f32>().expect("f32 cast").to_vec()
9098                }
9099                _ => panic!("expected CPU output"),
9100            }
9101        };
9102
9103        drop(global_bindings());
9104        let live_gen = crate::dispatch::topology_generation();
9105
9106        let (g, add, inputs) = build();
9107        let optimized = OptimizedGraph {
9108            roots: vec![add],
9109            generation: live_gen,
9110            placements: None,
9111            eviction: None,
9112        };
9113        let order_cache: OnceLock<Vec<NodeId>> = OnceLock::new();
9114        assert!(order_cache.get().is_none(), "sanity: cache starts empty");
9115
9116        // Cold call: cache miss, must compute AND populate.
9117        let (cold_arc, _) = PipelinedExecutor::realize_with_optimized_picking_cached_env(
9118            g.clone(),
9119            add,
9120            inputs,
9121            &optimized,
9122            &order_cache,
9123            None,
9124            None,
9125            SymEnv::default(),
9126        )
9127        .expect("cold cached realize");
9128        assert_eq!(read_bytes(&cold_arc), vec![11.0, 22.0, 33.0]);
9129        assert!(
9130            order_cache.get().is_some(),
9131            "the cold call must populate order_cache, not leave it empty"
9132        );
9133        let cached_order_after_cold = order_cache.get().unwrap().clone();
9134
9135        // Warm call: cache hit. Fresh inputs (same graph, new values) so the
9136        // realized OUTPUT differs from the cold call while the dispatch
9137        // ORDER (what's cached) must not change.
9138        let mut warm_inputs = StorageCache::new();
9139        warm_inputs.insert(
9140            g.read().unwrap().node(add).inputs[0],
9141            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9142                100.0_f32, 200.0, 300.0,
9143            ]))),
9144        );
9145        warm_inputs.insert(
9146            g.read().unwrap().node(add).inputs[1],
9147            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9148                1.0_f32, 2.0, 3.0,
9149            ]))),
9150        );
9151        let (warm_arc, _) = PipelinedExecutor::realize_with_optimized_picking_cached_env(
9152            g,
9153            add,
9154            warm_inputs,
9155            &optimized,
9156            &order_cache,
9157            None,
9158            None,
9159            SymEnv::default(),
9160        )
9161        .expect("warm cached realize");
9162        assert_eq!(
9163            read_bytes(&warm_arc),
9164            vec![101.0, 202.0, 303.0],
9165            "warm call must realize its OWN rebound inputs, not replay stale output",
9166        );
9167        assert_eq!(
9168            order_cache.get().unwrap(),
9169            &cached_order_after_cold,
9170            "the warm call must reuse the SAME cached order, not recompute a different one",
9171        );
9172    }
9173
9174    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
9175    /// §5), PM review question: does `OrderSource::Cached` weaken the
9176    /// existing `TopologyChanged` chunk-boundary check? No — proven at the
9177    /// unit level (not a live topology-bump integration test, deliberately:
9178    /// `bump_topology_generation()` mutates a process-wide atomic shared by
9179    /// every concurrently-running test in this binary, including the cold/
9180    /// warm cache test above, which reads it into a local at the start of
9181    /// ITS OWN body and would flake if another test's bump landed mid-call;
9182    /// introducing that cross-test hazard isn't worth it when the two arms'
9183    /// `generation_for` expressions are provably identical). `generation_for`
9184    /// is private to this module, so it's tested directly here: given the
9185    /// SAME `&OptimizedGraph`, `Cached` and `Optimized` must report the
9186    /// IDENTICAL generation — the chunk-boundary check that compares this
9187    /// value against the LIVE `topology_generation()` fires exactly the
9188    /// same way for both, so caching cannot silently skip or weaken it.
9189    #[test]
9190    fn cached_generation_for_matches_optimized_generation_for() {
9191        let optimized = OptimizedGraph {
9192            roots: vec![NodeId(0)],
9193            generation: 42,
9194            placements: None,
9195            eviction: None,
9196        };
9197        let order_cache: std::sync::OnceLock<Vec<NodeId>> = std::sync::OnceLock::new();
9198
9199        let optimized_gen = generation_for(&OrderSource::Optimized {
9200            optimized: &optimized,
9201            route: None,
9202        });
9203        let cached_gen = generation_for(&OrderSource::Cached {
9204            optimized: &optimized,
9205            order_cache: &order_cache,
9206        });
9207        assert_eq!(
9208            optimized_gen,
9209            Some(42),
9210            "sanity: Optimized reports the OptimizedGraph's own generation",
9211        );
9212        assert_eq!(
9213            cached_gen, optimized_gen,
9214            "Cached must report the SAME generation as Optimized for the same \
9215             OptimizedGraph -- the TopologyChanged check cannot tell the two apart, \
9216             by construction, so caching cannot silently weaken it",
9217        );
9218    }
9219
9220    /// **PR-C3 reorder-invariance gate (CPU, runnable — ORDERING level).**
9221    /// The auto-overlap reorder is a HINT: it changes only *which order*
9222    /// independent device runs dispatch in, never *which* nodes run nor the
9223    /// result. The byte-identical-OUTPUT proof is necessarily LIVE (the
9224    /// reorder fires only on a ≥2-device graph, which needs ≥2 real backends
9225    /// to realize — see `cuda_vulkan_multidevice_realize_live`'s
9226    /// `[22,86,192,340]` oracle, which now flows through this reorder, plus
9227    /// the dual-GPU `cuda_vulkan_overlap_bench_live` arbitrary-graph
9228    /// auto-overlap gate). THIS test proves the ordering-level invariant on a
9229    /// CPU-only path: the C3 reorder of a two-device graph is a valid
9230    /// topological **permutation** of the un-reordered topo order — same node
9231    /// multiset, every node still after its inputs — that genuinely DIFFERS
9232    /// from the un-reordered order (so the reorder fired). Because the
9233    /// executor caches each node's result and every op is deterministic,
9234    /// realizing any valid topological order yields identical bytes; this
9235    /// test guards the precondition (a valid permutation) that makes that so.
9236    #[test]
9237    fn c3_reorder_is_a_valid_topo_permutation() {
9238        // Two INDEPENDENT device sub-chains over distinct consts reconverging
9239        // at a final CUDA add, the Vulkan root bridged to CUDA by an explicit
9240        // Op::Copy (a residency seam = its own run). Reconverge inputs in the
9241        // "wrong" (cuda-first) order, the order the un-reordered topo DFS pops
9242        // CUDA-last — exactly the arbitrary-graph shape the auto-overlap pass
9243        // must fix. The chains are UNARY (Relu) so each stays a single
9244        // contiguous run (no const-re-read fan-in fragmenting them), exactly
9245        // like the live benchmark's `relu(mul·add)` chains; the CUDA chain is
9246        // HEAVIER (4 vs 2) so the critical-path reorder emits it first.
9247        // (Stamps only; not realized here — the ordering proof, CPU-runnable.)
9248        let n = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9249            g.push(Node {
9250                op,
9251                inputs,
9252                shape: Shape::from_dims(&[3]),
9253                dtype: DType::F32,
9254            })
9255        };
9256        let mut g = Graph::new();
9257        let ca = n(&mut g, Op::Const, vec![]);
9258        let cb = n(&mut g, Op::Const, vec![]);
9259        // CUDA chain — HEAVIER (4 unary stages, one contiguous run).
9260        let mut cprev = ca;
9261        for _ in 0..4 {
9262            cprev = n(&mut g, Op::Relu, vec![cprev]);
9263            g.set_target_backend(cprev, BackendId::Cuda);
9264        }
9265        let c2 = cprev; // CUDA chunk root
9266        // Vulkan chain — lighter (2 unary stages).
9267        let mut vprev = cb;
9268        for _ in 0..2 {
9269            vprev = n(&mut g, Op::Relu, vec![vprev]);
9270            g.set_target_backend(vprev, BackendId::Vulkan);
9271        }
9272        let v2 = vprev; // Vulkan chunk root
9273        // Vulkan -> CUDA copy (residency seam), then reconverge on CUDA with
9274        // inputs [cuda_root, copy] (cuda-first).
9275        let copy = g.push(Node {
9276            op: Op::Copy {
9277                target: DeviceLocation::Cuda { gpu_id: 0 },
9278            },
9279            inputs: vec![v2],
9280            shape: Shape::from_dims(&[3]),
9281            dtype: DType::F32,
9282        });
9283        g.set_target_backend(copy, BackendId::Cuda);
9284        let out = n(&mut g, Op::Add, vec![c2, copy]);
9285        g.set_target_backend(out, BackendId::Cuda);
9286
9287        let unreordered = execution_plan(&g, &[out]);
9288        let reordered = fuel_graph::lower_runs_arm0(&g, &[out]);
9289
9290        // (1) The reorder FIRED — the order changed (else the test is
9291        //     vacuous + auto-overlap did nothing on an arbitrary graph).
9292        assert_ne!(
9293            reordered, unreordered,
9294            "the C3 reorder must change the order on a two-device graph; \
9295             reordered={reordered:?} unreordered={unreordered:?}",
9296        );
9297
9298        // (2) Same node multiset — a permutation, no add/drop.
9299        let mut a = unreordered.clone();
9300        let mut b = reordered.clone();
9301        a.sort();
9302        b.sort();
9303        assert_eq!(a, b, "the reorder is a permutation of the same node set");
9304
9305        // (3) The reordered order is a VALID topological order: every node
9306        //     appears after all of its inputs that are in the order.
9307        let pos: std::collections::HashMap<NodeId, usize> = reordered
9308            .iter()
9309            .enumerate()
9310            .map(|(i, &node)| (node, i))
9311            .collect();
9312        for (i, &node) in reordered.iter().enumerate() {
9313            for &inp in &g.node(node).inputs {
9314                if let Some(&j) = pos.get(&inp) {
9315                    assert!(
9316                        j < i,
9317                        "input {inp:?} of {node:?} must precede it in the reordered \
9318                         order; reordered={reordered:?}",
9319                    );
9320                }
9321            }
9322        }
9323
9324        // (4) The overlap-relevant property: BOTH device producer chunks
9325        //     (the CUDA root c2, the Vulkan root v2) are emitted BEFORE the
9326        //     host-blocking cross-device copy — the A4b overlap topology the
9327        //     un-reordered cuda-last DFS violates — AND the HEAVIER CUDA chunk
9328        //     is emitted first (critical-path: the auto-submit device runs
9329        //     earliest, the live-overlap regression guard).
9330        let p = |node: NodeId| pos[&node];
9331        assert!(p(c2) < p(copy), "CUDA chunk before the cross-device copy");
9332        assert!(p(v2) < p(copy), "Vulkan chunk before the cross-device copy");
9333        assert!(
9334            p(c2) < p(v2),
9335            "the heavier CUDA chunk is emitted before the lighter Vulkan chunk \
9336             (critical-path heavy-first); reordered={reordered:?}",
9337        );
9338    }
9339
9340    /// **C3 follow-on — the OPERAND-ORDER-INVARIANCE gate (CPU, runnable —
9341    /// the reliable operand-independence proof).** The residual the live
9342    /// `cuda_vulkan_overlap_bench_live` benchmark targets is whether the
9343    /// reconverge OPERAND order (`xc.add(&xv)` vs `xv.add(&xc)`) changes the
9344    /// wall-clock overlap. Wall-clock is thermally noisy on a heterogeneous
9345    /// dev box; the DETERMINISTIC root guarantee is this: the C3-reordered
9346    /// dispatch order the executor consumes is **byte-identical for both
9347    /// operand orders**. If the lowered order is the same, the executor
9348    /// processes the SAME WorkItem stream with the SAME cross-device
9349    /// submit/wait timing, so overlap cannot depend on the operand order.
9350    ///
9351    /// This builds the SAME two-device reconverge as
9352    /// `c3_reorder_is_a_valid_topo_permutation` but TWICE — once cuda-first
9353    /// (`add(cuda_root, copy)`), once vulkan-first (`add(copy, cuda_root)`)
9354    /// — over structurally identical graphs (same node ids, only the
9355    /// reconverge's two inputs swapped) and asserts `lower_runs_arm0` emits
9356    /// the identical op/device run sequence. The live executor trace confirms
9357    /// the same: both operand orders produce the identical WorkItem stream
9358    /// (the eager-submit/drain/wait sequence at every cross-device copy is the
9359    /// same, and the CUDA chunk is enqueued first in both).
9360    #[test]
9361    fn c3_reorder_is_operand_order_invariant() {
9362        // Build the two-device reconverge with the reconverge inputs in the
9363        // given order; return (graph, out) over a FRESH graph so node ids line
9364        // up 1:1 between the two builds (only the add's input order differs).
9365        let build = |cuda_first: bool| -> (Graph, NodeId) {
9366            let n = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9367                g.push(Node {
9368                    op,
9369                    inputs,
9370                    shape: Shape::from_dims(&[3]),
9371                    dtype: DType::F32,
9372                })
9373            };
9374            let mut g = Graph::new();
9375            let ca = n(&mut g, Op::Const, vec![]);
9376            let cb = n(&mut g, Op::Const, vec![]);
9377            let mut cprev = ca;
9378            for _ in 0..4 {
9379                cprev = n(&mut g, Op::Relu, vec![cprev]);
9380                g.set_target_backend(cprev, BackendId::Cuda);
9381            }
9382            let c2 = cprev;
9383            let mut vprev = cb;
9384            for _ in 0..2 {
9385                vprev = n(&mut g, Op::Relu, vec![vprev]);
9386                g.set_target_backend(vprev, BackendId::Vulkan);
9387            }
9388            let v2 = vprev;
9389            let copy = g.push(Node {
9390                op: Op::Copy {
9391                    target: DeviceLocation::Cuda { gpu_id: 0 },
9392                },
9393                inputs: vec![v2],
9394                shape: Shape::from_dims(&[3]),
9395                dtype: DType::F32,
9396            });
9397            g.set_target_backend(copy, BackendId::Cuda);
9398            // The ONE knob: the reconverge's two inputs, swapped.
9399            let inputs = if cuda_first {
9400                vec![c2, copy]
9401            } else {
9402                vec![copy, c2]
9403            };
9404            let out = n(&mut g, Op::Add, inputs);
9405            g.set_target_backend(out, BackendId::Cuda);
9406            (g, out)
9407        };
9408
9409        let (g_cf, out_cf) = build(true);
9410        let (g_vf, out_vf) = build(false);
9411
9412        // Lower both via the production path (dispatch_order → lower_runs_arm0
9413        // → device_alternating_order, the C3 reorder).
9414        let order_cf = fuel_graph::lower_runs_arm0(&g_cf, &[out_cf]);
9415        let order_vf = fuel_graph::lower_runs_arm0(&g_vf, &[out_vf]);
9416
9417        // The decisive guarantee: the lowered dispatch order — as an
9418        // (op, device) sequence — is IDENTICAL for both operand orders. (Node
9419        // ids can differ if the build assigned them differently, but here the
9420        // builds are structurally identical so even the ids match; compare the
9421        // op/device sequence to be robust + descriptive on failure.)
9422        let tag = |g: &Graph, ids: &[NodeId]| -> Vec<(String, Option<BackendId>)> {
9423            ids.iter()
9424                .map(|&id| (format!("{:?}", g.node(id).op), g.target_backend(id)))
9425                .collect()
9426        };
9427        let seq_cf = tag(&g_cf, &order_cf);
9428        let seq_vf = tag(&g_vf, &order_vf);
9429        assert_eq!(
9430            seq_cf, seq_vf,
9431            "the C3-reordered dispatch order MUST be identical for both \
9432             reconverge operand orders (operand-order-invariance — the \
9433             executor then sees the same WorkItem stream regardless of \
9434             operand order, so overlap is operand-insensitive).\n\
9435             cuda-first = {seq_cf:?}\nvulkan-first = {seq_vf:?}",
9436        );
9437    }
9438
9439    /// A selector that always takes the LAST arm (arm 1) so a non-arm-0
9440    /// pick is observable (a `WinnerSelector` picks arm-0 ⇒ empty route).
9441    #[cfg(test)]
9442    #[derive(Debug)]
9443    struct PickLast;
9444    #[cfg(test)]
9445    impl RuntimeSelector for PickLast {
9446        fn select<'a>(
9447            &self,
9448            set: &'a crate::ranker::AlternativeSet,
9449        ) -> Option<&'a crate::ranker::Candidate> {
9450            set.alternatives().last()
9451        }
9452    }
9453
9454    /// Build the 2-arm diamond (mirrors `route_picker::tests::diamond`):
9455    /// arm-0 on CUDA, arm-1 on CPU; the arm exits carry their
9456    /// `target_backend` so the picker reads each arm's placement. Returns
9457    /// `(graph_arc, branch, post)`.
9458    #[cfg(test)]
9459    fn picking_diamond() -> (Arc<RwLock<Graph>>, NodeId, NodeId) {
9460        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9461            g.push(Node {
9462                op,
9463                inputs,
9464                shape: Shape::from_dims(&[2]),
9465                dtype: DType::F32,
9466            })
9467        };
9468        let mut g = Graph::new();
9469        let pre = node(&mut g, Op::Const, vec![]);
9470        let diverge = node(&mut g, Op::Relu, vec![pre]);
9471        let arm0 = node(&mut g, Op::Silu, vec![diverge]);
9472        let arm1 = node(&mut g, Op::GeluTanh, vec![diverge]);
9473        g.set_target_backend(arm0, BackendId::Cuda);
9474        g.set_target_backend(arm1, BackendId::Cpu);
9475        let reconverge = node(&mut g, Op::Relu, vec![arm0]);
9476        let mut b = g.open_branch(diverge);
9477        b.add_arm(arm0);
9478        b.add_arm(arm1);
9479        let branch = b
9480            .finalize_branches(&mut g, reconverge)
9481            .expect("well-formed 2-arm branch")
9482            .expect("2 arms survive");
9483        let post = node(&mut g, Op::Tanh, vec![reconverge]);
9484        (Arc::new(RwLock::new(g)), branch, post)
9485    }
9486
9487    /// Step E Phase C, PR C1: the streaming picking entry's gate.
9488    /// `streaming_pick_for` (the streaming successor of the old one-shot
9489    /// `pick_route_for`) must (1) return `Some(pick)` when a selector + a
9490    /// branch are present (⇒ the `OrderSource::Streaming` walk), (2) return
9491    /// `None` with no selector (the `runtime_selector_disabled` opt-out ⇒
9492    /// arm-0), and (3) short-circuit to `None` on a branchless graph (the
9493    /// fast-path ⇒ the untouched `dispatch_order` lowering).
9494    #[test]
9495    fn streaming_pick_for_gates() {
9496        let (graph, _branch, post) = picking_diamond();
9497        let _ = post;
9498
9499        // (1) selector + branch ⇒ Some(pick).
9500        let sel: Arc<dyn RuntimeSelector> = Arc::new(PickLast);
9501        assert!(
9502            PipelinedExecutor::streaming_pick_for(&graph, Some(sel.clone()), None)
9503                .expect("ok")
9504                .is_some(),
9505            "selector + branch ⇒ a streaming pick",
9506        );
9507
9508        // (2) no selector ⇒ None (arm-0 lowering).
9509        assert!(
9510            PipelinedExecutor::streaming_pick_for(&graph, None, None)
9511                .expect("ok")
9512                .is_none(),
9513            "no selector ⇒ no streaming pick (arm-0 lowering)",
9514        );
9515
9516        // (3) branchless graph + selector ⇒ None (the fast-path).
9517        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9518            g.push(Node {
9519                op,
9520                inputs,
9521                shape: Shape::from_dims(&[2]),
9522                dtype: DType::F32,
9523            })
9524        };
9525        let bl_graph = {
9526            let mut g = Graph::new();
9527            let c1 = node(&mut g, Op::Const, vec![]);
9528            let c2 = node(&mut g, Op::Const, vec![]);
9529            let add = node(&mut g, Op::Add, vec![c1, c2]);
9530            g.set_target_backend(add, BackendId::Cpu);
9531            Arc::new(RwLock::new(g))
9532        };
9533        assert!(
9534            PipelinedExecutor::streaming_pick_for(&bl_graph, Some(sel), None)
9535                .expect("ok")
9536                .is_none(),
9537            "branchless graph ⇒ no branches ⇒ no streaming pick (fast-path)",
9538        );
9539    }
9540
9541    /// **C1 byte-identity gate (executor layer).** The STREAMED dispatch
9542    /// order — produced by the compiler thread's lazy per-branch resolution
9543    /// (`walk_picked_route_streaming` over `resolve_branch`, the same path
9544    /// `order_for(OrderSource::Streaming)` collects) — equals the ONE-SHOT
9545    /// order (`lower_picked_route` over the route the eager `pick_route`
9546    /// resolves) on the branched diamond, for both arm-0 (WinnerSelector)
9547    /// and arm-1 (PickLast). This is the proof that C1 changes *when* a
9548    /// branch resolves, not *which* arm — the same selector, the same
9549    /// `resolve_branch`, the same emitted order.
9550    #[test]
9551    fn streamed_order_equals_one_shot() {
9552        let (graph, _branch, post) = picking_diamond();
9553        let g = graph.read().unwrap();
9554        let bindings = global_bindings();
9555
9556        for sel in [
9557            Arc::new(crate::ranker::WinnerSelector) as Arc<dyn RuntimeSelector>,
9558            Arc::new(PickLast) as Arc<dyn RuntimeSelector>,
9559        ] {
9560            // One-shot: resolve the whole route, then lower.
9561            let one_shot_route = pick_route(&g, &[post], &bindings, sel.as_ref(), None);
9562            let one_shot = fuel_graph::lower_picked_route(&g, &[post], &one_shot_route);
9563
9564            // Streamed: resolve each branch lazily at the frontier via the
9565            // SAME `resolve_branch` the compiler thread uses.
9566            let streamed = fuel_graph::lower_picked_route_streaming(&g, &[post], |branch| {
9567                resolve_branch(&g, branch, &bindings, sel.as_ref())
9568            });
9569
9570            assert_eq!(
9571                streamed, one_shot,
9572                "streamed order must equal one-shot for selector {sel:?}",
9573            );
9574        }
9575    }
9576
9577    /// ROW 157 / GAP-385: with ONE branch in the graph, the executor realizes a PICKED multi-node arm to the
9578    /// same numbers as arm 0. This is NOT shown for chained branches: with two or more in a row it failed
9579    /// (`input ... not realized`) until the lowering-order fix of 2026-11-17 (ROADMAP row 158); see
9580    /// `chained_branches_realize_equal_to_arm_zero_for_every_combination_of_arms_on_cpu`.
9581    ///
9582    /// A residual block on the host: `c1 -> relu -> silu -> tanh -> add(c1, .)`. The branch is built by
9583    /// the pathfinder's own `record_branch` (so the clone logic under test is the shipped code) with
9584    /// the alternative backend set to `Cpu`, which lets arm 1 run on this box. The route `{branch: 1}`
9585    /// makes the executor run the cloned three-node stretch; the result must equal the arm-0 result.
9586    ///
9587    /// What this does NOT show: a cross-device arm (the real alternative is another backend, with
9588    /// copies at its entry and exit), nor which arm a live selector picks. The same-backend arms mean
9589    /// the selector cannot map back to arm 1, so the route is given explicitly.
9590    #[test]
9591    fn a_single_picked_multi_node_arm_realizes_equal_to_arm_zero_on_cpu() {
9592        let (arm0, arm1) = realize_residual_block_both_arms(false);
9593        assert_eq!(
9594            arm1, arm0,
9595            "the cloned stretch computes what arm 0 computes"
9596        );
9597        assert_eq!(arm0.len(), 3);
9598        assert!(arm0.iter().all(|v| v.is_finite()));
9599    }
9600
9601    /// POSITIVE CONTROL for the test above (one branch): when the cloned stretch computes something else
9602    /// (Gelu in place of Silu, built by hand), the picked-arm result DIFFERS from arm 0. Without this the
9603    /// equality could pass by the executor ignoring the route and running arm 0 both times.
9604    #[test]
9605    fn a_picked_multi_node_arm_that_differs_changes_the_result() {
9606        let (arm0, arm1) = realize_residual_block_both_arms(true);
9607        assert_ne!(arm1, arm0, "the route must really run the cloned arm");
9608    }
9609
9610    /// Realize `c1 -> relu -> silu -> tanh -> add(c1, .)` through arm 0 and through arm 1. Arm 1 is the
9611    /// clone `record_branch` makes, or, when `control` is set, a hand-built clone whose middle node is
9612    /// Gelu instead of Silu.
9613    #[cfg(test)]
9614    fn realize_residual_block_both_arms(control: bool) -> (Vec<f32>, Vec<f32>) {
9615        use crate::optimize::OptimizedGraph;
9616        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9617            match &arc.read().unwrap().inner {
9618                fuel_memory::BackendStorage::Cpu(c) => c.as_slice::<f32>().expect("f32").to_vec(),
9619                _ => panic!("expected CPU output"),
9620            }
9621        };
9622        let build = || {
9623            let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9624                let id = g.push(Node {
9625                    op,
9626                    inputs,
9627                    shape: Shape::from_dims(&[3]),
9628                    dtype: DType::F32,
9629                });
9630                g.set_target_backend(id, BackendId::Cpu);
9631                id
9632            };
9633            let mut g = Graph::new();
9634            let c1 = node(&mut g, Op::Const, vec![]);
9635            let r = node(&mut g, Op::Relu, vec![c1]);
9636            let s = node(&mut g, Op::Silu, vec![r]);
9637            let t = node(&mut g, Op::Tanh, vec![s]);
9638            let res = node(&mut g, Op::Add, vec![c1, t]);
9639            let branch = if control {
9640                let r2 = node(&mut g, Op::Relu, vec![c1]);
9641                let s2 = node(&mut g, Op::GeluTanh, vec![r2]);
9642                let t2 = node(&mut g, Op::Tanh, vec![s2]);
9643                let mut b = g.open_branch(c1);
9644                b.add_arm(t);
9645                b.add_arm(t2);
9646                b.finalize_branches(&mut g, res)
9647                    .expect("well-formed")
9648                    .expect("2 arms")
9649            } else {
9650                crate::region_pathfinder::record_branch(
9651                    &mut g,
9652                    c1,
9653                    res,
9654                    &[r, s, t],
9655                    t,
9656                    BackendId::Cpu,
9657                )
9658                .expect("the region records a 2-arm branch")
9659            };
9660            let mut inputs = StorageCache::new();
9661            inputs.insert(
9662                c1,
9663                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9664                    -1.0_f32, 0.5, 2.0,
9665                ]))),
9666            );
9667            (Arc::new(RwLock::new(g)), res, branch, inputs)
9668        };
9669
9670        drop(global_bindings());
9671        let run = |pick_arm1: bool| -> Vec<f32> {
9672            // Another test registering a backend or kernels bumps the process-wide topology generation
9673            // (`bump_topology_generation`, shared by every concurrently running test), and the executor
9674            // then returns `TopologyChanged` ("rebuild and retry") for a plan stamped before the bump.
9675            // Measured: 1 in ~55 full-suite runs at 17 threads, 6 in 110, every one the message
9676            // "generation N ... generation M"; it is not arm choice. Follow the error's own contract
9677            // with a bounded rebuild, and fail loudly on anything else or on 20 stale stamps in a row.
9678            for _attempt in 0..20 {
9679                let (graph, res, branch, inputs) = build();
9680                let opt = OptimizedGraph {
9681                    roots: vec![res],
9682                    generation: crate::dispatch::topology_generation(),
9683                    placements: None,
9684                    eviction: None,
9685                };
9686                let mut route = PickedRoute::new();
9687                if pick_arm1 {
9688                    route.insert(branch, 1);
9689                }
9690                match PipelinedExecutor::realize_with_optimized_route(
9691                    graph, res, inputs, &opt, &route,
9692                ) {
9693                    Ok((arc, _)) => return read(&arc),
9694                    Err(e) if format!("{e}").contains("topology generation") => continue,
9695                    Err(e) => panic!("realize: {e}"),
9696                }
9697            }
9698            panic!("realize: topology generation changed on 20 consecutive attempts")
9699        };
9700        (run(false), run(true))
9701    }
9702
9703    // ===== Row 158: chained region branches with a NON-ZERO arm chosen. The first real run of arm 1 on a
9704    //        GPU failed with "reshape input NodeId(2) of NodeId(3) not realized"; it reproduces on CPU
9705    //        and was a lowering-order bug (`fuel-graph/src/run.rs`): the chosen arm's run was emitted
9706    //        after the reconverge that reads it whenever two or more branches were chained. =====
9707
9708    /// `ids, table -> IndexSelect -> Reshape -> block*` where each block is the residual stretch
9709    /// `relu -> silu -> tanh -> add(x, .)` recorded as a 2-arm branch (arm 1 = the clone), so block `i`'s
9710    /// reconverge is block `i + 1`'s diverge (the shape of the toy Llama graph). Returns
9711    /// `(graph, root, branches, ids_const, table_const, head nodes)`.
9712    #[cfg(test)]
9713    fn head_then_region_chain(
9714        blocks: usize,
9715    ) -> (Graph, NodeId, Vec<NodeId>, NodeId, NodeId, Vec<NodeId>) {
9716        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>, dims: &[usize], dt: DType| {
9717            let id = g.push(Node {
9718                op,
9719                inputs,
9720                shape: Shape::from_dims(dims),
9721                dtype: dt,
9722            });
9723            g.set_target_backend(id, BackendId::Cpu);
9724            id
9725        };
9726        let mut g = Graph::new();
9727        let ids = node(&mut g, Op::Const, vec![], &[3], DType::U32);
9728        let table = node(&mut g, Op::Const, vec![], &[8, 4], DType::F32);
9729        let gathered = node(
9730            &mut g,
9731            Op::IndexSelect { dim: 0 },
9732            vec![table, ids],
9733            &[3, 4],
9734            DType::F32,
9735        );
9736        let mut x = node(
9737            &mut g,
9738            Op::Reshape(Shape::from_dims(&[1, 3, 4])),
9739            vec![gathered],
9740            &[1, 3, 4],
9741            DType::F32,
9742        );
9743        let head = vec![gathered, x];
9744        let mut branches = Vec::new();
9745        for _ in 0..blocks {
9746            let r = node(&mut g, Op::Relu, vec![x], &[1, 3, 4], DType::F32);
9747            let s = node(&mut g, Op::Silu, vec![r], &[1, 3, 4], DType::F32);
9748            let t = node(&mut g, Op::Tanh, vec![s], &[1, 3, 4], DType::F32);
9749            let res = node(&mut g, Op::Add, vec![x, t], &[1, 3, 4], DType::F32);
9750            let branch = crate::region_pathfinder::record_branch(
9751                &mut g,
9752                x,
9753                res,
9754                &[r, s, t],
9755                t,
9756                BackendId::Cpu,
9757            )
9758            .expect("the block records a 2-arm branch");
9759            branches.push(branch);
9760            x = res;
9761        }
9762        (g, x, branches, ids, table, head)
9763    }
9764
9765    /// The route that sends branch `i` to arm 1 iff bit `i` of `mask` is set.
9766    #[cfg(test)]
9767    fn route_from_mask(branches: &[NodeId], mask: usize) -> PickedRoute {
9768        let mut route = PickedRoute::new();
9769        for (i, &b) in branches.iter().enumerate() {
9770            if mask >> i & 1 == 1 {
9771                route.insert(b, 1);
9772            }
9773        }
9774        route
9775    }
9776
9777    /// Why `order` is not a valid dispatch order for the route `mask`, or `None` when it is. Valid: every
9778    /// emitted node's inputs are emitted earlier, are leaves, or are an arm-0 exit whose branch chose
9779    /// arm 1 and whose arm-1 exit was emitted earlier (the alias the compiler thread inserts); the chosen
9780    /// arm's exit is emitted and the other arm's is not.
9781    #[cfg(test)]
9782    fn why_invalid_order(
9783        g: &Graph,
9784        branches: &[NodeId],
9785        mask: usize,
9786        order: &[NodeId],
9787    ) -> Option<String> {
9788        let mut alias: HashMap<NodeId, NodeId> = HashMap::new();
9789        for (i, &b) in branches.iter().enumerate() {
9790            if mask >> i & 1 == 1 {
9791                alias.insert(g.node(b).inputs[0], g.node(b).inputs[1]);
9792            }
9793        }
9794        let mut emitted: HashSet<NodeId> = HashSet::new();
9795        for &n in order {
9796            for &inp in &g.node(n).inputs {
9797                let ok = emitted.contains(&inp)
9798                    || matches!(g.node(inp).op, Op::Const)
9799                    || alias.get(&inp).is_some_and(|a| emitted.contains(a));
9800                if !ok {
9801                    return Some(format!(
9802                        "node {n:?} ({:?}) is emitted before its input {inp:?} ({:?})",
9803                        g.node(n).op,
9804                        g.node(inp).op
9805                    ));
9806                }
9807            }
9808            emitted.insert(n);
9809        }
9810        for (i, &b) in branches.iter().enumerate() {
9811            let arms = &g.node(b).inputs;
9812            let (chosen, other) = if mask >> i & 1 == 1 {
9813                (arms[1], arms[0])
9814            } else {
9815                (arms[0], arms[1])
9816            };
9817            if !emitted.contains(&chosen) {
9818                return Some(format!(
9819                    "branch {i}: the chosen arm exit {chosen:?} is not emitted"
9820                ));
9821            }
9822            if emitted.contains(&other) {
9823                return Some(format!(
9824                    "branch {i}: the other arm exit {other:?} is emitted"
9825                ));
9826            }
9827        }
9828        None
9829    }
9830
9831    /// LOWERING level (no executor): for 1 to 4 chained branches and EVERY combination of arms (not only
9832    /// all arm 1), the frozen and the streaming lowering each emit a valid order, and the two orders are
9833    /// identical for the same picks. Before the fix N=1 passed and every N >= 2 with an arm 1 failed.
9834    #[test]
9835    fn chained_branches_lower_to_a_valid_order_for_every_combination_of_arms() {
9836        for blocks in 1..=4usize {
9837            let (g, root, branches, _ids, _table, head) = head_then_region_chain(blocks);
9838            for mask in 0..(1usize << blocks) {
9839                let route = route_from_mask(&branches, mask);
9840                let frozen = fuel_graph::lower_picked_route(&g, &[root], &route);
9841                let streaming = fuel_graph::lower_picked_route_streaming(&g, &[root], |b| {
9842                    route.get(&b).copied().unwrap_or(0)
9843                });
9844                for (name, order) in [("frozen", &frozen), ("streaming", &streaming)] {
9845                    assert_eq!(
9846                        why_invalid_order(&g, &branches, mask, order),
9847                        None,
9848                        "{name} lowering, blocks={blocks} mask={mask:#b}: order={order:?}"
9849                    );
9850                    assert!(
9851                        head.iter().all(|h| order.contains(h)),
9852                        "{name}, blocks={blocks} mask={mask:#b}: the head must be emitted"
9853                    );
9854                }
9855                assert_eq!(
9856                    frozen, streaming,
9857                    "blocks={blocks} mask={mask:#b}: frozen and streaming differ"
9858                );
9859            }
9860        }
9861    }
9862
9863    /// ROW 158: a chain of CROSS-DEVICE region branches. Block `i` is `e = relu(x); d = silu(e);
9864    /// a = add(d, e); t = tanh(a); res = add(d, t)`, the stretch `a, t` is recorded with its alternative on
9865    /// `Cuda { gpu_id: 0 }` (arm 1) and its exit brought back to the host, and the residency pass inserts
9866    /// the inbound copies of BOTH external inputs (`d` and `e`) of the clone. `res` is the next block's `x`.
9867    /// Returns `(graph, root, branches)`.
9868    #[cfg(test)]
9869    fn cross_device_chain(blocks: usize) -> (Graph, NodeId, Vec<NodeId>) {
9870        use crate::region_pathfinder::try_record_branch;
9871        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
9872        let mut g = Graph::new();
9873        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9874            let id = g.push(Node {
9875                op,
9876                inputs,
9877                shape: Shape::from_dims(&[4]),
9878                dtype: DType::F32,
9879            });
9880            g.set_placement(id, DeviceLocation::Cpu);
9881            g.set_target_backend(id, BackendId::Cpu);
9882            id
9883        };
9884        let mut x = node(&mut g, Op::Const, vec![]);
9885        let mut branches = Vec::new();
9886        for _ in 0..blocks {
9887            let e = node(&mut g, Op::Relu, vec![x]);
9888            let d = node(&mut g, Op::Silu, vec![e]);
9889            let a = node(&mut g, Op::Add, vec![d, e]);
9890            let t = node(&mut g, Op::Tanh, vec![a]);
9891            let res = node(&mut g, Op::Add, vec![d, t]);
9892            let branch = try_record_branch(
9893                &mut g,
9894                d,
9895                res,
9896                &[a, t],
9897                t,
9898                BackendId::Cuda,
9899                cuda0,
9900                DeviceLocation::Cpu,
9901            )
9902            .expect("well-formed branch")
9903            .expect("two arms");
9904            branches.push(branch);
9905            x = res;
9906        }
9907        crate::optimize::insert_residency_copies(
9908            &mut g,
9909            &[x],
9910            &crate::plan::ExecutionPlan::empty(),
9911            DeviceLocation::Cpu,
9912            None,
9913        );
9914        (g, x, branches)
9915    }
9916
9917    /// LOWERING level: the cross-device chain (inbound copies, exit copies, two external inputs per arm)
9918    /// lowers to a valid order for 1 to 4 blocks and EVERY combination of arms, frozen and streaming
9919    /// identical. Found on a GPU run: with the chosen arm's runs moved to the slot of the first run that
9920    /// opens an arm, an inbound `Copy` ran before the main-chain node it reads (`Copy input NodeId(130) of
9921    /// NodeId(255) not realized`).
9922    #[test]
9923    fn cross_device_chains_lower_to_a_valid_order_for_every_combination_of_arms() {
9924        for blocks in 1..=4usize {
9925            let (g, root, branches) = cross_device_chain(blocks);
9926            for mask in 0..(1usize << blocks) {
9927                let route = route_from_mask(&branches, mask);
9928                let frozen = fuel_graph::lower_picked_route(&g, &[root], &route);
9929                let streaming = fuel_graph::lower_picked_route_streaming(&g, &[root], |b| {
9930                    route.get(&b).copied().unwrap_or(0)
9931                });
9932                for (name, order) in [("frozen", &frozen), ("streaming", &streaming)] {
9933                    assert_eq!(
9934                        why_invalid_order(&g, &branches, mask, order),
9935                        None,
9936                        "{name} lowering, blocks={blocks} mask={mask:#b}: order={order:?}"
9937                    );
9938                }
9939                assert_eq!(
9940                    frozen, streaming,
9941                    "blocks={blocks} mask={mask:#b}: frozen and streaming differ"
9942                );
9943            }
9944        }
9945    }
9946
9947    /// A chain of cross-device region branches whose stretch reads a SHARED EARLY value `h` (computed once,
9948    /// before any diverge) as well as its diverge `d`: `fillers` nodes sit between the previous block and
9949    /// `d`, and `h` enters the stretch at its first node (`second_in_middle == false`) or its second.
9950    /// The residency pass inserts ONE inbound copy of `h` onto the alternative device and CSEs it between
9951    /// every block's arm 1, so that copy is in branch 1's arm 1 and in branch 2's arm 1 at once.
9952    #[cfg(test)]
9953    fn shared_early_input_chain(
9954        blocks: usize,
9955        fillers: usize,
9956        second_in_middle: bool,
9957    ) -> (Graph, NodeId, Vec<NodeId>) {
9958        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
9959        let mut g = Graph::new();
9960        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9961            let id = g.push(Node {
9962                op,
9963                inputs,
9964                shape: Shape::from_dims(&[4]),
9965                dtype: DType::F32,
9966            });
9967            g.set_placement(id, DeviceLocation::Cpu);
9968            g.set_target_backend(id, BackendId::Cpu);
9969            id
9970        };
9971        let c1 = node(&mut g, Op::Const, vec![]);
9972        // The early value: NOT downstream of any diverge, so it is outside every stretch.
9973        let h = node(&mut g, Op::Relu, vec![c1]);
9974        let mut x = node(&mut g, Op::Const, vec![]);
9975        let mut branches = Vec::new();
9976        for _ in 0..blocks {
9977            let mut d = x;
9978            for _ in 0..fillers {
9979                d = node(&mut g, Op::Silu, vec![d]);
9980            }
9981            let (a, t) = if second_in_middle {
9982                let s1 = node(&mut g, Op::Tanh, vec![d]);
9983                let s2 = node(&mut g, Op::Add, vec![s1, h]);
9984                (s1, s2)
9985            } else {
9986                let s1 = node(&mut g, Op::Add, vec![d, h]);
9987                let s2 = node(&mut g, Op::Tanh, vec![s1]);
9988                (s1, s2)
9989            };
9990            let res = node(&mut g, Op::Add, vec![d, t]);
9991            let branch = crate::region_pathfinder::try_record_branch(
9992                &mut g,
9993                d,
9994                res,
9995                &[a, t],
9996                t,
9997                BackendId::Cuda,
9998                cuda0,
9999                DeviceLocation::Cpu,
10000            )
10001            .expect("well-formed branch")
10002            .expect("two arms");
10003            branches.push(branch);
10004            x = res;
10005        }
10006
10007        crate::optimize::insert_residency_copies(
10008            &mut g,
10009            &[x],
10010            &crate::plan::ExecutionPlan::empty(),
10011            DeviceLocation::Cpu,
10012            None,
10013        );
10014        (g, x, branches)
10015    }
10016
10017    /// LOWERING level, 140 shapes (1 to 3 blocks x 0 to 4 fillers x both entry positions x EVERY
10018    /// combination of arms; the frozen and the streaming order may differ here, as they may on any multi-device
10019    /// graph, but BOTH must be valid): a shared inbound copy must run when ANY branch's chosen arm reads it, and the
10020    /// chosen arm's runs must come before the reconverge. Under the first-slot relocation with per-branch
10021    /// skip sets, 80 of the 140 (a node emitted before its input) were invalid; this is the CPU form of the
10022    /// GPU failures `Copy input NodeId(130) of NodeId(255) not realized` and `cpu kernel wrapper called
10023    /// with non-CPU input` (ROADMAP row 158).
10024    #[test]
10025    fn cross_device_chains_with_a_shared_early_input_lower_to_a_valid_order_for_every_combination_of_arms()
10026     {
10027        let mut shapes = 0;
10028        for blocks in 1..=3usize {
10029            for fillers in 0..=4usize {
10030                for second_in_middle in [false, true] {
10031                    let (g, root, branches) =
10032                        shared_early_input_chain(blocks, fillers, second_in_middle);
10033                    for mask in 0..(1usize << blocks) {
10034                        shapes += 1;
10035                        let route = route_from_mask(&branches, mask);
10036                        let frozen = fuel_graph::lower_picked_route(&g, &[root], &route);
10037                        let streaming =
10038                            fuel_graph::lower_picked_route_streaming(&g, &[root], |b| {
10039                                route.get(&b).copied().unwrap_or(0)
10040                            });
10041                        for (name, order) in [("frozen", &frozen), ("streaming", &streaming)] {
10042                            assert_eq!(
10043                                why_invalid_order(&g, &branches, mask, order),
10044                                None,
10045                                "{name} lowering, blocks={blocks} fillers={fillers} second_in_middle={second_in_middle} mask={mask:#b}: order={order:?}"
10046                            );
10047                        }
10048                    }
10049                }
10050            }
10051        }
10052        assert_eq!(shapes, 140, "the family size changed: re-pin it");
10053    }
10054
10055    /// A chain of cross-device region branches whose stretch reads EXTERNAL values besides its diverge.
10056    /// `ext[i]` is what block `i`'s stretch reads: 0 = the shared early value `h`, 1 = the value two blocks
10057    /// back (a skip connection), 2 = both. `entry` is the stretch node that reads them (0 = the first, 1 =
10058    /// the second); `fillers` nodes sit between the previous block and the diverge. The residency pass
10059    /// inserts one inbound copy per (value, device) and CSEs it between regions, so a copy can sit in
10060    /// several branches' arm 1 at once and its natural position in the base order is set by whichever
10061    /// branch reaches it first. Lowering only: the ops are structural (an `Add` may have three inputs).
10062    #[cfg(test)]
10063    fn pattern_chain(ext: &[u8], entry: usize, fillers: usize) -> (Graph, NodeId, Vec<NodeId>) {
10064        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
10065        let mut g = Graph::new();
10066        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
10067            let id = g.push(Node {
10068                op,
10069                inputs,
10070                shape: Shape::from_dims(&[4]),
10071                dtype: DType::F32,
10072            });
10073            g.set_placement(id, DeviceLocation::Cpu);
10074            g.set_target_backend(id, BackendId::Cpu);
10075            id
10076        };
10077        let c1 = node(&mut g, Op::Const, vec![]);
10078        let h = node(&mut g, Op::Relu, vec![c1]);
10079        let mut two_back = node(&mut g, Op::Const, vec![]);
10080        let mut x = node(&mut g, Op::Const, vec![]);
10081        let mut one_back = x;
10082        let mut branches = Vec::new();
10083        for &kind in ext {
10084            let mut d = x;
10085            for _ in 0..fillers {
10086                d = node(&mut g, Op::Silu, vec![d]);
10087            }
10088            let externals: Vec<NodeId> = match kind {
10089                0 => vec![h],
10090                1 => vec![two_back],
10091                _ => vec![h, two_back],
10092            };
10093            let (first, last) = if entry == 0 {
10094                let mut inputs = vec![d];
10095                inputs.extend(externals);
10096                let a = node(&mut g, Op::Add, inputs);
10097                let t = node(&mut g, Op::Tanh, vec![a]);
10098                (a, t)
10099            } else {
10100                let a = node(&mut g, Op::Tanh, vec![d]);
10101                let mut inputs = vec![a];
10102                inputs.extend(externals);
10103                let t = node(&mut g, Op::Add, inputs);
10104                (a, t)
10105            };
10106            let res = node(&mut g, Op::Add, vec![d, last]);
10107            let branch = crate::region_pathfinder::try_record_branch(
10108                &mut g,
10109                d,
10110                res,
10111                &[first, last],
10112                last,
10113                BackendId::Cuda,
10114                cuda0,
10115                DeviceLocation::Cpu,
10116            )
10117            .expect("well-formed branch")
10118            .expect("two arms");
10119            branches.push(branch);
10120            two_back = one_back;
10121            one_back = x;
10122            x = res;
10123        }
10124        crate::optimize::insert_residency_copies(
10125            &mut g,
10126            &[x],
10127            &crate::plan::ExecutionPlan::empty(),
10128            DeviceLocation::Cpu,
10129            None,
10130        );
10131        (g, x, branches)
10132    }
10133
10134    /// LOWERING level, 1548 (shape, arm combination) cases: 1 to 3 chained cross-device branches, every
10135    /// per-block external-input pattern (`h`, a skip connection, both), both entry positions, 0 to 2
10136    /// fillers, EVERY combination of arms; frozen and streaming lowering each valid. With the chosen arm's
10137    /// late runs moved to the FIRST arm slot, 644 checks failed with `Copy (onto Cuda) is emitted before
10138    /// its input`, the CPU form of the GPU failure `Copy input NodeId(130) of NodeId(255) not realized`:
10139    /// the first run opening an arm of the branch was an arm-1 inbound copy shared with another region and
10140    /// positioned early, and the other arm-1 runs were moved there, before the node they read.
10141    #[test]
10142    fn cross_device_chains_with_shared_and_skip_inputs_lower_to_a_valid_order_for_every_combination_of_arms()
10143     {
10144        let mut cases = 0;
10145        for blocks in 1..=3usize {
10146            for code in 0..3usize.pow(blocks as u32) {
10147                let ext: Vec<u8> = (0..blocks)
10148                    .map(|i| ((code / 3usize.pow(i as u32)) % 3) as u8)
10149                    .collect();
10150                for entry in 0..2usize {
10151                    for fillers in 0..=2usize {
10152                        let (g, root, branches) = pattern_chain(&ext, entry, fillers);
10153                        for mask in 0..(1usize << blocks) {
10154                            cases += 1;
10155                            let route = route_from_mask(&branches, mask);
10156                            let frozen = fuel_graph::lower_picked_route(&g, &[root], &route);
10157                            let streaming =
10158                                fuel_graph::lower_picked_route_streaming(&g, &[root], |b| {
10159                                    route.get(&b).copied().unwrap_or(0)
10160                                });
10161                            for (name, order) in [("frozen", &frozen), ("streaming", &streaming)] {
10162                                assert_eq!(
10163                                    why_invalid_order(&g, &branches, mask, order),
10164                                    None,
10165                                    "{name} lowering, ext={ext:?} entry={entry} fillers={fillers} mask={mask:#b}: order={order:?}"
10166                                );
10167                            }
10168                        }
10169                    }
10170                }
10171            }
10172        }
10173        assert_eq!(cases, 1548, "the family size changed: re-pin it");
10174    }
10175
10176    /// EXECUTOR level on CPU: the chain realized for every combination of arms (2 and 3 blocks, every
10177    /// mask, arm 1 = the clone on the same backend) equals arm 0. Before the fix any chain of two or more
10178    /// with an arm 1 failed with "input ... not realized".
10179    #[test]
10180    fn chained_branches_realize_equal_to_arm_zero_for_every_combination_of_arms_on_cpu() {
10181        use crate::optimize::OptimizedGraph;
10182        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
10183            match &arc.read().unwrap().inner {
10184                fuel_memory::BackendStorage::Cpu(c) => c.as_slice::<f32>().expect("f32").to_vec(),
10185                _ => panic!("expected CPU output"),
10186            }
10187        };
10188        drop(global_bindings());
10189        // Hold the generation still between building the stamp and realizing (ROADMAP row 165).
10190        let _gate = crate::dispatch::TOPOLOGY_TEST_GATE
10191            .write()
10192            .unwrap_or_else(|p| p.into_inner());
10193        let run = |blocks: usize, mask: usize| -> Vec<f32> {
10194            let (g, root, branches, ids, table, _head) = head_then_region_chain(blocks);
10195            let mut inputs = StorageCache::new();
10196            inputs.insert(
10197                ids,
10198                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[1_u32, 4, 6]))),
10199            );
10200            let table_vals: Vec<f32> = (0..32).map(|i| (i as f32 - 16.0) / 8.0).collect();
10201            inputs.insert(
10202                table,
10203                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&table_vals))),
10204            );
10205            let opt = OptimizedGraph {
10206                roots: vec![root],
10207                generation: crate::dispatch::topology_generation(),
10208                placements: None,
10209                eviction: None,
10210            };
10211            let route = route_from_mask(&branches, mask);
10212            let (arc, _) = PipelinedExecutor::realize_with_optimized_route(
10213                Arc::new(RwLock::new(g)),
10214                root,
10215                inputs,
10216                &opt,
10217                &route,
10218            )
10219            .unwrap_or_else(|e| panic!("realize (blocks={blocks}, mask={mask:#b}): {e}"));
10220            read(&arc)
10221        };
10222        for blocks in 1..=3usize {
10223            let arm0 = run(blocks, 0);
10224            assert_eq!(arm0.len(), 12);
10225            assert!(arm0.iter().all(|v| v.is_finite()));
10226            for mask in 1..(1usize << blocks) {
10227                assert_eq!(
10228                    run(blocks, mask),
10229                    arm0,
10230                    "blocks={blocks} mask={mask:#b}: a cloned stretch computes what arm 0 computes"
10231                );
10232            }
10233        }
10234    }
10235
10236    /// Realizing a node whose target_backend isn't set surfaces a
10237    /// typed error (no panic).
10238    #[test]
10239    fn pipelined_errors_on_unset_target_backend() {
10240        let graph = Arc::new(RwLock::new(Graph::new()));
10241        let (lhs_id, rhs_id, add_id) = {
10242            let mut g = graph.write().unwrap();
10243            let lhs = g.push(Node {
10244                op: Op::Const,
10245                inputs: vec![],
10246                shape: Shape::from_dims(&[2]),
10247                dtype: DType::F32,
10248            });
10249            let rhs = g.push(Node {
10250                op: Op::Const,
10251                inputs: vec![],
10252                shape: Shape::from_dims(&[2]),
10253                dtype: DType::F32,
10254            });
10255            // Deliberately do NOT call set_target_backend on the Add.
10256            let add = g.push(Node {
10257                op: Op::Add,
10258                inputs: vec![lhs, rhs],
10259                shape: Shape::from_dims(&[2]),
10260                dtype: DType::F32,
10261            });
10262            (lhs, rhs, add)
10263        };
10264
10265        let mut inputs = StorageCache::new();
10266        inputs.insert(
10267            lhs_id,
10268            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]))),
10269        );
10270        inputs.insert(
10271            rhs_id,
10272            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[3.0_f32, 4.0]))),
10273        );
10274
10275        let result = PipelinedExecutor::realize(graph, add_id, inputs);
10276        assert!(result.is_err(), "missing target_backend must error");
10277        let msg = result.unwrap_err().to_string();
10278        assert!(
10279            msg.contains("target_backend"),
10280            "error names the unmet precondition: {msg}"
10281        );
10282    }
10283
10284    /// Realizing a Const-only graph adopts the pre-seeded input
10285    /// without calling any kernel.
10286    #[test]
10287    fn pipelined_realize_const_only() {
10288        let storage = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0, 7.0]);
10289
10290        let graph = Arc::new(RwLock::new(Graph::new()));
10291        let const_id = {
10292            let mut g = graph.write().unwrap();
10293            g.push(Node {
10294                op: Op::Const,
10295                inputs: vec![],
10296                shape: Shape::from_dims(&[3]),
10297                dtype: DType::F32,
10298            })
10299        };
10300
10301        let mut inputs = StorageCache::new();
10302        inputs.insert(const_id, Arc::new(RwLock::new(storage)));
10303
10304        let (result_arc, _) =
10305            PipelinedExecutor::realize(graph, const_id, inputs).expect("realize const");
10306        let guard = result_arc.read().unwrap();
10307        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
10308            let typed: &[f32] = c.as_slice().unwrap();
10309            assert_eq!(typed, &[5.0, 6.0, 7.0]);
10310        }
10311    }
10312
10313    /// Missing input-cache entry for a Const surfaces a typed error.
10314    #[test]
10315    fn pipelined_errors_on_missing_const_input() {
10316        let graph = Arc::new(RwLock::new(Graph::new()));
10317        let const_id = {
10318            let mut g = graph.write().unwrap();
10319            g.push(Node {
10320                op: Op::Const,
10321                inputs: vec![],
10322                shape: Shape::from_dims(&[2]),
10323                dtype: DType::F32,
10324            })
10325        };
10326        // Deliberately empty input cache.
10327        let inputs = StorageCache::new();
10328        let result = PipelinedExecutor::realize(graph, const_id, inputs);
10329        assert!(result.is_err());
10330    }
10331
10332    /// E2E: 2-node graph (Const + Relu) — exercises the unary
10333    /// dispatch wrapper + kernel through the pipelined executor.
10334    #[test]
10335    fn pipelined_realize_const_relu() {
10336        let storage = fuel_memory::from_slice_cpu(&[-1.0_f32, 0.0, 0.5, -3.5, 7.25]);
10337        let graph = Arc::new(RwLock::new(Graph::new()));
10338        let (in_id, relu_id) = {
10339            let mut g = graph.write().unwrap();
10340            let in_id = g.push(Node {
10341                op: Op::Const,
10342                inputs: vec![],
10343                shape: Shape::from_dims(&[5]),
10344                dtype: DType::F32,
10345            });
10346            let relu_id = g.push(Node {
10347                op: Op::Relu,
10348                inputs: vec![in_id],
10349                shape: Shape::from_dims(&[5]),
10350                dtype: DType::F32,
10351            });
10352            g.set_target_backend(relu_id, BackendId::Cpu);
10353            (in_id, relu_id)
10354        };
10355        let mut inputs = StorageCache::new();
10356        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10357
10358        let (result_arc, _) = PipelinedExecutor::realize(graph, relu_id, inputs).expect("realize");
10359        let guard = result_arc.read().unwrap();
10360        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
10361            let typed: &[f32] = c.as_slice().expect("f32 cast");
10362            assert_eq!(typed, &[0.0, 0.0, 0.5, 0.0, 7.25]);
10363        }
10364    }
10365
10366    /// E2E: Const + Const + Sub + Mul + Div — exercises three more
10367    /// of the freshly-migrated binary kernels in one graph. Verifies
10368    /// that intermediates flow through the cache as expected.
10369    #[test]
10370    fn pipelined_realize_chained_binary_ops() {
10371        let a_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
10372        let b_storage = fuel_memory::from_slice_cpu(&[3.0_f32, 5.0]);
10373        let c_storage = fuel_memory::from_slice_cpu(&[2.0_f32, 4.0]);
10374
10375        let graph = Arc::new(RwLock::new(Graph::new()));
10376        let (a_id, b_id, c_id, sub_id, mul_id, div_id) = {
10377            let mut g = graph.write().unwrap();
10378            let a = g.push(Node {
10379                op: Op::Const,
10380                inputs: vec![],
10381                shape: Shape::from_dims(&[2]),
10382                dtype: DType::F32,
10383            });
10384            let b = g.push(Node {
10385                op: Op::Const,
10386                inputs: vec![],
10387                shape: Shape::from_dims(&[2]),
10388                dtype: DType::F32,
10389            });
10390            let c = g.push(Node {
10391                op: Op::Const,
10392                inputs: vec![],
10393                shape: Shape::from_dims(&[2]),
10394                dtype: DType::F32,
10395            });
10396            // (a - b)         = [7, 15]
10397            let sub = g.push(Node {
10398                op: Op::Sub,
10399                inputs: vec![a, b],
10400                shape: Shape::from_dims(&[2]),
10401                dtype: DType::F32,
10402            });
10403            // (a - b) * c     = [14, 60]
10404            let mul = g.push(Node {
10405                op: Op::Mul,
10406                inputs: vec![sub, c],
10407                shape: Shape::from_dims(&[2]),
10408                dtype: DType::F32,
10409            });
10410            // ((a-b)*c) / b   = [14/3, 12]
10411            let div = g.push(Node {
10412                op: Op::Div,
10413                inputs: vec![mul, b],
10414                shape: Shape::from_dims(&[2]),
10415                dtype: DType::F32,
10416            });
10417            g.set_target_backend(sub, BackendId::Cpu);
10418            g.set_target_backend(mul, BackendId::Cpu);
10419            g.set_target_backend(div, BackendId::Cpu);
10420            (a, b, c, sub, mul, div)
10421        };
10422
10423        let _ = (sub_id, mul_id);
10424        let mut inputs = StorageCache::new();
10425        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
10426        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
10427        inputs.insert(c_id, Arc::new(RwLock::new(c_storage)));
10428
10429        let (result_arc, _) = PipelinedExecutor::realize(graph, div_id, inputs).expect("realize");
10430        let guard = result_arc.read().unwrap();
10431        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
10432            let typed: &[f32] = c.as_slice().unwrap();
10433            assert!((typed[0] - (14.0_f32 / 3.0)).abs() < 1e-6);
10434            assert!((typed[1] - 12.0).abs() < 1e-6);
10435        }
10436    }
10437
10438    /// E2E: Const + Transpose — verifies metadata-only view ops
10439    /// share the input's Storage Arc and produce a strided Layout.
10440    /// Stage 3 of Layout-on-Node.
10441    #[test]
10442    fn pipelined_realize_transpose_is_metadata_only() {
10443        // shape [2, 3]; transpose → shape [3, 2], strided
10444        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
10445        let graph = Arc::new(RwLock::new(Graph::new()));
10446        let (in_id, t_id) = {
10447            let mut g = graph.write().unwrap();
10448            let in_id = g.push(Node {
10449                op: Op::Const,
10450                inputs: vec![],
10451                shape: Shape::from_dims(&[2, 3]),
10452                dtype: DType::F32,
10453            });
10454            let t_id = g.push(Node {
10455                op: Op::Transpose,
10456                inputs: vec![in_id],
10457                shape: Shape::from_dims(&[3, 2]),
10458                dtype: DType::F32,
10459            });
10460            // Note: NO set_target_backend — transpose is metadata-only
10461            // and doesn't run on a backend.
10462            (in_id, t_id)
10463        };
10464        let mut inputs = StorageCache::new();
10465        let in_arc = Arc::new(RwLock::new(storage));
10466        inputs.insert(in_id, Arc::clone(&in_arc));
10467
10468        let (result_arc, result_layout) =
10469            PipelinedExecutor::realize(graph, t_id, inputs).expect("realize");
10470
10471        // The output Storage Arc is the SAME Arc as the input —
10472        // metadata-only adoption shares bytes.
10473        assert!(
10474            Arc::ptr_eq(&result_arc, &in_arc),
10475            "transpose must share input bytes"
10476        );
10477
10478        // The output Layout is the transposed view.
10479        assert_eq!(result_layout.shape().dims(), &[3, 2]);
10480        assert_eq!(result_layout.stride(), &[1, 3]);
10481        assert!(!result_layout.is_contiguous());
10482    }
10483
10484    /// E2E: Const + Flip(dim=0) — verifies Op::Flip is metadata-only.
10485    /// The output Storage Arc must be the SAME Arc (no copy);
10486    /// the output Layout has a negated stride at dim 0 and a
10487    /// shifted start_offset.
10488    #[test]
10489    fn pipelined_realize_flip_is_metadata_only() {
10490        // shape [3, 4]; flip dim 0 → shape [3, 4], stride [-4, 1], offset 8.
10491        let data: Vec<f32> = (1..=12).map(|x| x as f32).collect();
10492        let storage = fuel_memory::from_slice_cpu(&data);
10493        let graph = Arc::new(RwLock::new(Graph::new()));
10494        let (in_id, f_id) = {
10495            let mut g = graph.write().unwrap();
10496            let in_id = g.push(Node {
10497                op: Op::Const,
10498                inputs: vec![],
10499                shape: Shape::from_dims(&[3, 4]),
10500                dtype: DType::F32,
10501            });
10502            let f_id = g.push(Node {
10503                op: Op::Flip { dim: 0 },
10504                inputs: vec![in_id],
10505                shape: Shape::from_dims(&[3, 4]),
10506                dtype: DType::F32,
10507            });
10508            (in_id, f_id)
10509        };
10510        let mut inputs = StorageCache::new();
10511        let in_arc = Arc::new(RwLock::new(storage));
10512        inputs.insert(in_id, Arc::clone(&in_arc));
10513
10514        let (result_arc, result_layout) =
10515            PipelinedExecutor::realize(graph, f_id, inputs).expect("realize");
10516
10517        assert!(
10518            Arc::ptr_eq(&result_arc, &in_arc),
10519            "flip must share input bytes"
10520        );
10521        assert_eq!(result_layout.shape().dims(), &[3, 4]);
10522        assert_eq!(result_layout.stride(), &[-4_isize, 1]);
10523        assert_eq!(result_layout.start_offset(), 8);
10524        assert!(!result_layout.is_contiguous());
10525    }
10526
10527    /// E2E: Const + Permute(rank-3 axes [2, 0, 1]) — verifies the
10528    /// general permute path through metadata-only adoption.
10529    #[test]
10530    fn pipelined_realize_permute_is_metadata_only() {
10531        // shape [2, 3, 4]; permute axes [2, 0, 1] → shape [4, 2, 3]
10532        let data: Vec<f32> = (1..=24).map(|x| x as f32).collect();
10533        let storage = fuel_memory::from_slice_cpu(&data);
10534        let graph = Arc::new(RwLock::new(Graph::new()));
10535        let (in_id, p_id) = {
10536            let mut g = graph.write().unwrap();
10537            let in_id = g.push(Node {
10538                op: Op::Const,
10539                inputs: vec![],
10540                shape: Shape::from_dims(&[2, 3, 4]),
10541                dtype: DType::F32,
10542            });
10543            let p_id = g.push(Node {
10544                op: Op::Permute(vec![2, 0, 1]),
10545                inputs: vec![in_id],
10546                shape: Shape::from_dims(&[4, 2, 3]),
10547                dtype: DType::F32,
10548            });
10549            (in_id, p_id)
10550        };
10551        let mut inputs = StorageCache::new();
10552        let in_arc = Arc::new(RwLock::new(storage));
10553        inputs.insert(in_id, Arc::clone(&in_arc));
10554
10555        let (result_arc, result_layout) =
10556            PipelinedExecutor::realize(graph, p_id, inputs).expect("realize");
10557
10558        assert!(Arc::ptr_eq(&result_arc, &in_arc));
10559        assert_eq!(result_layout.shape().dims(), &[4, 2, 3]);
10560        // Original strides for shape [2, 3, 4] are [12, 4, 1].
10561        // After permute axes [2, 0, 1]: [strides[2], strides[0], strides[1]] = [1, 12, 4].
10562        assert_eq!(result_layout.stride(), &[1, 12, 4]);
10563    }
10564
10565    /// E2E: Const + Cast(f32→f64) — verifies cast through the
10566    /// pipelined executor. Output Storage has the target dtype;
10567    /// bytes encode the widened values.
10568    #[test]
10569    fn pipelined_realize_cast_f32_to_f64() {
10570        let storage = fuel_memory::from_slice_cpu(&[1.5_f32, -2.25, 100.0]);
10571        let graph = Arc::new(RwLock::new(Graph::new()));
10572        let (in_id, c_id) = {
10573            let mut g = graph.write().unwrap();
10574            let in_id = g.push(Node {
10575                op: Op::Const,
10576                inputs: vec![],
10577                shape: Shape::from_dims(&[3]),
10578                dtype: DType::F32,
10579            });
10580            let c_id = g.push(Node {
10581                op: Op::Cast(DType::F64),
10582                inputs: vec![in_id],
10583                shape: Shape::from_dims(&[3]),
10584                dtype: DType::F64,
10585            });
10586            g.set_target_backend(c_id, BackendId::Cpu);
10587            (in_id, c_id)
10588        };
10589        let mut inputs = StorageCache::new();
10590        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10591
10592        let (result_arc, result_layout) =
10593            PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
10594        assert_eq!(result_layout.shape().dims(), &[3]);
10595
10596        let guard = result_arc.read().unwrap();
10597        assert_eq!(guard.dtype, DType::F64);
10598        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10599            panic!("expected Cpu storage");
10600        };
10601        assert_eq!(c.as_slice::<f64>().unwrap(), &[1.5_f64, -2.25, 100.0]);
10602    }
10603
10604    /// E2E: Const + Cast(f32→bf16) + Cast(bf16→f32) — round trip
10605    /// through bf16; verifies the Cast wrapper's source-dtype
10606    /// dispatch (different sources hit different match arms).
10607    /// Inputs chosen to round-trip exactly through bf16.
10608    #[test]
10609    fn pipelined_realize_cast_round_trip_via_bf16() {
10610        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, -3.0, 0.5]);
10611        let graph = Arc::new(RwLock::new(Graph::new()));
10612        let (in_id, c1_id, c2_id) = {
10613            let mut g = graph.write().unwrap();
10614            let in_id = g.push(Node {
10615                op: Op::Const,
10616                inputs: vec![],
10617                shape: Shape::from_dims(&[4]),
10618                dtype: DType::F32,
10619            });
10620            let c1_id = g.push(Node {
10621                op: Op::Cast(DType::BF16),
10622                inputs: vec![in_id],
10623                shape: Shape::from_dims(&[4]),
10624                dtype: DType::BF16,
10625            });
10626            let c2_id = g.push(Node {
10627                op: Op::Cast(DType::F32),
10628                inputs: vec![c1_id],
10629                shape: Shape::from_dims(&[4]),
10630                dtype: DType::F32,
10631            });
10632            g.set_target_backend(c1_id, BackendId::Cpu);
10633            g.set_target_backend(c2_id, BackendId::Cpu);
10634            (in_id, c1_id, c2_id)
10635        };
10636        let _ = c1_id;
10637        let mut inputs = StorageCache::new();
10638        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10639
10640        let (result_arc, _) = PipelinedExecutor::realize(graph, c2_id, inputs).expect("realize");
10641        let guard = result_arc.read().unwrap();
10642        assert_eq!(guard.dtype, DType::F32);
10643        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10644            panic!("expected Cpu storage");
10645        };
10646        assert_eq!(c.as_slice::<f32>().unwrap(), &[1.0_f32, 2.0, -3.0, 0.5]);
10647    }
10648
10649    /// E2E: Const + Slice — slice is metadata-only; the output Arc
10650    /// shares bytes with the input, and the Layout's start_offset
10651    /// + narrowed shape reflect the slice. Stage 3 of Layout-on-Node
10652    ///
10653    /// extended to cover Op::Slice via Layout::narrow.
10654    #[test]
10655    fn pipelined_realize_slice_is_metadata_only() {
10656        // shape [5]; slice dim 0 from index 1 with len 3 → shape [3]
10657        // Source: [10, 20, 30, 40, 50]; slice → [20, 30, 40]
10658        let storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0]);
10659        let graph = Arc::new(RwLock::new(Graph::new()));
10660        let (in_id, s_id) = {
10661            let mut g = graph.write().unwrap();
10662            let in_id = g.push(Node {
10663                op: Op::Const,
10664                inputs: vec![],
10665                shape: Shape::from_dims(&[5]),
10666                dtype: DType::F32,
10667            });
10668            let s_id = g.push(Node {
10669                op: Op::Slice {
10670                    dim: 0,
10671                    start: 1,
10672                    len: 3,
10673                },
10674                inputs: vec![in_id],
10675                shape: Shape::from_dims(&[3]),
10676                dtype: DType::F32,
10677            });
10678            (in_id, s_id)
10679        };
10680        let mut inputs = StorageCache::new();
10681        let in_arc = Arc::new(RwLock::new(storage));
10682        inputs.insert(in_id, Arc::clone(&in_arc));
10683
10684        let (result_arc, result_layout) =
10685            PipelinedExecutor::realize(graph, s_id, inputs).expect("realize");
10686
10687        // Bytes shared with the input.
10688        assert!(Arc::ptr_eq(&result_arc, &in_arc));
10689        assert_eq!(result_layout.shape().dims(), &[3]);
10690        // Slice into a contiguous source: the resulting layout has
10691        // start_offset = original_stride[0] * start = 1 * 1 = 1,
10692        // and stride [1] (still contiguous within the narrowed dim).
10693        assert_eq!(result_layout.start_offset(), 1);
10694        assert_eq!(result_layout.stride(), &[1]);
10695    }
10696
10697    /// E2E: Const + Slice + SumAll — slice is metadata-only, but
10698    /// sum needs contiguous bytes, so auto-Contiguize materializes
10699    /// the slice before reduce. Tests the stage 3+4 integration
10700    /// through Op::Slice. Sum of `[20, 30, 40]` is 90.
10701    #[test]
10702    fn pipelined_realize_slice_then_sum_all() {
10703        let storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0]);
10704        let graph = Arc::new(RwLock::new(Graph::new()));
10705        let (in_id, s_id, sum_id) = {
10706            let mut g = graph.write().unwrap();
10707            let in_id = g.push(Node {
10708                op: Op::Const,
10709                inputs: vec![],
10710                shape: Shape::from_dims(&[5]),
10711                dtype: DType::F32,
10712            });
10713            let s_id = g.push(Node {
10714                op: Op::Slice {
10715                    dim: 0,
10716                    start: 1,
10717                    len: 3,
10718                },
10719                inputs: vec![in_id],
10720                shape: Shape::from_dims(&[3]),
10721                dtype: DType::F32,
10722            });
10723            let sum_id = g.push(Node {
10724                op: Op::SumAll,
10725                inputs: vec![s_id],
10726                shape: Shape::from_dims(&[]),
10727                dtype: DType::F32,
10728            });
10729            g.set_target_backend(sum_id, BackendId::Cpu);
10730            (in_id, s_id, sum_id)
10731        };
10732        let _ = s_id;
10733        let mut inputs = StorageCache::new();
10734        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10735
10736        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
10737        let guard = result_arc.read().unwrap();
10738        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10739            panic!("expected Cpu storage");
10740        };
10741        assert_eq!(c.as_slice::<f32>().unwrap(), &[90.0]);
10742    }
10743
10744    /// E2E: Const + Flip + ReluElementwise — Flip is metadata-only,
10745    /// then a kernel that doesn't yet handle negative strides forces
10746    /// auto-Contiguize to materialize through StridedIndex (which
10747    /// handles signed strides natively). Verifies the post-flip
10748    /// data ordering ([4, 3, 2, 1]) is correctly seen by the kernel.
10749    #[test]
10750    fn pipelined_realize_flip_then_relu_materializes_in_reverse() {
10751        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
10752        let graph = Arc::new(RwLock::new(Graph::new()));
10753        let (in_id, _f_id, r_id) = {
10754            let mut g = graph.write().unwrap();
10755            let in_id = g.push(Node {
10756                op: Op::Const,
10757                inputs: vec![],
10758                shape: Shape::from_dims(&[4]),
10759                dtype: DType::F32,
10760            });
10761            let f_id = g.push(Node {
10762                op: Op::Flip { dim: 0 },
10763                inputs: vec![in_id],
10764                shape: Shape::from_dims(&[4]),
10765                dtype: DType::F32,
10766            });
10767            let r_id = g.push(Node {
10768                op: Op::Relu,
10769                inputs: vec![f_id],
10770                shape: Shape::from_dims(&[4]),
10771                dtype: DType::F32,
10772            });
10773            g.set_target_backend(r_id, BackendId::Cpu);
10774            (in_id, f_id, r_id)
10775        };
10776        let mut inputs = StorageCache::new();
10777        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10778
10779        let (result_arc, result_layout) =
10780            PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
10781        let guard = result_arc.read().unwrap();
10782        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10783            panic!("expected Cpu storage");
10784        };
10785        assert_eq!(c.as_slice::<f32>().unwrap(), &[4.0, 3.0, 2.0, 1.0]);
10786        assert_eq!(result_layout.shape().dims(), &[4]);
10787        assert!(result_layout.is_contiguous(), "relu output is contiguous");
10788    }
10789
10790    /// E2E: Const + BroadcastTo — verifies that broadcast layouts
10791    /// have stride 0 on the broadcast dim while sharing the input's
10792    /// bytes. Stage 3 of Layout-on-Node.
10793    #[test]
10794    fn pipelined_realize_broadcast_is_metadata_only() {
10795        // shape [3]; broadcast to [4, 3] — leading dim is 0-stride
10796        let storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
10797        let graph = Arc::new(RwLock::new(Graph::new()));
10798        let (in_id, b_id) = {
10799            let mut g = graph.write().unwrap();
10800            let in_id = g.push(Node {
10801                op: Op::Const,
10802                inputs: vec![],
10803                shape: Shape::from_dims(&[3]),
10804                dtype: DType::F32,
10805            });
10806            let b_id = g.push(Node {
10807                op: Op::BroadcastTo(Shape::from_dims(&[4, 3])),
10808                inputs: vec![in_id],
10809                shape: Shape::from_dims(&[4, 3]),
10810                dtype: DType::F32,
10811            });
10812            (in_id, b_id)
10813        };
10814        let mut inputs = StorageCache::new();
10815        let in_arc = Arc::new(RwLock::new(storage));
10816        inputs.insert(in_id, Arc::clone(&in_arc));
10817
10818        let (result_arc, result_layout) =
10819            PipelinedExecutor::realize(graph, b_id, inputs).expect("realize");
10820
10821        assert!(Arc::ptr_eq(&result_arc, &in_arc));
10822        assert_eq!(result_layout.shape().dims(), &[4, 3]);
10823        // Broadcasted leading dim has stride 0.
10824        assert_eq!(result_layout.stride(), &[0, 1]);
10825    }
10826
10827    /// E2E: Const + Const + MatMul — exercises rank-2 matmul
10828    /// through the pipelined executor. Inputs are contiguous (no
10829    /// auto-Contiguize needed); the kernel walks them via the
10830    /// (m, n, k) carried in OpParams::Matmul.
10831    #[test]
10832    fn pipelined_realize_matmul_2x3_times_3x2() {
10833        // [[1, 2, 3], [4, 5, 6]] @ [[7, 8], [9, 10], [11, 12]]
10834        //   = [[58, 64], [139, 154]]
10835        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
10836        let rhs_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0, 9.0, 10.0, 11.0, 12.0]);
10837
10838        let graph = Arc::new(RwLock::new(Graph::new()));
10839        let (lhs_id, rhs_id, mm_id) = {
10840            let mut g = graph.write().unwrap();
10841            let lhs = g.push(Node {
10842                op: Op::Const,
10843                inputs: vec![],
10844                shape: Shape::from_dims(&[2, 3]),
10845                dtype: DType::F32,
10846            });
10847            let rhs = g.push(Node {
10848                op: Op::Const,
10849                inputs: vec![],
10850                shape: Shape::from_dims(&[3, 2]),
10851                dtype: DType::F32,
10852            });
10853            let mm = g.push(Node {
10854                op: Op::MatMul,
10855                inputs: vec![lhs, rhs],
10856                shape: Shape::from_dims(&[2, 2]),
10857                dtype: DType::F32,
10858            });
10859            g.set_target_backend(mm, BackendId::Cpu);
10860            (lhs, rhs, mm)
10861        };
10862        let mut inputs = StorageCache::new();
10863        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
10864        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
10865
10866        let (result_arc, result_layout) =
10867            PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
10868        assert_eq!(result_layout.shape().dims(), &[2, 2]);
10869        assert!(result_layout.is_contiguous());
10870
10871        let guard = result_arc.read().unwrap();
10872        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10873            panic!("expected Cpu storage");
10874        };
10875        assert_eq!(c.as_slice::<f32>().unwrap(), &[58.0, 64.0, 139.0, 154.0]);
10876    }
10877
10878    /// E2E: batched matmul through the pipelined executor. Two
10879    /// batches of [2, 2] @ [2, 2]; the kernel iterates over
10880    /// `batch_count` and produces concatenated outputs.
10881    #[test]
10882    fn pipelined_realize_matmul_batched_2x_2x2_times_2x2() {
10883        let lhs_storage = fuel_memory::from_slice_cpu(&[
10884            1.0_f32, 2.0, 3.0, 4.0, // batch 0
10885            1.0, 0.0, 0.0, 1.0, // batch 1 (identity)
10886        ]);
10887        let rhs_storage = fuel_memory::from_slice_cpu(&[
10888            5.0_f32, 6.0, 7.0, 8.0, // batch 0
10889            10.0, 20.0, 30.0, 40.0, // batch 1
10890        ]);
10891
10892        let graph = Arc::new(RwLock::new(Graph::new()));
10893        let (lhs_id, rhs_id, mm_id) = {
10894            let mut g = graph.write().unwrap();
10895            let lhs = g.push(Node {
10896                op: Op::Const,
10897                inputs: vec![],
10898                shape: Shape::from_dims(&[2, 2, 2]),
10899                dtype: DType::F32,
10900            });
10901            let rhs = g.push(Node {
10902                op: Op::Const,
10903                inputs: vec![],
10904                shape: Shape::from_dims(&[2, 2, 2]),
10905                dtype: DType::F32,
10906            });
10907            let mm = g.push(Node {
10908                op: Op::MatMul,
10909                inputs: vec![lhs, rhs],
10910                shape: Shape::from_dims(&[2, 2, 2]),
10911                dtype: DType::F32,
10912            });
10913            g.set_target_backend(mm, BackendId::Cpu);
10914            (lhs, rhs, mm)
10915        };
10916        let mut inputs = StorageCache::new();
10917        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
10918        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
10919
10920        let (result_arc, result_layout) =
10921            PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
10922        assert_eq!(result_layout.shape().dims(), &[2, 2, 2]);
10923        assert!(result_layout.is_contiguous());
10924
10925        let guard = result_arc.read().unwrap();
10926        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10927            panic!("expected Cpu storage");
10928        };
10929        // batch 0: [[1,2],[3,4]] @ [[5,6],[7,8]] = [[19,22],[43,50]]
10930        // batch 1: identity @ [[10,20],[30,40]]   = [[10,20],[30,40]]
10931        assert_eq!(
10932            c.as_slice::<f32>().unwrap(),
10933            &[19.0, 22.0, 43.0, 50.0, 10.0, 20.0, 30.0, 40.0]
10934        );
10935    }
10936
10937    /// E2E: F64 elementwise add through the pipelined executor.
10938    /// Verifies that capability-driven dispatch correctly routes
10939    /// (AddElementwise, F64) to the f64 wrapper/kernel.
10940    #[test]
10941    fn pipelined_realize_add_f64() {
10942        let lhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0]);
10943        let rhs = fuel_memory::from_slice_cpu(&[10.0_f64, 20.0, 30.0]);
10944        let graph = Arc::new(RwLock::new(Graph::new()));
10945        let (l_id, r_id, op_id) = {
10946            let mut g = graph.write().unwrap();
10947            let l = g.push(Node {
10948                op: Op::Const,
10949                inputs: vec![],
10950                shape: Shape::from_dims(&[3]),
10951                dtype: DType::F64,
10952            });
10953            let r = g.push(Node {
10954                op: Op::Const,
10955                inputs: vec![],
10956                shape: Shape::from_dims(&[3]),
10957                dtype: DType::F64,
10958            });
10959            let op = g.push(Node {
10960                op: Op::Add,
10961                inputs: vec![l, r],
10962                shape: Shape::from_dims(&[3]),
10963                dtype: DType::F64,
10964            });
10965            g.set_target_backend(op, BackendId::Cpu);
10966            (l, r, op)
10967        };
10968        let mut inputs = StorageCache::new();
10969        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10970        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10971        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
10972        let guard = result_arc.read().unwrap();
10973        assert_eq!(guard.dtype, DType::F64);
10974        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10975            panic!("expected Cpu storage");
10976        };
10977        assert_eq!(c.as_slice::<f64>().unwrap(), &[11.0_f64, 22.0, 33.0]);
10978    }
10979
10980    /// E2E: Op::Equal F32 → Bool mask through the pipelined executor (GAP-168c).
10981    /// Verifies (a) the binding-table key `(EqualElementwise, [F32, F32, U8],
10982    /// Cpu)` resolves, (b) the executor allocates a U8-sized output
10983    /// buffer (1 byte per element, not 4), (c) the kernel writes the
10984    /// expected mask bits including IEEE-754 NaN handling
10985    /// (`NaN == NaN` is false).
10986    #[test]
10987    fn pipelined_realize_eq_f32_to_bool_mask() {
10988        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, f32::NAN, 0.0]);
10989        let rhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -0.0]);
10990        let graph = Arc::new(RwLock::new(Graph::new()));
10991        let (l_id, r_id, eq_id) = {
10992            let mut g = graph.write().unwrap();
10993            let l = g.push(Node {
10994                op: Op::Const,
10995                inputs: vec![],
10996                shape: Shape::from_dims(&[5]),
10997                dtype: DType::F32,
10998            });
10999            let r = g.push(Node {
11000                op: Op::Const,
11001                inputs: vec![],
11002                shape: Shape::from_dims(&[5]),
11003                dtype: DType::F32,
11004            });
11005            let eq = g.push(Node {
11006                op: Op::Equal,
11007                inputs: vec![l, r],
11008                shape: Shape::from_dims(&[5]),
11009                dtype: DType::Bool,
11010            });
11011            g.set_target_backend(eq, BackendId::Cpu);
11012            (l, r, eq)
11013        };
11014        let mut inputs = StorageCache::new();
11015        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11016        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11017        let (result_arc, _) = PipelinedExecutor::realize(graph, eq_id, inputs).expect("realize");
11018        let guard = result_arc.read().unwrap();
11019        assert_eq!(guard.dtype, DType::Bool);
11020        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11021            panic!("expected Cpu storage");
11022        };
11023        let mask: &[u8] = c.as_slice().expect("u8 view");
11024        // Index 0: 1.0 == 1.0 → 1.
11025        // Index 1: 2.0 != 5.0 → 0.
11026        // Index 2: 3.0 == 3.0 → 1.
11027        // Index 3: NaN == NaN → 0 (IEEE-754).
11028        // Index 4: 0.0 == -0.0 → 1 (IEEE-754 zero equality).
11029        assert_eq!(mask, &[1, 0, 1, 0, 1]);
11030    }
11031
11032    /// E2E: Op::Ne F32 → Bool mask. Mirrors the Eq F32 test with
11033    /// inverted predicate; NaN-vs-NaN slot now yields `1` (since
11034    /// `NaN != NaN` per IEEE-754).
11035    #[test]
11036    fn pipelined_realize_ne_f32_to_bool_mask() {
11037        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, f32::NAN, 0.0]);
11038        let rhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -0.0]);
11039        let graph = Arc::new(RwLock::new(Graph::new()));
11040        let (l_id, r_id, ne_id) = {
11041            let mut g = graph.write().unwrap();
11042            let l = g.push(Node {
11043                op: Op::Const,
11044                inputs: vec![],
11045                shape: Shape::from_dims(&[5]),
11046                dtype: DType::F32,
11047            });
11048            let r = g.push(Node {
11049                op: Op::Const,
11050                inputs: vec![],
11051                shape: Shape::from_dims(&[5]),
11052                dtype: DType::F32,
11053            });
11054            let ne = g.push(Node {
11055                op: Op::Ne,
11056                inputs: vec![l, r],
11057                shape: Shape::from_dims(&[5]),
11058                dtype: DType::Bool,
11059            });
11060            g.set_target_backend(ne, BackendId::Cpu);
11061            (l, r, ne)
11062        };
11063        let mut inputs = StorageCache::new();
11064        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11065        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11066        let (result_arc, _) = PipelinedExecutor::realize(graph, ne_id, inputs).expect("realize");
11067        let guard = result_arc.read().unwrap();
11068        assert_eq!(guard.dtype, DType::Bool);
11069        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11070            panic!("expected Cpu storage");
11071        };
11072        let mask: &[u8] = c.as_slice().expect("u8 view");
11073        // Inverse of the Eq test:
11074        // 1.0 != 1.0 → 0;  2.0 != 5.0 → 1;  3.0 != 3.0 → 0;
11075        // NaN != NaN → 1 (IEEE-754);  0.0 != -0.0 → 0 (IEEE-754).
11076        assert_eq!(mask, &[0, 1, 0, 1, 0]);
11077    }
11078
11079    /// E2E: Op::Lt F32 → Bool mask. Confirms strict-less-than semantics
11080    /// + IEEE-754 NaN handling (any comparison with NaN is unordered →
11081    ///
11082    /// `0`).
11083    #[test]
11084    fn pipelined_realize_lt_f32_to_bool_mask() {
11085        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -1.0]);
11086        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 3.0, 0.0, 0.0]);
11087        let graph = Arc::new(RwLock::new(Graph::new()));
11088        let (l_id, r_id, lt_id) = {
11089            let mut g = graph.write().unwrap();
11090            let l = g.push(Node {
11091                op: Op::Const,
11092                inputs: vec![],
11093                shape: Shape::from_dims(&[5]),
11094                dtype: DType::F32,
11095            });
11096            let r = g.push(Node {
11097                op: Op::Const,
11098                inputs: vec![],
11099                shape: Shape::from_dims(&[5]),
11100                dtype: DType::F32,
11101            });
11102            let lt = g.push(Node {
11103                op: Op::Lt,
11104                inputs: vec![l, r],
11105                shape: Shape::from_dims(&[5]),
11106                dtype: DType::Bool,
11107            });
11108            g.set_target_backend(lt, BackendId::Cpu);
11109            (l, r, lt)
11110        };
11111        let mut inputs = StorageCache::new();
11112        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11113        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11114        let (result_arc, _) = PipelinedExecutor::realize(graph, lt_id, inputs).expect("realize");
11115        let guard = result_arc.read().unwrap();
11116        assert_eq!(guard.dtype, DType::Bool);
11117        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11118            panic!("expected Cpu storage");
11119        };
11120        let mask: &[u8] = c.as_slice().expect("u8 view");
11121        // 1.0 < 2.0 → 1;  5.0 < 5.0 → 0 (strict);  3.0 < 3.0 → 0;
11122        // NaN < 0.0 → 0 (unordered);  -1.0 < 0.0 → 1.
11123        assert_eq!(mask, &[1, 0, 0, 0, 1]);
11124    }
11125
11126    /// E2E: Op::Le F32 → Bool mask. Distinct from Lt at the equal slot
11127    /// (`5.0 <= 5.0` = 1, vs Lt's `5.0 < 5.0` = 0). NaN unordered → 0.
11128    #[test]
11129    fn pipelined_realize_le_f32_to_bool_mask() {
11130        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -1.0]);
11131        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 2.0, 0.0, 0.0]);
11132        let graph = Arc::new(RwLock::new(Graph::new()));
11133        let (l_id, r_id, le_id) = {
11134            let mut g = graph.write().unwrap();
11135            let l = g.push(Node {
11136                op: Op::Const,
11137                inputs: vec![],
11138                shape: Shape::from_dims(&[5]),
11139                dtype: DType::F32,
11140            });
11141            let r = g.push(Node {
11142                op: Op::Const,
11143                inputs: vec![],
11144                shape: Shape::from_dims(&[5]),
11145                dtype: DType::F32,
11146            });
11147            let le = g.push(Node {
11148                op: Op::Le,
11149                inputs: vec![l, r],
11150                shape: Shape::from_dims(&[5]),
11151                dtype: DType::Bool,
11152            });
11153            g.set_target_backend(le, BackendId::Cpu);
11154            (l, r, le)
11155        };
11156        let mut inputs = StorageCache::new();
11157        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11158        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11159        let (result_arc, _) = PipelinedExecutor::realize(graph, le_id, inputs).expect("realize");
11160        let guard = result_arc.read().unwrap();
11161        assert_eq!(guard.dtype, DType::Bool);
11162        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11163            panic!("expected Cpu storage");
11164        };
11165        let mask: &[u8] = c.as_slice().expect("u8 view");
11166        // 1.0 <= 2.0 → 1;  5.0 <= 5.0 → 1 (key Lt difference);
11167        // 3.0 <= 2.0 → 0;  NaN <= 0.0 → 0 (unordered);  -1.0 <= 0.0 → 1.
11168        assert_eq!(mask, &[1, 1, 0, 0, 1]);
11169    }
11170
11171    /// E2E: Op::Gt F32 → Bool mask. Strict-greater: equality slot is
11172    /// `0`. NaN unordered → `0`.
11173    #[test]
11174    fn pipelined_realize_gt_f32_to_bool_mask() {
11175        let lhs = fuel_memory::from_slice_cpu(&[3.0_f32, 5.0, 2.0, f32::NAN, 1.0]);
11176        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 3.0, 0.0, 0.0]);
11177        let graph = Arc::new(RwLock::new(Graph::new()));
11178        let (l_id, r_id, gt_id) = {
11179            let mut g = graph.write().unwrap();
11180            let l = g.push(Node {
11181                op: Op::Const,
11182                inputs: vec![],
11183                shape: Shape::from_dims(&[5]),
11184                dtype: DType::F32,
11185            });
11186            let r = g.push(Node {
11187                op: Op::Const,
11188                inputs: vec![],
11189                shape: Shape::from_dims(&[5]),
11190                dtype: DType::F32,
11191            });
11192            let gt = g.push(Node {
11193                op: Op::Gt,
11194                inputs: vec![l, r],
11195                shape: Shape::from_dims(&[5]),
11196                dtype: DType::Bool,
11197            });
11198            g.set_target_backend(gt, BackendId::Cpu);
11199            (l, r, gt)
11200        };
11201        let mut inputs = StorageCache::new();
11202        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11203        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11204        let (result_arc, _) = PipelinedExecutor::realize(graph, gt_id, inputs).expect("realize");
11205        let guard = result_arc.read().unwrap();
11206        assert_eq!(guard.dtype, DType::Bool);
11207        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11208            panic!("expected Cpu storage");
11209        };
11210        let mask: &[u8] = c.as_slice().expect("u8 view");
11211        // 3.0 > 2.0 → 1;  5.0 > 5.0 → 0 (strict);  2.0 > 3.0 → 0;
11212        // NaN > 0.0 → 0 (unordered);  1.0 > 0.0 → 1.
11213        assert_eq!(mask, &[1, 0, 0, 0, 1]);
11214    }
11215
11216    /// E2E: Op::Ge F32 → Bool mask. Greater-or-equal: equality slot
11217    /// is `1` (distinguishes from Gt). NaN unordered → `0`. Closes
11218    /// the comparison family with full `[Eq, Ne, Lt, Le, Gt, Ge]`
11219    /// coverage.
11220    #[test]
11221    fn pipelined_realize_ge_f32_to_bool_mask() {
11222        let lhs = fuel_memory::from_slice_cpu(&[3.0_f32, 5.0, 2.0, f32::NAN, 0.0]);
11223        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 3.0, 0.0, 0.0]);
11224        let graph = Arc::new(RwLock::new(Graph::new()));
11225        let (l_id, r_id, ge_id) = {
11226            let mut g = graph.write().unwrap();
11227            let l = g.push(Node {
11228                op: Op::Const,
11229                inputs: vec![],
11230                shape: Shape::from_dims(&[5]),
11231                dtype: DType::F32,
11232            });
11233            let r = g.push(Node {
11234                op: Op::Const,
11235                inputs: vec![],
11236                shape: Shape::from_dims(&[5]),
11237                dtype: DType::F32,
11238            });
11239            let ge = g.push(Node {
11240                op: Op::Ge,
11241                inputs: vec![l, r],
11242                shape: Shape::from_dims(&[5]),
11243                dtype: DType::Bool,
11244            });
11245            g.set_target_backend(ge, BackendId::Cpu);
11246            (l, r, ge)
11247        };
11248        let mut inputs = StorageCache::new();
11249        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11250        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11251        let (result_arc, _) = PipelinedExecutor::realize(graph, ge_id, inputs).expect("realize");
11252        let guard = result_arc.read().unwrap();
11253        assert_eq!(guard.dtype, DType::Bool);
11254        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11255            panic!("expected Cpu storage");
11256        };
11257        let mask: &[u8] = c.as_slice().expect("u8 view");
11258        // 3.0 >= 2.0 → 1;  5.0 >= 5.0 → 1 (key Gt difference);
11259        // 2.0 >= 3.0 → 0;  NaN >= 0.0 → 0 (unordered);  0.0 >= 0.0 → 1.
11260        assert_eq!(mask, &[1, 1, 0, 0, 1]);
11261    }
11262
11263    /// E2E: Op::Equal F64 → Bool mask. Confirms the F64 wrapper is
11264    /// independently registered and routed (binding-table key
11265    /// `(EqualElementwise, [F64, F64, U8], Cpu)`).
11266    #[test]
11267    fn pipelined_realize_eq_f64_to_bool_mask() {
11268        let lhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0]);
11269        let rhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 4.0]);
11270        let graph = Arc::new(RwLock::new(Graph::new()));
11271        let (l_id, r_id, eq_id) = {
11272            let mut g = graph.write().unwrap();
11273            let l = g.push(Node {
11274                op: Op::Const,
11275                inputs: vec![],
11276                shape: Shape::from_dims(&[3]),
11277                dtype: DType::F64,
11278            });
11279            let r = g.push(Node {
11280                op: Op::Const,
11281                inputs: vec![],
11282                shape: Shape::from_dims(&[3]),
11283                dtype: DType::F64,
11284            });
11285            let eq = g.push(Node {
11286                op: Op::Equal,
11287                inputs: vec![l, r],
11288                shape: Shape::from_dims(&[3]),
11289                dtype: DType::Bool,
11290            });
11291            g.set_target_backend(eq, BackendId::Cpu);
11292            (l, r, eq)
11293        };
11294        let mut inputs = StorageCache::new();
11295        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11296        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11297        let (result_arc, _) = PipelinedExecutor::realize(graph, eq_id, inputs).expect("realize");
11298        let guard = result_arc.read().unwrap();
11299        assert_eq!(guard.dtype, DType::Bool);
11300        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11301            panic!("expected Cpu storage");
11302        };
11303        let mask: &[u8] = c.as_slice().expect("u8 view");
11304        assert_eq!(mask, &[1, 1, 0]);
11305    }
11306
11307    /// E2E: Op::Where ternary select — `out[i] = if cond[i] != 0 { a[i] } else { b[i] }`.
11308    /// Validates (a) the binding-table key `(Where, [Bool, F32, F32, F32], Cpu)`
11309    /// resolves to the where_f32 wrapper, (b) the Bool cond input drives
11310    /// the per-slot pick, (c) outputs preserve the input dtype.
11311    ///
11312    /// GAP-168(c): the cond STORAGE is tagged Bool, not merely the graph node.
11313    /// Bool and U8 are byte-identical, so leaving the storage U8 under a Bool
11314    /// node is exactly the mismatch this cut exists to make visible.
11315    #[test]
11316    fn pipelined_realize_where_f32_picks_per_slot_from_bool_mask() {
11317        // cond = [1, 0, 1, 0, 1]; a = [1, 2, 3, 4, 5]; b = [10, 20, 30, 40, 50]
11318        // expected = [1, 20, 3, 40, 5]
11319        let mut cond_storage = fuel_memory::from_slice_cpu(&[1u8, 0, 1, 0, 1]);
11320        cond_storage.dtype = DType::Bool; // GAP-168(c): a Bool mask, not U8 bytes
11321        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0]);
11322        let b_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0]);
11323        let graph = Arc::new(RwLock::new(Graph::new()));
11324        let (cond_id, a_id, b_id, where_id) = {
11325            let mut g = graph.write().unwrap();
11326            let cond = g.push(Node {
11327                op: Op::Const,
11328                inputs: vec![],
11329                shape: Shape::from_dims(&[5]),
11330                dtype: DType::Bool,
11331            });
11332            let a = g.push(Node {
11333                op: Op::Const,
11334                inputs: vec![],
11335                shape: Shape::from_dims(&[5]),
11336                dtype: DType::F32,
11337            });
11338            let b = g.push(Node {
11339                op: Op::Const,
11340                inputs: vec![],
11341                shape: Shape::from_dims(&[5]),
11342                dtype: DType::F32,
11343            });
11344            let w = g.push(Node {
11345                op: Op::Where,
11346                inputs: vec![cond, a, b],
11347                shape: Shape::from_dims(&[5]),
11348                dtype: DType::F32,
11349            });
11350            g.set_target_backend(w, BackendId::Cpu);
11351            (cond, a, b, w)
11352        };
11353        let mut inputs = StorageCache::new();
11354        inputs.insert(cond_id, Arc::new(RwLock::new(cond_storage)));
11355        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
11356        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
11357        let (result_arc, _) = PipelinedExecutor::realize(graph, where_id, inputs).expect("realize");
11358        let guard = result_arc.read().unwrap();
11359        assert_eq!(guard.dtype, DType::F32);
11360        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11361            panic!("expected Cpu storage");
11362        };
11363        let out: &[f32] = c.as_slice().expect("f32 view");
11364        assert_eq!(out, &[1.0, 20.0, 3.0, 40.0, 5.0]);
11365    }
11366
11367    /// E2E: full chain `eq → where`. Compares two f32 vectors, then
11368    /// uses the resulting Bool mask to pick from a third tensor (or a
11369    /// fallback). Validates the comparison-family + Where ops compose
11370    /// end-to-end.
11371    #[test]
11372    fn pipelined_realize_eq_then_where_full_chain() {
11373        // a = [1, 2, 3]; b = [1, 5, 3] → eq = [1, 0, 1]
11374        // pick = [10, 20, 30]; fallback = [99, 99, 99]
11375        // result = [10, 99, 30]
11376        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
11377        let b_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0]);
11378        let pick_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
11379        let fb_storage = fuel_memory::from_slice_cpu(&[99.0_f32, 99.0, 99.0]);
11380        let graph = Arc::new(RwLock::new(Graph::new()));
11381        let (a_id, b_id, pick_id, fb_id, where_id) = {
11382            let mut g = graph.write().unwrap();
11383            let a = g.push(Node {
11384                op: Op::Const,
11385                inputs: vec![],
11386                shape: Shape::from_dims(&[3]),
11387                dtype: DType::F32,
11388            });
11389            let b = g.push(Node {
11390                op: Op::Const,
11391                inputs: vec![],
11392                shape: Shape::from_dims(&[3]),
11393                dtype: DType::F32,
11394            });
11395            let pick = g.push(Node {
11396                op: Op::Const,
11397                inputs: vec![],
11398                shape: Shape::from_dims(&[3]),
11399                dtype: DType::F32,
11400            });
11401            let fb = g.push(Node {
11402                op: Op::Const,
11403                inputs: vec![],
11404                shape: Shape::from_dims(&[3]),
11405                dtype: DType::F32,
11406            });
11407            let eq = g.push(Node {
11408                op: Op::Equal,
11409                inputs: vec![a, b],
11410                shape: Shape::from_dims(&[3]),
11411                dtype: DType::Bool,
11412            });
11413            let w = g.push(Node {
11414                op: Op::Where,
11415                inputs: vec![eq, pick, fb],
11416                shape: Shape::from_dims(&[3]),
11417                dtype: DType::F32,
11418            });
11419            g.set_target_backend(eq, BackendId::Cpu);
11420            g.set_target_backend(w, BackendId::Cpu);
11421            (a, b, pick, fb, w)
11422        };
11423        let mut inputs = StorageCache::new();
11424        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
11425        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
11426        inputs.insert(pick_id, Arc::new(RwLock::new(pick_storage)));
11427        inputs.insert(fb_id, Arc::new(RwLock::new(fb_storage)));
11428        let (result_arc, _) = PipelinedExecutor::realize(graph, where_id, inputs).expect("realize");
11429        let guard = result_arc.read().unwrap();
11430        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11431            panic!("expected Cpu storage");
11432        };
11433        let out: &[f32] = c.as_slice().expect("f32 view");
11434        assert_eq!(out, &[10.0, 99.0, 30.0]);
11435    }
11436
11437    /// E2E: Q4_0 QMatMul through the pipelined executor — proves
11438    /// quantized weights can flow into the unified path. Activations
11439    /// are F32, weights are U32-typed (raw block bytes).
11440    /// Construct a Q4_0 weight tensor where every weight = 1.0
11441    /// (d=1.0, every nibble=9 → 1*(9-8)=1), so A @ W^T computes
11442    /// the per-row sum of activations.
11443    #[test]
11444    fn pipelined_realize_qmatmul_q4_0_unit_weight_sums_activations() {
11445        use fuel_graph::QuantType;
11446        use half::f16;
11447        let block_size = std::mem::size_of::<fuel_quantized::BlockQ4_0>();
11448        let mut w_bytes = vec![0u8; 2 * block_size];
11449        for block_idx in 0..2 {
11450            let off = block_idx * block_size;
11451            let d_bytes = f16::from_f32(1.0).to_le_bytes();
11452            w_bytes[off..off + 2].copy_from_slice(&d_bytes);
11453            for i in 0..16 {
11454                w_bytes[off + 2 + i] = 0x99;
11455            }
11456        }
11457        // Weight tensor is U32-typed (rank-1, length = bytes/4)
11458        let w_storage = fuel_memory::Storage::new(
11459            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
11460                &w_bytes,
11461            )),
11462            DType::U32,
11463        );
11464
11465        let act_vec: Vec<f32> = (1..=32).map(|x| x as f32).collect();
11466        let act_storage = fuel_memory::from_slice_cpu(&act_vec);
11467
11468        let graph = Arc::new(RwLock::new(Graph::new()));
11469        let (act_id, w_id, mm_id) = {
11470            let mut g = graph.write().unwrap();
11471            let act = g.push(Node {
11472                op: Op::Const,
11473                inputs: vec![],
11474                shape: Shape::from_dims(&[1, 32]),
11475                dtype: DType::F32,
11476            });
11477            let w = g.push(Node {
11478                op: Op::Const,
11479                inputs: vec![],
11480                shape: Shape::from_dims(&[w_bytes.len() / 4]),
11481                dtype: DType::U32,
11482            });
11483            let mm = g.push(Node {
11484                op: Op::Fused(
11485                    fuel_graph::registry::FusedOps::QMATMUL,
11486                    fuel_graph::registry::FusedOpParams::QMatMul {
11487                        quant_type: QuantType::Q4_0,
11488                        k: 32,
11489                        n: 2,
11490                    },
11491                ),
11492                inputs: vec![act, w],
11493                shape: Shape::from_dims(&[1, 2]),
11494                dtype: DType::F32,
11495            });
11496            g.set_target_backend(mm, BackendId::Cpu);
11497            (act, w, mm)
11498        };
11499        let mut inputs = StorageCache::new();
11500        inputs.insert(act_id, Arc::new(RwLock::new(act_storage)));
11501        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
11502        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11503        let guard = result_arc.read().unwrap();
11504        assert_eq!(guard.dtype, DType::F32);
11505        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11506            panic!("expected Cpu storage");
11507        };
11508        let r: &[f32] = c.as_slice().unwrap();
11509        // Both rows = sum(1..=32) = 528, within Q8_1 round-trip
11510        // tolerance.
11511        assert!((r[0] - 528.0).abs() < 0.5, "got {}, want 528", r[0]);
11512        assert!((r[1] - 528.0).abs() < 0.5, "got {}, want 528", r[1]);
11513    }
11514
11515    /// E2E: QMatMul with Q5_0 weights — verifies the new quant
11516    /// dispatch arm picks `qmatmul_q5_0_f32`. We build weights by
11517    /// quantizing all-ones via `BlockQ5_0::from_float`, then
11518    /// compare pipelined output against the direct fuel_quantized
11519    /// matmul on the same blocks.
11520    #[test]
11521    fn pipelined_realize_qmatmul_q5_0_against_reference() {
11522        use fuel_graph::QuantType;
11523        use fuel_quantized::{BlockQ5_0, GgmlType};
11524        let n = 2;
11525        let k = 64; // 2 blocks per row
11526        // Quantize an all-ones [n, k] weight matrix.
11527        let w_f32 = vec![1.0_f32; n * k];
11528        let blocks_per_row = k / BlockQ5_0::BLCK_SIZE;
11529        let mut w_blocks = vec![BlockQ5_0::zeros(); n * blocks_per_row];
11530        BlockQ5_0::from_float(&w_f32, &mut w_blocks);
11531        // Reinterpret block slice as bytes (BlockQ5_0 is #[repr(C)]).
11532        let bytes_per_block = std::mem::size_of::<BlockQ5_0>();
11533        let w_bytes: Vec<u8> = unsafe {
11534            std::slice::from_raw_parts(
11535                w_blocks.as_ptr() as *const u8,
11536                w_blocks.len() * bytes_per_block,
11537            )
11538        }
11539        .to_vec();
11540        let w_storage = fuel_memory::Storage::new(
11541            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
11542                &w_bytes,
11543            )),
11544            DType::U32,
11545        );
11546        let act_vec: Vec<f32> = (1..=k).map(|x| x as f32).collect();
11547        let act_storage = fuel_memory::from_slice_cpu(&act_vec);
11548        // Reference: direct matmul through fuel_quantized.
11549        let mut ref_out = vec![0.0_f32; n];
11550        fuel_quantized::matmul::<BlockQ5_0>((1, k, n), &act_vec, &w_blocks, &mut ref_out)
11551            .expect("ref matmul");
11552
11553        let graph = Arc::new(RwLock::new(Graph::new()));
11554        let (act_id, w_id, mm_id) = {
11555            let mut g = graph.write().unwrap();
11556            let act = g.push(Node {
11557                op: Op::Const,
11558                inputs: vec![],
11559                shape: Shape::from_dims(&[1, k]),
11560                dtype: DType::F32,
11561            });
11562            let w = g.push(Node {
11563                op: Op::Const,
11564                inputs: vec![],
11565                shape: Shape::from_dims(&[w_bytes.len() / 4]),
11566                dtype: DType::U32,
11567            });
11568            let mm = g.push(Node {
11569                op: Op::Fused(
11570                    fuel_graph::registry::FusedOps::QMATMUL,
11571                    fuel_graph::registry::FusedOpParams::QMatMul {
11572                        quant_type: QuantType::Q5_0,
11573                        k,
11574                        n,
11575                    },
11576                ),
11577                inputs: vec![act, w],
11578                shape: Shape::from_dims(&[1, n]),
11579                dtype: DType::F32,
11580            });
11581            g.set_target_backend(mm, BackendId::Cpu);
11582            (act, w, mm)
11583        };
11584        let mut inputs = StorageCache::new();
11585        inputs.insert(act_id, Arc::new(RwLock::new(act_storage)));
11586        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
11587        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11588        let guard = result_arc.read().unwrap();
11589        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11590            panic!("expected Cpu storage");
11591        };
11592        let r: &[f32] = c.as_slice().unwrap();
11593        // Bit-exact against same kernel via the trait, since both
11594        // paths run fuel_quantized::matmul<BlockQ5_0>.
11595        assert_eq!(
11596            r,
11597            ref_out.as_slice(),
11598            "pipelined Q5_0 differs from reference: got {r:?}, want {ref_out:?}"
11599        );
11600    }
11601
11602    /// E2E: QMatMul with Q6K (256-element super-block k-quant).
11603    /// Same idea as the Q5_0 test — bit-exact against the
11604    /// reference fuel_quantized::matmul<BlockQ6K>. Confirms the
11605    /// dispatch arm wires `qmatmul_q6k_f32` correctly.
11606    #[test]
11607    fn pipelined_realize_qmatmul_q6k_against_reference() {
11608        use fuel_graph::QuantType;
11609        use fuel_quantized::{BlockQ6K, GgmlType};
11610        let n = 2;
11611        let k = 256; // 1 super-block per row
11612        let w_f32 = vec![1.0_f32; n * k];
11613        let blocks_per_row = k / BlockQ6K::BLCK_SIZE;
11614        let mut w_blocks = vec![BlockQ6K::zeros(); n * blocks_per_row];
11615        BlockQ6K::from_float(&w_f32, &mut w_blocks);
11616        let bytes_per_block = std::mem::size_of::<BlockQ6K>();
11617        let w_bytes: Vec<u8> = unsafe {
11618            std::slice::from_raw_parts(
11619                w_blocks.as_ptr() as *const u8,
11620                w_blocks.len() * bytes_per_block,
11621            )
11622        }
11623        .to_vec();
11624        let w_storage = fuel_memory::Storage::new(
11625            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
11626                &w_bytes,
11627            )),
11628            DType::U32,
11629        );
11630        let act_vec: Vec<f32> = (1..=k).map(|x| x as f32 / 100.0).collect();
11631        let act_storage = fuel_memory::from_slice_cpu(&act_vec);
11632        let mut ref_out = vec![0.0_f32; n];
11633        fuel_quantized::matmul::<BlockQ6K>((1, k, n), &act_vec, &w_blocks, &mut ref_out)
11634            .expect("ref matmul");
11635
11636        let graph = Arc::new(RwLock::new(Graph::new()));
11637        let (act_id, w_id, mm_id) = {
11638            let mut g = graph.write().unwrap();
11639            let act = g.push(Node {
11640                op: Op::Const,
11641                inputs: vec![],
11642                shape: Shape::from_dims(&[1, k]),
11643                dtype: DType::F32,
11644            });
11645            let w = g.push(Node {
11646                op: Op::Const,
11647                inputs: vec![],
11648                shape: Shape::from_dims(&[w_bytes.len() / 4]),
11649                dtype: DType::U32,
11650            });
11651            let mm = g.push(Node {
11652                op: Op::Fused(
11653                    fuel_graph::registry::FusedOps::QMATMUL,
11654                    fuel_graph::registry::FusedOpParams::QMatMul {
11655                        quant_type: QuantType::Q6K,
11656                        k,
11657                        n,
11658                    },
11659                ),
11660                inputs: vec![act, w],
11661                shape: Shape::from_dims(&[1, n]),
11662                dtype: DType::F32,
11663            });
11664            g.set_target_backend(mm, BackendId::Cpu);
11665            (act, w, mm)
11666        };
11667        let mut inputs = StorageCache::new();
11668        inputs.insert(act_id, Arc::new(RwLock::new(act_storage)));
11669        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
11670        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11671        let guard = result_arc.read().unwrap();
11672        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11673            panic!("expected Cpu storage");
11674        };
11675        let r: &[f32] = c.as_slice().unwrap();
11676        assert_eq!(
11677            r,
11678            ref_out.as_slice(),
11679            "pipelined Q6K differs from reference: got {r:?}, want {ref_out:?}"
11680        );
11681    }
11682
11683    /// E2E: `QMatMul` through the pipelined executor for the formats added with the float route
11684    /// (Q3_K, Q5_K, IQ4_NL, IQ4_XS, IQ3_S; board 307: dequantized tile by tile, multiplied in
11685    /// float). The weights are the type's own blocks from random bytes (a small finite `d`), the
11686    /// reference is `fuel_quantized::matmul`, and the dispatch arm must be the one for that type:
11687    /// a wrong `quant_type` arm decodes the same bytes differently and is far from the reference.
11688    fn qmatmul_e2e_random_blocks<T: fuel_quantized::GgmlType>(quant_type: fuel_graph::QuantType) {
11689        let (m, n, k) = (3, 5, 512);
11690        let size = std::mem::size_of::<T>();
11691        let count = n * k / T::BLCK_SIZE;
11692        let mut seed = 0x9E37_79B9_u32;
11693        let mut w_bytes: Vec<u8> = (0..count * size)
11694            .map(|_| {
11695                seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
11696                (seed >> 24) as u8
11697            })
11698            .collect();
11699        let d = half::f16::from_f32(0.02).to_le_bytes();
11700        for b in 0..count {
11701            w_bytes[b * size..b * size + 2].copy_from_slice(&d);
11702        }
11703        let mut w_blocks = vec![T::zeros(); count];
11704        bytemuck::cast_slice_mut::<T, u8>(&mut w_blocks).copy_from_slice(&w_bytes);
11705        let act_vec: Vec<f32> = (0..m * k).map(|x| ((x % 17) as f32 - 8.0) / 8.0).collect();
11706        let mut ref_out = vec![0.0_f32; m * n];
11707        fuel_quantized::matmul::<T>((m, k, n), &act_vec, &w_blocks, &mut ref_out).expect("ref");
11708
11709        let w_storage = fuel_memory::Storage::new(
11710            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
11711                &w_bytes,
11712            )),
11713            DType::U32,
11714        );
11715        let graph = Arc::new(RwLock::new(Graph::new()));
11716        let (act_id, w_id, mm_id) = {
11717            let mut g = graph.write().unwrap();
11718            let act = g.push(Node {
11719                op: Op::Const,
11720                inputs: vec![],
11721                shape: Shape::from_dims(&[m, k]),
11722                dtype: DType::F32,
11723            });
11724            let w = g.push(Node {
11725                op: Op::Const,
11726                inputs: vec![],
11727                shape: Shape::from_dims(&[w_bytes.len() / 4]),
11728                dtype: DType::U32,
11729            });
11730            let mm = g.push(Node {
11731                op: Op::Fused(
11732                    fuel_graph::registry::FusedOps::QMATMUL,
11733                    fuel_graph::registry::FusedOpParams::QMatMul { quant_type, k, n },
11734                ),
11735                inputs: vec![act, w],
11736                shape: Shape::from_dims(&[m, n]),
11737                dtype: DType::F32,
11738            });
11739            g.set_target_backend(mm, BackendId::Cpu);
11740            (act, w, mm)
11741        };
11742        let mut inputs = StorageCache::new();
11743        inputs.insert(
11744            act_id,
11745            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&act_vec))),
11746        );
11747        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
11748        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11749        let guard = result_arc.read().unwrap();
11750        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11751            panic!("expected Cpu storage");
11752        };
11753        let r: &[f32] = c.as_slice().unwrap();
11754        let scale = ref_out.iter().fold(1e-6_f32, |a, v| a.max(v.abs()));
11755        let worst = r
11756            .iter()
11757            .zip(&ref_out)
11758            .fold(0.0_f32, |a, (x, y)| a.max((x - y).abs()));
11759        assert!(
11760            worst <= 1e-5 * scale,
11761            "{quant_type:?}: pipelined differs from the reference by {worst} (scale {scale})"
11762        );
11763        assert!(
11764            scale > 1e-3,
11765            "{quant_type:?}: the product is all zeros, the test is vacuous"
11766        );
11767    }
11768
11769    #[test]
11770    fn pipelined_realize_qmatmul_float_route_formats_against_reference() {
11771        use fuel_graph::QuantType;
11772        use fuel_quantized::iq_grid_types::BlockIq3S;
11773        use fuel_quantized::iq4::{BlockIq4Nl, BlockIq4Xs};
11774        use fuel_quantized::{BlockQ3K, BlockQ5K};
11775        qmatmul_e2e_random_blocks::<BlockQ3K>(QuantType::Q3K);
11776        qmatmul_e2e_random_blocks::<BlockQ5K>(QuantType::Q5K);
11777        qmatmul_e2e_random_blocks::<BlockIq4Nl>(QuantType::Iq4Nl);
11778        qmatmul_e2e_random_blocks::<BlockIq4Xs>(QuantType::Iq4Xs);
11779        qmatmul_e2e_random_blocks::<BlockIq3S>(QuantType::Iq3S);
11780    }
11781
11782    /// E2E: BF16 RmsNormLastDim through the pipelined executor.
11783    /// Verifies that capability-driven dispatch routes the
11784    /// half-float norm op to the bf16-specific kernel (which
11785    /// accumulates in f32 internally).
11786    #[test]
11787    fn pipelined_realize_rms_norm_bf16() {
11788        let v: Vec<half::bf16> = [3.0_f32, 4.0]
11789            .iter()
11790            .map(|&x| half::bf16::from_f32(x))
11791            .collect();
11792        let storage = fuel_memory::from_slice_cpu(&v);
11793        let graph = Arc::new(RwLock::new(Graph::new()));
11794        let (in_id, op_id) = {
11795            let mut g = graph.write().unwrap();
11796            let in_id = g.push(Node {
11797                op: Op::Const,
11798                inputs: vec![],
11799                shape: Shape::from_dims(&[1, 2]),
11800                dtype: DType::BF16,
11801            });
11802            let op_id = g.push(Node {
11803                op: Op::Fused(
11804                    fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM,
11805                    fuel_graph::registry::FusedOpParams::RmsNormLastDim { eps: 0.0 },
11806                ),
11807                inputs: vec![in_id],
11808                shape: Shape::from_dims(&[1, 2]),
11809                dtype: DType::BF16,
11810            });
11811            g.set_target_backend(op_id, BackendId::Cpu);
11812            (in_id, op_id)
11813        };
11814        let mut inputs = StorageCache::new();
11815        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11816        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
11817        let guard = result_arc.read().unwrap();
11818        assert_eq!(guard.dtype, DType::BF16);
11819        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11820            panic!("expected Cpu storage");
11821        };
11822        let r: &[half::bf16] = c.as_slice().unwrap();
11823        let rms = (12.5_f32).sqrt();
11824        // bf16's ~3-digit mantissa absorbs the divisor; allow ~5%.
11825        assert!((r[0].to_f32() - 3.0 / rms).abs() < 0.05);
11826        assert!((r[1].to_f32() - 4.0 / rms).abs() < 0.05);
11827    }
11828
11829    /// E2E: BF16 matmul through the pipelined executor — proves
11830    /// the LLM forward-pass blocker (every transformer layer
11831    /// is dominated by matmul). Identity matmul on bf16 round-
11832    /// trips small integers exactly.
11833    #[test]
11834    fn pipelined_realize_matmul_bf16_identity() {
11835        let lhs_v: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0]
11836            .iter()
11837            .map(|&x| half::bf16::from_f32(x))
11838            .collect();
11839        let rhs_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0]
11840            .iter()
11841            .map(|&x| half::bf16::from_f32(x))
11842            .collect();
11843        let lhs = fuel_memory::from_slice_cpu(&lhs_v);
11844        let rhs = fuel_memory::from_slice_cpu(&rhs_v);
11845        let graph = Arc::new(RwLock::new(Graph::new()));
11846        let (l_id, r_id, mm_id) = {
11847            let mut g = graph.write().unwrap();
11848            let l = g.push(Node {
11849                op: Op::Const,
11850                inputs: vec![],
11851                shape: Shape::from_dims(&[2, 2]),
11852                dtype: DType::BF16,
11853            });
11854            let r = g.push(Node {
11855                op: Op::Const,
11856                inputs: vec![],
11857                shape: Shape::from_dims(&[2, 2]),
11858                dtype: DType::BF16,
11859            });
11860            let mm = g.push(Node {
11861                op: Op::MatMul,
11862                inputs: vec![l, r],
11863                shape: Shape::from_dims(&[2, 2]),
11864                dtype: DType::BF16,
11865            });
11866            g.set_target_backend(mm, BackendId::Cpu);
11867            (l, r, mm)
11868        };
11869        let mut inputs = StorageCache::new();
11870        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11871        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11872        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11873        let guard = result_arc.read().unwrap();
11874        assert_eq!(guard.dtype, DType::BF16);
11875        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11876            panic!("expected Cpu storage");
11877        };
11878        let r: &[half::bf16] = c.as_slice().unwrap();
11879        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
11880        assert_eq!(result_f32, vec![1.0, 2.0, 3.0, 4.0]);
11881    }
11882
11883    /// E2E (ROADMAP row 34): a mixed `[F32, W, F32]` matmul (f32 activation, half weight) runs on
11884    /// the CPU through the NATIVE kernel, with the weight left half-width: the output is f32 and
11885    /// equals the f64 matmul over the widened weights to f32 accumulation error. The weight is
11886    /// rounded to its stored half type first.
11887    fn mixed_cpu_matmul_matches_f64(weight_dtype: DType) {
11888        let (m, n, k) = (3_usize, 5_usize, 7_usize);
11889        let a: Vec<f32> = (0..m * k)
11890            .map(|i| ((i * 37 % 19) as f32 - 9.0) / 8.0)
11891            .collect();
11892        let w_f32: Vec<f32> = (0..k * n)
11893            .map(|i| ((i * 53 % 23) as f32 - 11.0) / 10.0)
11894            .collect();
11895        let (w_storage, widened): (_, Vec<f32>) = if weight_dtype == DType::BF16 {
11896            let h: Vec<half::bf16> = w_f32.iter().map(|&x| half::bf16::from_f32(x)).collect();
11897            let wide = h.iter().map(|x| x.to_f32()).collect();
11898            (fuel_memory::from_slice_cpu(&h), wide)
11899        } else {
11900            let h: Vec<half::f16> = w_f32.iter().map(|&x| half::f16::from_f32(x)).collect();
11901            let wide = h.iter().map(|x| x.to_f32()).collect();
11902            (fuel_memory::from_slice_cpu(&h), wide)
11903        };
11904        let graph = Arc::new(RwLock::new(Graph::new()));
11905        let (l_id, r_id, mm_id) = {
11906            let mut g = graph.write().unwrap();
11907            let l = g.push(Node {
11908                op: Op::Const,
11909                inputs: vec![],
11910                shape: Shape::from_dims(&[m, k]),
11911                dtype: DType::F32,
11912            });
11913            let r = g.push(Node {
11914                op: Op::Const,
11915                inputs: vec![],
11916                shape: Shape::from_dims(&[k, n]),
11917                dtype: weight_dtype,
11918            });
11919            let mm = g.push(Node {
11920                op: Op::MatMul,
11921                inputs: vec![l, r],
11922                shape: Shape::from_dims(&[m, n]),
11923                dtype: DType::F32,
11924            });
11925            g.set_target_backend(mm, BackendId::Cpu);
11926            (l, r, mm)
11927        };
11928        let mut inputs = StorageCache::new();
11929        inputs.insert(l_id, Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&a))));
11930        inputs.insert(r_id, Arc::new(RwLock::new(w_storage)));
11931        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11932        let guard = result_arc.read().unwrap();
11933        assert_eq!(guard.dtype, DType::F32);
11934        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11935            panic!("expected Cpu storage");
11936        };
11937        let got: &[f32] = c.as_slice().unwrap();
11938        for i in 0..m {
11939            for j in 0..n {
11940                let want: f64 = (0..k)
11941                    .map(|kk| a[i * k + kk] as f64 * widened[kk * n + j] as f64)
11942                    .sum();
11943                let err = (got[i * n + j] as f64 - want).abs();
11944                assert!(
11945                    err < 1e-5,
11946                    "{weight_dtype:?} [{i},{j}]: got {}, want {want}",
11947                    got[i * n + j]
11948                );
11949            }
11950        }
11951    }
11952
11953    #[test]
11954    fn pipelined_realize_mixed_f32_bf16_matmul_is_native_on_cpu() {
11955        mixed_cpu_matmul_matches_f64(DType::BF16);
11956    }
11957
11958    #[test]
11959    fn pipelined_realize_mixed_f32_f16_matmul_is_native_on_cpu() {
11960        mixed_cpu_matmul_matches_f64(DType::F16);
11961    }
11962
11963    /// E2E: F16 sum-reduce — verifies bf16/f16 reduction dispatch
11964    /// works through the executor.
11965    #[test]
11966    fn pipelined_realize_sum_dim_f16() {
11967        let v: Vec<half::f16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]
11968            .iter()
11969            .map(|&x| half::f16::from_f32(x))
11970            .collect();
11971        let storage = fuel_memory::from_slice_cpu(&v);
11972        let graph = Arc::new(RwLock::new(Graph::new()));
11973        let (in_id, sum_id) = {
11974            let mut g = graph.write().unwrap();
11975            let in_id = g.push(Node {
11976                op: Op::Const,
11977                inputs: vec![],
11978                shape: Shape::from_dims(&[2, 3]),
11979                dtype: DType::F16,
11980            });
11981            let sum_id = g.push(Node {
11982                op: Op::SumDim(1),
11983                inputs: vec![in_id],
11984                shape: Shape::from_dims(&[2]),
11985                dtype: DType::F16,
11986            });
11987            g.set_target_backend(sum_id, BackendId::Cpu);
11988            (in_id, sum_id)
11989        };
11990        let mut inputs = StorageCache::new();
11991        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11992        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
11993        let guard = result_arc.read().unwrap();
11994        assert_eq!(guard.dtype, DType::F16);
11995        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11996            panic!("expected Cpu storage");
11997        };
11998        let r: &[half::f16] = c.as_slice().unwrap();
11999        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
12000        assert_eq!(result_f32, vec![6.0, 15.0]);
12001    }
12002
12003    /// E2E: BF16 elementwise add through the pipelined executor.
12004    #[test]
12005    fn pipelined_realize_add_bf16() {
12006        let lhs_vec: Vec<half::bf16> = [1.0_f32, 2.0, 3.0]
12007            .iter()
12008            .map(|&x| half::bf16::from_f32(x))
12009            .collect();
12010        let rhs_vec: Vec<half::bf16> = [10.0_f32, 20.0, 30.0]
12011            .iter()
12012            .map(|&x| half::bf16::from_f32(x))
12013            .collect();
12014        let lhs = fuel_memory::from_slice_cpu(&lhs_vec);
12015        let rhs = fuel_memory::from_slice_cpu(&rhs_vec);
12016        let graph = Arc::new(RwLock::new(Graph::new()));
12017        let (l_id, r_id, op_id) = {
12018            let mut g = graph.write().unwrap();
12019            let l = g.push(Node {
12020                op: Op::Const,
12021                inputs: vec![],
12022                shape: Shape::from_dims(&[3]),
12023                dtype: DType::BF16,
12024            });
12025            let r = g.push(Node {
12026                op: Op::Const,
12027                inputs: vec![],
12028                shape: Shape::from_dims(&[3]),
12029                dtype: DType::BF16,
12030            });
12031            let op = g.push(Node {
12032                op: Op::Add,
12033                inputs: vec![l, r],
12034                shape: Shape::from_dims(&[3]),
12035                dtype: DType::BF16,
12036            });
12037            g.set_target_backend(op, BackendId::Cpu);
12038            (l, r, op)
12039        };
12040        let mut inputs = StorageCache::new();
12041        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
12042        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
12043        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12044        let guard = result_arc.read().unwrap();
12045        assert_eq!(guard.dtype, DType::BF16);
12046        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12047            panic!("expected Cpu storage");
12048        };
12049        let r: &[half::bf16] = c.as_slice().unwrap();
12050        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
12051        assert_eq!(result_f32, vec![11.0, 22.0, 33.0]);
12052    }
12053
12054    /// E2E: F16 unary chain — Const + Sqr + Sqrt — verifies F16
12055    /// dispatch works and the via-f32 round-trip kernels behave
12056    /// correctly through the executor.
12057    #[test]
12058    fn pipelined_realize_sqr_then_sqrt_f16() {
12059        let v: Vec<half::f16> = [1.0_f32, 4.0, 9.0]
12060            .iter()
12061            .map(|&x| half::f16::from_f32(x))
12062            .collect();
12063        let storage = fuel_memory::from_slice_cpu(&v);
12064        let graph = Arc::new(RwLock::new(Graph::new()));
12065        let (in_id, sqrt_id) = {
12066            let mut g = graph.write().unwrap();
12067            let in_id = g.push(Node {
12068                op: Op::Const,
12069                inputs: vec![],
12070                shape: Shape::from_dims(&[3]),
12071                dtype: DType::F16,
12072            });
12073            let sqr_id = g.push(Node {
12074                op: Op::Sqr,
12075                inputs: vec![in_id],
12076                shape: Shape::from_dims(&[3]),
12077                dtype: DType::F16,
12078            });
12079            let sqrt_id = g.push(Node {
12080                op: Op::Sqrt,
12081                inputs: vec![sqr_id],
12082                shape: Shape::from_dims(&[3]),
12083                dtype: DType::F16,
12084            });
12085            g.set_target_backend(sqr_id, BackendId::Cpu);
12086            g.set_target_backend(sqrt_id, BackendId::Cpu);
12087            (in_id, sqrt_id)
12088        };
12089        let mut inputs = StorageCache::new();
12090        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12091        let (result_arc, _) = PipelinedExecutor::realize(graph, sqrt_id, inputs).expect("realize");
12092        let guard = result_arc.read().unwrap();
12093        assert_eq!(guard.dtype, DType::F16);
12094        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12095            panic!("expected Cpu storage");
12096        };
12097        let r: &[half::f16] = c.as_slice().unwrap();
12098        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
12099        // f16 has ~3 decimal digits; sqrt(sqr(x)) = |x| within rounding.
12100        for (got, want) in result_f32.iter().zip(&[1.0_f32, 4.0, 9.0]) {
12101            assert!((got - want).abs() < 0.05, "got {got}, want {want}");
12102        }
12103    }
12104
12105    /// E2E: F64 sum-reduce along one dim through the pipelined
12106    /// executor.
12107    #[test]
12108    fn pipelined_realize_sum_dim_f64() {
12109        let storage = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
12110        let graph = Arc::new(RwLock::new(Graph::new()));
12111        let (in_id, sum_id) = {
12112            let mut g = graph.write().unwrap();
12113            let in_id = g.push(Node {
12114                op: Op::Const,
12115                inputs: vec![],
12116                shape: Shape::from_dims(&[2, 3]),
12117                dtype: DType::F64,
12118            });
12119            let sum_id = g.push(Node {
12120                op: Op::SumDim(1),
12121                inputs: vec![in_id],
12122                shape: Shape::from_dims(&[2]),
12123                dtype: DType::F64,
12124            });
12125            g.set_target_backend(sum_id, BackendId::Cpu);
12126            (in_id, sum_id)
12127        };
12128        let mut inputs = StorageCache::new();
12129        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12130        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
12131        let guard = result_arc.read().unwrap();
12132        assert_eq!(guard.dtype, DType::F64);
12133        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12134            panic!("expected Cpu storage");
12135        };
12136        assert_eq!(c.as_slice::<f64>().unwrap(), &[6.0_f64, 15.0]);
12137    }
12138
12139    /// E2E: F64 matmul through the pipelined executor.
12140    #[test]
12141    fn pipelined_realize_matmul_2x3_times_3x2_f64() {
12142        let lhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
12143        let rhs = fuel_memory::from_slice_cpu(&[7.0_f64, 8.0, 9.0, 10.0, 11.0, 12.0]);
12144        let graph = Arc::new(RwLock::new(Graph::new()));
12145        let (l_id, r_id, mm_id) = {
12146            let mut g = graph.write().unwrap();
12147            let l = g.push(Node {
12148                op: Op::Const,
12149                inputs: vec![],
12150                shape: Shape::from_dims(&[2, 3]),
12151                dtype: DType::F64,
12152            });
12153            let r = g.push(Node {
12154                op: Op::Const,
12155                inputs: vec![],
12156                shape: Shape::from_dims(&[3, 2]),
12157                dtype: DType::F64,
12158            });
12159            let mm = g.push(Node {
12160                op: Op::MatMul,
12161                inputs: vec![l, r],
12162                shape: Shape::from_dims(&[2, 2]),
12163                dtype: DType::F64,
12164            });
12165            g.set_target_backend(mm, BackendId::Cpu);
12166            (l, r, mm)
12167        };
12168        let mut inputs = StorageCache::new();
12169        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
12170        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
12171        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
12172        let guard = result_arc.read().unwrap();
12173        assert_eq!(guard.dtype, DType::F64);
12174        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12175            panic!("expected Cpu storage");
12176        };
12177        assert_eq!(
12178            c.as_slice::<f64>().unwrap(),
12179            &[58.0_f64, 64.0, 139.0, 154.0]
12180        );
12181    }
12182
12183    /// E2E: F64 unary chain — Const + Sqr + Sqrt — verifies that
12184    /// the kernel-binding lookup picks the f64 entries when the
12185    /// graph nodes carry DType::F64.
12186    #[test]
12187    fn pipelined_realize_sqr_then_sqrt_f64() {
12188        let storage = fuel_memory::from_slice_cpu(&[1.0_f64, 4.0, 9.0]);
12189        let graph = Arc::new(RwLock::new(Graph::new()));
12190        let (in_id, sqrt_id) = {
12191            let mut g = graph.write().unwrap();
12192            let in_id = g.push(Node {
12193                op: Op::Const,
12194                inputs: vec![],
12195                shape: Shape::from_dims(&[3]),
12196                dtype: DType::F64,
12197            });
12198            let sqr_id = g.push(Node {
12199                op: Op::Sqr,
12200                inputs: vec![in_id],
12201                shape: Shape::from_dims(&[3]),
12202                dtype: DType::F64,
12203            });
12204            let sqrt_id = g.push(Node {
12205                op: Op::Sqrt,
12206                inputs: vec![sqr_id],
12207                shape: Shape::from_dims(&[3]),
12208                dtype: DType::F64,
12209            });
12210            g.set_target_backend(sqr_id, BackendId::Cpu);
12211            g.set_target_backend(sqrt_id, BackendId::Cpu);
12212            (in_id, sqrt_id)
12213        };
12214        let mut inputs = StorageCache::new();
12215        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12216        let (result_arc, _) = PipelinedExecutor::realize(graph, sqrt_id, inputs).expect("realize");
12217        let guard = result_arc.read().unwrap();
12218        assert_eq!(guard.dtype, DType::F64);
12219        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12220            panic!("expected Cpu storage");
12221        };
12222        assert_eq!(c.as_slice::<f64>().unwrap(), &[1.0_f64, 4.0, 9.0]);
12223    }
12224
12225    /// E2E: ArgMaxDim — produces U32 output indices.
12226    #[test]
12227    fn pipelined_realize_argmax_dim() {
12228        // input [2, 3] = [[1, 5, 2], [9, 0, 4]]
12229        // argmax dim=1 → [1, 0]
12230        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 2.0, 9.0, 0.0, 4.0]);
12231        let graph = Arc::new(RwLock::new(Graph::new()));
12232        let (in_id, op_id) = {
12233            let mut g = graph.write().unwrap();
12234            let in_id = g.push(Node {
12235                op: Op::Const,
12236                inputs: vec![],
12237                shape: Shape::from_dims(&[2, 3]),
12238                dtype: DType::F32,
12239            });
12240            let op_id = g.push(Node {
12241                op: Op::ArgMaxDim(1),
12242                inputs: vec![in_id],
12243                shape: Shape::from_dims(&[2]),
12244                dtype: DType::U32,
12245            });
12246            g.set_target_backend(op_id, BackendId::Cpu);
12247            (in_id, op_id)
12248        };
12249        let mut inputs = StorageCache::new();
12250        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12251        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12252        let guard = result_arc.read().unwrap();
12253        assert_eq!(guard.dtype, DType::U32);
12254        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12255            panic!("expected Cpu storage");
12256        };
12257        assert_eq!(c.as_slice::<u32>().unwrap(), &[1u32, 0]);
12258    }
12259
12260    /// E2E: IndexAdd along outer dim — accumulate updates into a
12261    /// rank-1 base tensor at indexed positions.
12262    #[test]
12263    fn pipelined_realize_index_add_simple() {
12264        let base = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
12265        let indices = fuel_memory::from_slice_cpu(&[0u32, 0]);
12266        let src = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
12267        let graph = Arc::new(RwLock::new(Graph::new()));
12268        let (b_id, i_id, s_id, op_id) = {
12269            let mut g = graph.write().unwrap();
12270            let b = g.push(Node {
12271                op: Op::Const,
12272                inputs: vec![],
12273                shape: Shape::from_dims(&[3]),
12274                dtype: DType::F32,
12275            });
12276            let i = g.push(Node {
12277                op: Op::Const,
12278                inputs: vec![],
12279                shape: Shape::from_dims(&[2]),
12280                dtype: DType::U32,
12281            });
12282            let s = g.push(Node {
12283                op: Op::Const,
12284                inputs: vec![],
12285                shape: Shape::from_dims(&[2]),
12286                dtype: DType::F32,
12287            });
12288            let op = g.push(Node {
12289                op: Op::IndexAdd { dim: 0 },
12290                inputs: vec![b, i, s],
12291                shape: Shape::from_dims(&[3]),
12292                dtype: DType::F32,
12293            });
12294            g.set_target_backend(op, BackendId::Cpu);
12295            (b, i, s, op)
12296        };
12297        let mut inputs = StorageCache::new();
12298        inputs.insert(b_id, Arc::new(RwLock::new(base)));
12299        inputs.insert(i_id, Arc::new(RwLock::new(indices)));
12300        inputs.insert(s_id, Arc::new(RwLock::new(src)));
12301        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12302        let guard = result_arc.read().unwrap();
12303        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12304            panic!("expected Cpu storage");
12305        };
12306        // 10 + 1 + 2 = 13; 20 untouched; 30 untouched.
12307        assert_eq!(c.as_slice::<f32>().unwrap(), &[13.0, 20.0, 30.0]);
12308    }
12309
12310    /// E2E: ScatterAdd along outer dim — same-rank indices, base
12311    /// starts as zeros, src adds values at scatter positions.
12312    #[test]
12313    fn pipelined_realize_scatter_add_outer_dim() {
12314        // base [3, 2] = zeros; indices [2, 2] = [[0, 1], [2, 0]];
12315        // src [2, 2] = [[1, 2], [3, 4]]; dim=0
12316        // → out = [[1, 4], [0, 2], [3, 0]]
12317        let base = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
12318        let indices = fuel_memory::from_slice_cpu(&[0u32, 1, 2, 0]);
12319        let src = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
12320        let graph = Arc::new(RwLock::new(Graph::new()));
12321        let (b_id, i_id, s_id, op_id) = {
12322            let mut g = graph.write().unwrap();
12323            let b = g.push(Node {
12324                op: Op::Const,
12325                inputs: vec![],
12326                shape: Shape::from_dims(&[3, 2]),
12327                dtype: DType::F32,
12328            });
12329            let i = g.push(Node {
12330                op: Op::Const,
12331                inputs: vec![],
12332                shape: Shape::from_dims(&[2, 2]),
12333                dtype: DType::U32,
12334            });
12335            let s = g.push(Node {
12336                op: Op::Const,
12337                inputs: vec![],
12338                shape: Shape::from_dims(&[2, 2]),
12339                dtype: DType::F32,
12340            });
12341            let op = g.push(Node {
12342                op: Op::ScatterAdd { dim: 0 },
12343                inputs: vec![b, i, s],
12344                shape: Shape::from_dims(&[3, 2]),
12345                dtype: DType::F32,
12346            });
12347            g.set_target_backend(op, BackendId::Cpu);
12348            (b, i, s, op)
12349        };
12350        let mut inputs = StorageCache::new();
12351        inputs.insert(b_id, Arc::new(RwLock::new(base)));
12352        inputs.insert(i_id, Arc::new(RwLock::new(indices)));
12353        inputs.insert(s_id, Arc::new(RwLock::new(src)));
12354        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12355        let guard = result_arc.read().unwrap();
12356        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12357            panic!("expected Cpu storage");
12358        };
12359        assert_eq!(
12360            c.as_slice::<f32>().unwrap(),
12361            &[1.0, 4.0, 0.0, 2.0, 3.0, 0.0]
12362        );
12363    }
12364
12365    /// E2E: Rope through the pipelined executor. cos=0, sin=1
12366    /// rotates the head_dim halves with sign per the rotate_half
12367    /// convention.
12368    #[test]
12369    fn pipelined_realize_rope_pi_over_two() {
12370        // x [1, 1, 4] = [1, 2, 3, 4]. cos=[0,0,0,0], sin=[1,1,1,1].
12371        // Expected: [-3, -4, 1, 2].
12372        let x = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
12373        let cos = fuel_memory::from_slice_cpu(&[0.0_f32, 0.0, 0.0, 0.0]);
12374        let sin = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
12375        let graph = Arc::new(RwLock::new(Graph::new()));
12376        let (x_id, cos_id, sin_id, r_id) = {
12377            let mut g = graph.write().unwrap();
12378            let x = g.push(Node {
12379                op: Op::Const,
12380                inputs: vec![],
12381                shape: Shape::from_dims(&[1, 1, 4]),
12382                dtype: DType::F32,
12383            });
12384            let c = g.push(Node {
12385                op: Op::Const,
12386                inputs: vec![],
12387                shape: Shape::from_dims(&[1, 4]),
12388                dtype: DType::F32,
12389            });
12390            let s = g.push(Node {
12391                op: Op::Const,
12392                inputs: vec![],
12393                shape: Shape::from_dims(&[1, 4]),
12394                dtype: DType::F32,
12395            });
12396            let r = g.push(Node {
12397                op: Op::Fused(
12398                    fuel_graph::registry::FusedOps::ROPE,
12399                    fuel_graph::registry::FusedOpParams::Rope,
12400                ),
12401                inputs: vec![x, c, s],
12402                shape: Shape::from_dims(&[1, 1, 4]),
12403                dtype: DType::F32,
12404            });
12405            g.set_target_backend(r, BackendId::Cpu);
12406            (x, c, s, r)
12407        };
12408        let mut inputs = StorageCache::new();
12409        inputs.insert(x_id, Arc::new(RwLock::new(x)));
12410        inputs.insert(cos_id, Arc::new(RwLock::new(cos)));
12411        inputs.insert(sin_id, Arc::new(RwLock::new(sin)));
12412        let (result_arc, _) = PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
12413        let guard = result_arc.read().unwrap();
12414        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12415            panic!("expected Cpu storage");
12416        };
12417        assert_eq!(c.as_slice::<f32>().unwrap(), &[-3.0, -4.0, 1.0, 2.0]);
12418    }
12419
12420    /// E2E: Gather along inner dim. Source [2, 4]; indices [2, 3];
12421    /// output [2, 3] = picks from each row by per-row indices.
12422    #[test]
12423    fn pipelined_realize_gather_inner_dim() {
12424        let source =
12425            fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0]);
12426        let indices = fuel_memory::from_slice_cpu(&[0u32, 2, 1, 3, 0, 0]);
12427        let graph = Arc::new(RwLock::new(Graph::new()));
12428        let (src_id, idx_id, g_id) = {
12429            let mut g = graph.write().unwrap();
12430            let s = g.push(Node {
12431                op: Op::Const,
12432                inputs: vec![],
12433                shape: Shape::from_dims(&[2, 4]),
12434                dtype: DType::F32,
12435            });
12436            let i = g.push(Node {
12437                op: Op::Const,
12438                inputs: vec![],
12439                shape: Shape::from_dims(&[2, 3]),
12440                dtype: DType::U32,
12441            });
12442            let g_id = g.push(Node {
12443                op: Op::Gather { dim: 1 },
12444                inputs: vec![s, i],
12445                shape: Shape::from_dims(&[2, 3]),
12446                dtype: DType::F32,
12447            });
12448            g.set_target_backend(g_id, BackendId::Cpu);
12449            (s, i, g_id)
12450        };
12451        let mut inputs = StorageCache::new();
12452        inputs.insert(src_id, Arc::new(RwLock::new(source)));
12453        inputs.insert(idx_id, Arc::new(RwLock::new(indices)));
12454        let (result_arc, _) = PipelinedExecutor::realize(graph, g_id, inputs).expect("realize");
12455        let guard = result_arc.read().unwrap();
12456        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12457            panic!("expected Cpu storage");
12458        };
12459        assert_eq!(
12460            c.as_slice::<f32>().unwrap(),
12461            &[10.0, 30.0, 20.0, 80.0, 50.0, 50.0]
12462        );
12463    }
12464
12465    /// E2E: IndexSelect — embedding-table lookup. Source is a
12466    /// `[vocab=4, d_model=3]` table; indices are token IDs;
12467    /// output is `[seq=3, d_model=3]` with the picked rows.
12468    #[test]
12469    fn pipelined_realize_index_select_embedding_lookup() {
12470        let table = fuel_memory::from_slice_cpu(&[
12471            10.0_f32, 11.0, 12.0, // row 0
12472            20.0, 21.0, 22.0, // row 1
12473            30.0, 31.0, 32.0, // row 2
12474            40.0, 41.0, 42.0, // row 3
12475        ]);
12476        let indices = fuel_memory::from_slice_cpu(&[2u32, 0, 2]);
12477        let graph = Arc::new(RwLock::new(Graph::new()));
12478        let (table_id, idx_id, sel_id) = {
12479            let mut g = graph.write().unwrap();
12480            let t = g.push(Node {
12481                op: Op::Const,
12482                inputs: vec![],
12483                shape: Shape::from_dims(&[4, 3]),
12484                dtype: DType::F32,
12485            });
12486            let i = g.push(Node {
12487                op: Op::Const,
12488                inputs: vec![],
12489                shape: Shape::from_dims(&[3]),
12490                dtype: DType::U32,
12491            });
12492            let s = g.push(Node {
12493                op: Op::IndexSelect { dim: 0 },
12494                inputs: vec![t, i],
12495                shape: Shape::from_dims(&[3, 3]),
12496                dtype: DType::F32,
12497            });
12498            g.set_target_backend(s, BackendId::Cpu);
12499            (t, i, s)
12500        };
12501        let mut inputs = StorageCache::new();
12502        inputs.insert(table_id, Arc::new(RwLock::new(table)));
12503        inputs.insert(idx_id, Arc::new(RwLock::new(indices)));
12504        let (result_arc, result_layout) =
12505            PipelinedExecutor::realize(graph, sel_id, inputs).expect("realize");
12506        assert_eq!(result_layout.shape().dims(), &[3, 3]);
12507        let guard = result_arc.read().unwrap();
12508        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12509            panic!("expected Cpu storage");
12510        };
12511        assert_eq!(
12512            c.as_slice::<f32>().unwrap(),
12513            &[30.0, 31.0, 32.0, 10.0, 11.0, 12.0, 30.0, 31.0, 32.0]
12514        );
12515    }
12516
12517    /// E2E: RmsNormLastDim on a 2-row input. Each row's output
12518    /// has unit RMS up to the eps-induced bias.
12519    #[test]
12520    fn pipelined_realize_rms_norm_last_dim() {
12521        let storage = fuel_memory::from_slice_cpu(&[
12522            3.0_f32, 4.0, // row 0: rms = sqrt(12.5)
12523            6.0, 8.0, // row 1: rms = sqrt(50.0) = 5*sqrt(2)
12524        ]);
12525        let graph = Arc::new(RwLock::new(Graph::new()));
12526        let (in_id, op_id) = {
12527            let mut g = graph.write().unwrap();
12528            let in_id = g.push(Node {
12529                op: Op::Const,
12530                inputs: vec![],
12531                shape: Shape::from_dims(&[2, 2]),
12532                dtype: DType::F32,
12533            });
12534            let op_id = g.push(Node {
12535                op: Op::Fused(
12536                    fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM,
12537                    fuel_graph::registry::FusedOpParams::RmsNormLastDim { eps: 0.0 },
12538                ),
12539                inputs: vec![in_id],
12540                shape: Shape::from_dims(&[2, 2]),
12541                dtype: DType::F32,
12542            });
12543            g.set_target_backend(op_id, BackendId::Cpu);
12544            (in_id, op_id)
12545        };
12546        let mut inputs = StorageCache::new();
12547        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12548        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12549        let guard = result_arc.read().unwrap();
12550        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12551            panic!("expected Cpu storage");
12552        };
12553        let result: &[f32] = c.as_slice().unwrap();
12554        // Row 0: rms = sqrt(12.5). Output = [3, 4] / sqrt(12.5).
12555        let rms0 = (12.5_f32).sqrt();
12556        assert!((result[0] - 3.0 / rms0).abs() < 1e-6);
12557        assert!((result[1] - 4.0 / rms0).abs() < 1e-6);
12558        // Row 1: rms = sqrt(50). Output = [6, 8] / sqrt(50).
12559        let rms1 = (50.0_f32).sqrt();
12560        assert!((result[2] - 6.0 / rms1).abs() < 1e-6);
12561        assert!((result[3] - 8.0 / rms1).abs() < 1e-6);
12562    }
12563
12564    /// E2E: LayerNormLastDim — each row's output has zero mean and
12565    /// unit variance.
12566    #[test]
12567    fn pipelined_realize_layer_norm_last_dim() {
12568        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 10.0, 20.0, 30.0]);
12569        let graph = Arc::new(RwLock::new(Graph::new()));
12570        let (in_id, op_id) = {
12571            let mut g = graph.write().unwrap();
12572            let in_id = g.push(Node {
12573                op: Op::Const,
12574                inputs: vec![],
12575                shape: Shape::from_dims(&[2, 3]),
12576                dtype: DType::F32,
12577            });
12578            let op_id = g.push(Node {
12579                op: Op::Fused(
12580                    fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM,
12581                    fuel_graph::registry::FusedOpParams::LayerNormLastDim { eps: 0.0 },
12582                ),
12583                inputs: vec![in_id],
12584                shape: Shape::from_dims(&[2, 3]),
12585                dtype: DType::F32,
12586            });
12587            g.set_target_backend(op_id, BackendId::Cpu);
12588            (in_id, op_id)
12589        };
12590        let mut inputs = StorageCache::new();
12591        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12592        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12593        let guard = result_arc.read().unwrap();
12594        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12595            panic!("expected Cpu storage");
12596        };
12597        let result: &[f32] = c.as_slice().unwrap();
12598        // Each row should have mean ~0 and var ~1.
12599        for row in 0..2 {
12600            let off = row * 3;
12601            let sum: f32 = result[off..off + 3].iter().sum();
12602            let mean = sum / 3.0;
12603            assert!(mean.abs() < 1e-6, "row {row} mean should be 0, got {mean}");
12604            let var: f32 = result[off..off + 3]
12605                .iter()
12606                .map(|v| (v - mean).powi(2))
12607                .sum::<f32>()
12608                / 3.0;
12609            assert!(
12610                (var - 1.0).abs() < 1e-6,
12611                "row {row} var should be 1, got {var}"
12612            );
12613        }
12614    }
12615
12616    /// E2E: SoftmaxLastDim on a 2-row input. Each row should sum
12617    /// to 1; uniform row gives uniform output.
12618    #[test]
12619    fn pipelined_realize_softmax_last_dim() {
12620        // Row 0: [1, 1, 1, 1] → uniform 0.25 each
12621        // Row 1: [0, 0, 0, 100] → effectively a one-hot at position 3
12622        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 100.0]);
12623        let graph = Arc::new(RwLock::new(Graph::new()));
12624        let (in_id, op_id) = {
12625            let mut g = graph.write().unwrap();
12626            let in_id = g.push(Node {
12627                op: Op::Const,
12628                inputs: vec![],
12629                shape: Shape::from_dims(&[2, 4]),
12630                dtype: DType::F32,
12631            });
12632            let op_id = g.push(Node {
12633                op: Op::Fused(
12634                    fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM,
12635                    fuel_graph::registry::FusedOpParams::SoftmaxLastDim,
12636                ),
12637                inputs: vec![in_id],
12638                shape: Shape::from_dims(&[2, 4]),
12639                dtype: DType::F32,
12640            });
12641            g.set_target_backend(op_id, BackendId::Cpu);
12642            (in_id, op_id)
12643        };
12644        let mut inputs = StorageCache::new();
12645        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12646        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12647        let guard = result_arc.read().unwrap();
12648        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12649            panic!("expected Cpu storage");
12650        };
12651        let result: &[f32] = c.as_slice().unwrap();
12652
12653        // Row 0: uniform 0.25
12654        for v in &result[..4] {
12655            assert!((v - 0.25).abs() < 1e-7);
12656        }
12657        // Row 1: positions 0..3 ≈ 0, position 4 (= last column) ≈ 1
12658        // (e^100 dominates).
12659        for v in &result[4..7] {
12660            assert!(
12661                *v < 1e-30,
12662                "row-1 leading positions should be near 0, got {v}"
12663            );
12664        }
12665        assert!(
12666            result[7] > 0.999,
12667            "row-1 last position should dominate, got {}",
12668            result[7]
12669        );
12670        // Each row sums to 1.
12671        let row0_sum: f32 = result[..4].iter().sum();
12672        let row1_sum: f32 = result[4..].iter().sum();
12673        assert!((row0_sum - 1.0).abs() < 1e-6);
12674        assert!((row1_sum - 1.0).abs() < 1e-6);
12675    }
12676
12677    /// E2E: Concat along inner dim — two [2, 3] tensors → [2, 6].
12678    #[test]
12679    fn pipelined_realize_concat_inner_dim() {
12680        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
12681        let b = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0, 9.0, 10.0, 11.0, 12.0]);
12682        let graph = Arc::new(RwLock::new(Graph::new()));
12683        let (a_id, b_id, c_id) = {
12684            let mut g = graph.write().unwrap();
12685            let a = g.push(Node {
12686                op: Op::Const,
12687                inputs: vec![],
12688                shape: Shape::from_dims(&[2, 3]),
12689                dtype: DType::F32,
12690            });
12691            let b = g.push(Node {
12692                op: Op::Const,
12693                inputs: vec![],
12694                shape: Shape::from_dims(&[2, 3]),
12695                dtype: DType::F32,
12696            });
12697            let c = g.push(Node {
12698                op: Op::Concat { dim: 1 },
12699                inputs: vec![a, b],
12700                shape: Shape::from_dims(&[2, 6]),
12701                dtype: DType::F32,
12702            });
12703            g.set_target_backend(c, BackendId::Cpu);
12704            (a, b, c)
12705        };
12706        let mut inputs = StorageCache::new();
12707        inputs.insert(a_id, Arc::new(RwLock::new(a)));
12708        inputs.insert(b_id, Arc::new(RwLock::new(b)));
12709        let (result_arc, result_layout) =
12710            PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12711        assert_eq!(result_layout.shape().dims(), &[2, 6]);
12712        let guard = result_arc.read().unwrap();
12713        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12714            panic!("expected Cpu storage");
12715        };
12716        assert_eq!(
12717            c.as_slice::<f32>().unwrap(),
12718            &[
12719                1.0, 2.0, 3.0, 7.0, 8.0, 9.0, 4.0, 5.0, 6.0, 10.0, 11.0, 12.0
12720            ]
12721        );
12722    }
12723
12724    /// E2E: Concat with three inputs along outer dim — verifies
12725    /// variable-arity input handling through the executor.
12726    #[test]
12727    fn pipelined_realize_concat_three_inputs_outer() {
12728        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
12729        let b = fuel_memory::from_slice_cpu(&[3.0_f32, 4.0]);
12730        let c = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0]);
12731        let graph = Arc::new(RwLock::new(Graph::new()));
12732        let (a_id, b_id, c_id, cat_id) = {
12733            let mut g = graph.write().unwrap();
12734            let a = g.push(Node {
12735                op: Op::Const,
12736                inputs: vec![],
12737                shape: Shape::from_dims(&[2]),
12738                dtype: DType::F32,
12739            });
12740            let b = g.push(Node {
12741                op: Op::Const,
12742                inputs: vec![],
12743                shape: Shape::from_dims(&[2]),
12744                dtype: DType::F32,
12745            });
12746            let c = g.push(Node {
12747                op: Op::Const,
12748                inputs: vec![],
12749                shape: Shape::from_dims(&[2]),
12750                dtype: DType::F32,
12751            });
12752            let cat = g.push(Node {
12753                op: Op::Concat { dim: 0 },
12754                inputs: vec![a, b, c],
12755                shape: Shape::from_dims(&[6]),
12756                dtype: DType::F32,
12757            });
12758            g.set_target_backend(cat, BackendId::Cpu);
12759            (a, b, c, cat)
12760        };
12761        let mut inputs = StorageCache::new();
12762        inputs.insert(a_id, Arc::new(RwLock::new(a)));
12763        inputs.insert(b_id, Arc::new(RwLock::new(b)));
12764        inputs.insert(c_id, Arc::new(RwLock::new(c)));
12765        let (result_arc, _) = PipelinedExecutor::realize(graph, cat_id, inputs).expect("realize");
12766        let guard = result_arc.read().unwrap();
12767        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12768            panic!("expected Cpu storage");
12769        };
12770        assert_eq!(
12771            c.as_slice::<f32>().unwrap(),
12772            &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
12773        );
12774    }
12775
12776    /// E2E: AddScalar — graph emits Op::AddScalar; the executor
12777    /// maps it to OpKind::Affine with mul=1, add=c.
12778    #[test]
12779    fn pipelined_realize_add_scalar() {
12780        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
12781        let graph = Arc::new(RwLock::new(Graph::new()));
12782        let (in_id, op_id) = {
12783            let mut g = graph.write().unwrap();
12784            let in_id = g.push(Node {
12785                op: Op::Const,
12786                inputs: vec![],
12787                shape: Shape::from_dims(&[3]),
12788                dtype: DType::F32,
12789            });
12790            let op_id = g.push(Node {
12791                op: Op::AddScalar(10.0),
12792                inputs: vec![in_id],
12793                shape: Shape::from_dims(&[3]),
12794                dtype: DType::F32,
12795            });
12796            g.set_target_backend(op_id, BackendId::Cpu);
12797            (in_id, op_id)
12798        };
12799        let mut inputs = StorageCache::new();
12800        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12801        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12802        let guard = result_arc.read().unwrap();
12803        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12804            panic!("expected Cpu storage");
12805        };
12806        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 12.0, 13.0]);
12807    }
12808
12809    /// E2E: Clamp — clamp values to [-2, 2].
12810    #[test]
12811    fn pipelined_realize_clamp() {
12812        let storage = fuel_memory::from_slice_cpu(&[-5.0_f32, 0.5, 100.0]);
12813        let graph = Arc::new(RwLock::new(Graph::new()));
12814        let (in_id, op_id) = {
12815            let mut g = graph.write().unwrap();
12816            let in_id = g.push(Node {
12817                op: Op::Const,
12818                inputs: vec![],
12819                shape: Shape::from_dims(&[3]),
12820                dtype: DType::F32,
12821            });
12822            let op_id = g.push(Node {
12823                op: Op::Clamp {
12824                    min: -2.0,
12825                    max: 2.0,
12826                },
12827                inputs: vec![in_id],
12828                shape: Shape::from_dims(&[3]),
12829                dtype: DType::F32,
12830            });
12831            g.set_target_backend(op_id, BackendId::Cpu);
12832            (in_id, op_id)
12833        };
12834        let mut inputs = StorageCache::new();
12835        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12836        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12837        let guard = result_arc.read().unwrap();
12838        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12839            panic!("expected Cpu storage");
12840        };
12841        assert_eq!(c.as_slice::<f32>().unwrap(), &[-2.0, 0.5, 2.0]);
12842    }
12843
12844    /// E2E: Maximum — elementwise tensor max.
12845    #[test]
12846    fn pipelined_realize_maximum_elementwise() {
12847        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, -3.0]);
12848        let rhs_storage = fuel_memory::from_slice_cpu(&[2.0_f32, 1.0, -1.0]);
12849        let graph = Arc::new(RwLock::new(Graph::new()));
12850        let (lhs_id, rhs_id, op_id) = {
12851            let mut g = graph.write().unwrap();
12852            let lhs = g.push(Node {
12853                op: Op::Const,
12854                inputs: vec![],
12855                shape: Shape::from_dims(&[3]),
12856                dtype: DType::F32,
12857            });
12858            let rhs = g.push(Node {
12859                op: Op::Const,
12860                inputs: vec![],
12861                shape: Shape::from_dims(&[3]),
12862                dtype: DType::F32,
12863            });
12864            let op = g.push(Node {
12865                op: Op::Maximum,
12866                inputs: vec![lhs, rhs],
12867                shape: Shape::from_dims(&[3]),
12868                dtype: DType::F32,
12869            });
12870            g.set_target_backend(op, BackendId::Cpu);
12871            (lhs, rhs, op)
12872        };
12873        let mut inputs = StorageCache::new();
12874        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
12875        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
12876        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12877        let guard = result_arc.read().unwrap();
12878        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12879            panic!("expected Cpu storage");
12880        };
12881        assert_eq!(c.as_slice::<f32>().unwrap(), &[2.0, 5.0, -1.0]);
12882    }
12883
12884    /// E2E: Const + Const + Conv2D — the 2×2 sum-kernel test from
12885    /// byte_kernels driven through the pipelined executor.
12886    #[test]
12887    fn pipelined_realize_conv2d_2x2_sum_kernel() {
12888        // x [1, 1, 3, 3]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
12889        // weight [1, 1, 2, 2]: all-ones
12890        // → out [1, 1, 2, 2]: [[12, 16], [24, 28]]
12891        let x_storage =
12892            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
12893        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
12894
12895        let graph = Arc::new(RwLock::new(Graph::new()));
12896        let (x_id, w_id, c_id) = {
12897            let mut g = graph.write().unwrap();
12898            let x = g.push(Node {
12899                op: Op::Const,
12900                inputs: vec![],
12901                shape: Shape::from_dims(&[1, 1, 3, 3]),
12902                dtype: DType::F32,
12903            });
12904            let w = g.push(Node {
12905                op: Op::Const,
12906                inputs: vec![],
12907                shape: Shape::from_dims(&[1, 1, 2, 2]),
12908                dtype: DType::F32,
12909            });
12910            let c = g.push(Node {
12911                op: Op::Fused(
12912                    fuel_graph::registry::FusedOps::CONV2D,
12913                    fuel_graph::registry::FusedOpParams::Conv2D {
12914                        stride: (1, 1),
12915                        padding: (0, 0),
12916                        groups: 1,
12917                    },
12918                ),
12919                inputs: vec![x, w],
12920                shape: Shape::from_dims(&[1, 1, 2, 2]),
12921                dtype: DType::F32,
12922            });
12923            g.set_target_backend(c, BackendId::Cpu);
12924            (x, w, c)
12925        };
12926        let mut inputs = StorageCache::new();
12927        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12928        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12929
12930        let (result_arc, result_layout) =
12931            PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12932        assert_eq!(result_layout.shape().dims(), &[1, 1, 2, 2]);
12933
12934        let guard = result_arc.read().unwrap();
12935        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12936            panic!("expected Cpu storage");
12937        };
12938        assert_eq!(c.as_slice::<f32>().unwrap(), &[12.0, 16.0, 24.0, 28.0]);
12939    }
12940
12941    /// E2E: Conv2D with bias (3 inputs).
12942    #[test]
12943    fn pipelined_realize_conv2d_with_bias() {
12944        let x_storage =
12945            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
12946        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
12947        let bias_storage = fuel_memory::from_slice_cpu(&[100.0_f32]);
12948
12949        let graph = Arc::new(RwLock::new(Graph::new()));
12950        let (x_id, w_id, b_id, c_id) = {
12951            let mut g = graph.write().unwrap();
12952            let x = g.push(Node {
12953                op: Op::Const,
12954                inputs: vec![],
12955                shape: Shape::from_dims(&[1, 1, 3, 3]),
12956                dtype: DType::F32,
12957            });
12958            let w = g.push(Node {
12959                op: Op::Const,
12960                inputs: vec![],
12961                shape: Shape::from_dims(&[1, 1, 2, 2]),
12962                dtype: DType::F32,
12963            });
12964            let b = g.push(Node {
12965                op: Op::Const,
12966                inputs: vec![],
12967                shape: Shape::from_dims(&[1]),
12968                dtype: DType::F32,
12969            });
12970            let c = g.push(Node {
12971                op: Op::Fused(
12972                    fuel_graph::registry::FusedOps::CONV2D,
12973                    fuel_graph::registry::FusedOpParams::Conv2D {
12974                        stride: (1, 1),
12975                        padding: (0, 0),
12976                        groups: 1,
12977                    },
12978                ),
12979                inputs: vec![x, w, b],
12980                shape: Shape::from_dims(&[1, 1, 2, 2]),
12981                dtype: DType::F32,
12982            });
12983            g.set_target_backend(c, BackendId::Cpu);
12984            (x, w, b, c)
12985        };
12986        let mut inputs = StorageCache::new();
12987        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12988        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12989        inputs.insert(b_id, Arc::new(RwLock::new(bias_storage)));
12990
12991        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12992        let guard = result_arc.read().unwrap();
12993        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12994            panic!("expected Cpu storage");
12995        };
12996        assert_eq!(c.as_slice::<f32>().unwrap(), &[112.0, 116.0, 124.0, 128.0]);
12997    }
12998
12999    /// E2E: Conv2D in F64 — same 2x2 sum-kernel test as F32, on doubles.
13000    #[test]
13001    fn pipelined_realize_conv2d_f64() {
13002        let x_storage =
13003            fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
13004        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f64, 1.0, 1.0, 1.0]);
13005
13006        let graph = Arc::new(RwLock::new(Graph::new()));
13007        let (x_id, w_id, c_id) = {
13008            let mut g = graph.write().unwrap();
13009            let x = g.push(Node {
13010                op: Op::Const,
13011                inputs: vec![],
13012                shape: Shape::from_dims(&[1, 1, 3, 3]),
13013                dtype: DType::F64,
13014            });
13015            let w = g.push(Node {
13016                op: Op::Const,
13017                inputs: vec![],
13018                shape: Shape::from_dims(&[1, 1, 2, 2]),
13019                dtype: DType::F64,
13020            });
13021            let c = g.push(Node {
13022                op: Op::Fused(
13023                    fuel_graph::registry::FusedOps::CONV2D,
13024                    fuel_graph::registry::FusedOpParams::Conv2D {
13025                        stride: (1, 1),
13026                        padding: (0, 0),
13027                        groups: 1,
13028                    },
13029                ),
13030                inputs: vec![x, w],
13031                shape: Shape::from_dims(&[1, 1, 2, 2]),
13032                dtype: DType::F64,
13033            });
13034            g.set_target_backend(c, BackendId::Cpu);
13035            (x, w, c)
13036        };
13037        let mut inputs = StorageCache::new();
13038        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
13039        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
13040        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
13041        let guard = result_arc.read().unwrap();
13042        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13043            panic!("expected Cpu storage");
13044        };
13045        assert_eq!(c.as_slice::<f64>().unwrap(), &[12.0, 16.0, 24.0, 28.0]);
13046    }
13047
13048    /// E2E: Conv2D in BF16 — f32-accumulator path. Tolerant compare.
13049    #[test]
13050    fn pipelined_realize_conv2d_bf16() {
13051        let x_data: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
13052            .iter()
13053            .map(|v| half::bf16::from_f32(*v))
13054            .collect();
13055        let w_data: Vec<half::bf16> = [1.0_f32, 1.0, 1.0, 1.0]
13056            .iter()
13057            .map(|v| half::bf16::from_f32(*v))
13058            .collect();
13059        let x_storage = fuel_memory::from_slice_cpu(&x_data);
13060        let w_storage = fuel_memory::from_slice_cpu(&w_data);
13061
13062        let graph = Arc::new(RwLock::new(Graph::new()));
13063        let (x_id, w_id, c_id) = {
13064            let mut g = graph.write().unwrap();
13065            let x = g.push(Node {
13066                op: Op::Const,
13067                inputs: vec![],
13068                shape: Shape::from_dims(&[1, 1, 3, 3]),
13069                dtype: DType::BF16,
13070            });
13071            let w = g.push(Node {
13072                op: Op::Const,
13073                inputs: vec![],
13074                shape: Shape::from_dims(&[1, 1, 2, 2]),
13075                dtype: DType::BF16,
13076            });
13077            let c = g.push(Node {
13078                op: Op::Fused(
13079                    fuel_graph::registry::FusedOps::CONV2D,
13080                    fuel_graph::registry::FusedOpParams::Conv2D {
13081                        stride: (1, 1),
13082                        padding: (0, 0),
13083                        groups: 1,
13084                    },
13085                ),
13086                inputs: vec![x, w],
13087                shape: Shape::from_dims(&[1, 1, 2, 2]),
13088                dtype: DType::BF16,
13089            });
13090            g.set_target_backend(c, BackendId::Cpu);
13091            (x, w, c)
13092        };
13093        let mut inputs = StorageCache::new();
13094        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
13095        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
13096        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
13097        let guard = result_arc.read().unwrap();
13098        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13099            panic!("expected Cpu storage");
13100        };
13101        let got: Vec<f32> = c
13102            .as_slice::<half::bf16>()
13103            .unwrap()
13104            .iter()
13105            .map(|v| v.to_f32())
13106            .collect();
13107        let want = [12.0_f32, 16.0, 24.0, 28.0];
13108        for (g, w) in got.iter().zip(want.iter()) {
13109            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
13110        }
13111    }
13112
13113    /// E2E: Conv2D in F16 — f32-accumulator path. Tolerant compare.
13114    #[test]
13115    fn pipelined_realize_conv2d_f16() {
13116        let x_data: Vec<half::f16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
13117            .iter()
13118            .map(|v| half::f16::from_f32(*v))
13119            .collect();
13120        let w_data: Vec<half::f16> = [1.0_f32, 1.0, 1.0, 1.0]
13121            .iter()
13122            .map(|v| half::f16::from_f32(*v))
13123            .collect();
13124        let x_storage = fuel_memory::from_slice_cpu(&x_data);
13125        let w_storage = fuel_memory::from_slice_cpu(&w_data);
13126
13127        let graph = Arc::new(RwLock::new(Graph::new()));
13128        let (x_id, w_id, c_id) = {
13129            let mut g = graph.write().unwrap();
13130            let x = g.push(Node {
13131                op: Op::Const,
13132                inputs: vec![],
13133                shape: Shape::from_dims(&[1, 1, 3, 3]),
13134                dtype: DType::F16,
13135            });
13136            let w = g.push(Node {
13137                op: Op::Const,
13138                inputs: vec![],
13139                shape: Shape::from_dims(&[1, 1, 2, 2]),
13140                dtype: DType::F16,
13141            });
13142            let c = g.push(Node {
13143                op: Op::Fused(
13144                    fuel_graph::registry::FusedOps::CONV2D,
13145                    fuel_graph::registry::FusedOpParams::Conv2D {
13146                        stride: (1, 1),
13147                        padding: (0, 0),
13148                        groups: 1,
13149                    },
13150                ),
13151                inputs: vec![x, w],
13152                shape: Shape::from_dims(&[1, 1, 2, 2]),
13153                dtype: DType::F16,
13154            });
13155            g.set_target_backend(c, BackendId::Cpu);
13156            (x, w, c)
13157        };
13158        let mut inputs = StorageCache::new();
13159        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
13160        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
13161        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
13162        let guard = result_arc.read().unwrap();
13163        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13164            panic!("expected Cpu storage");
13165        };
13166        let got: Vec<f32> = c
13167            .as_slice::<half::f16>()
13168            .unwrap()
13169            .iter()
13170            .map(|v| v.to_f32())
13171            .collect();
13172        let want = [12.0_f32, 16.0, 24.0, 28.0];
13173        for (g, w) in got.iter().zip(want.iter()) {
13174            assert!((g - w).abs() < 0.05, "got {got:?} want {want:?}");
13175        }
13176    }
13177
13178    /// E2E: Op::PagedAttn — F32, single-head, B=1, Sq=1.
13179    /// Same setup as the FlashAttn smoke test, but the K/V live in a
13180    /// paged cache that we look up via block_table.
13181    /// Layout:
13182    ///   block_size=2, num_blocks=1, max_blocks_per_seq=1.
13183    ///   k_cache shape [1, 2, 1, 2] = num_blocks × block_size × Hkv × D.
13184    ///   k_cache[block 0, slot 0, h 0] = [1, 0]
13185    ///   k_cache[block 0, slot 1, h 0] = [0, 1]
13186    ///   v_cache values: [10, 0] / [0, 10]
13187    ///   block_table[b=0, logical_block 0] = 0 (physical)
13188    ///   context_lens[0] = 2
13189    ///   q[0, 0, 0] = [2, 0]
13190    /// Causal is implicit (q_pos = ctx_len - Sq + sq = 2 - 1 + 0 = 1, both keys admissible).
13191    /// Same softmax math as FlashAttn → ~[8.808, 1.192].
13192    #[test]
13193    fn pipelined_realize_paged_attn_f32() {
13194        let q = fuel_memory::from_slice_cpu(&[2.0_f32, 0.0]);
13195        let k_cache = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13196        let v_cache = fuel_memory::from_slice_cpu(&[10.0_f32, 0.0, 0.0, 10.0]);
13197        let block_table_u32 = fuel_memory::Storage::new(
13198            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
13199                0_u32,
13200            ])),
13201            DType::U32,
13202        );
13203        let context_lens_u32 = fuel_memory::Storage::new(
13204            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
13205                2_u32,
13206            ])),
13207            DType::U32,
13208        );
13209        let graph = Arc::new(RwLock::new(Graph::new()));
13210        let (q_id, kc_id, vc_id, bt_id, cl_id, op_id) = {
13211            let mut g = graph.write().unwrap();
13212            let q = g.push(Node {
13213                op: Op::Const,
13214                inputs: vec![],
13215                shape: Shape::from_dims(&[1, 1, 1, 2]),
13216                dtype: DType::F32,
13217            });
13218            let kc = g.push(Node {
13219                op: Op::Const,
13220                inputs: vec![],
13221                shape: Shape::from_dims(&[1, 2, 1, 2]),
13222                dtype: DType::F32,
13223            });
13224            let vc = g.push(Node {
13225                op: Op::Const,
13226                inputs: vec![],
13227                shape: Shape::from_dims(&[1, 2, 1, 2]),
13228                dtype: DType::F32,
13229            });
13230            let bt = g.push(Node {
13231                op: Op::Const,
13232                inputs: vec![],
13233                shape: Shape::from_dims(&[1, 1]),
13234                dtype: DType::U32,
13235            });
13236            let cl = g.push(Node {
13237                op: Op::Const,
13238                inputs: vec![],
13239                shape: Shape::from_dims(&[1]),
13240                dtype: DType::U32,
13241            });
13242            let op = g.push(Node {
13243                op: Op::Fused(
13244                    fuel_graph::registry::FusedOps::PAGED_ATTN,
13245                    fuel_graph::registry::FusedOpParams::PagedAttn {
13246                        softmax_scale: 1.0,
13247                        block_size: 2,
13248                        softcap: None,
13249                    },
13250                ),
13251                inputs: vec![q, kc, vc, bt, cl],
13252                shape: Shape::from_dims(&[1, 1, 1, 2]),
13253                dtype: DType::F32,
13254            });
13255            g.set_target_backend(op, BackendId::Cpu);
13256            (q, kc, vc, bt, cl, op)
13257        };
13258        let mut inputs = StorageCache::new();
13259        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13260        inputs.insert(kc_id, Arc::new(RwLock::new(k_cache)));
13261        inputs.insert(vc_id, Arc::new(RwLock::new(v_cache)));
13262        inputs.insert(bt_id, Arc::new(RwLock::new(block_table_u32)));
13263        inputs.insert(cl_id, Arc::new(RwLock::new(context_lens_u32)));
13264        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13265        let guard = result_arc.read().unwrap();
13266        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13267            panic!("expected Cpu storage");
13268        };
13269        let r = c.as_slice::<f32>().unwrap();
13270        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
13271        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
13272        assert!(
13273            (r[0] - 10.0 * expected_p0).abs() < 1e-5,
13274            "row[0]: got {} expected {}",
13275            r[0],
13276            10.0 * expected_p0
13277        );
13278        assert!(
13279            (r[1] - 10.0 * expected_p1).abs() < 1e-5,
13280            "row[1]: got {} expected {}",
13281            r[1],
13282            10.0 * expected_p1
13283        );
13284    }
13285
13286    /// E2E: PagedAttn BF16 — same single-row test, tolerant.
13287    #[test]
13288    fn pipelined_realize_paged_attn_bf16() {
13289        let q_v: Vec<half::bf16> = [2.0_f32, 0.0]
13290            .iter()
13291            .map(|x| half::bf16::from_f32(*x))
13292            .collect();
13293        let kc_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0]
13294            .iter()
13295            .map(|x| half::bf16::from_f32(*x))
13296            .collect();
13297        let vc_v: Vec<half::bf16> = [10.0_f32, 0.0, 0.0, 10.0]
13298            .iter()
13299            .map(|x| half::bf16::from_f32(*x))
13300            .collect();
13301        let q = fuel_memory::from_slice_cpu(&q_v);
13302        let k_cache = fuel_memory::from_slice_cpu(&kc_v);
13303        let v_cache = fuel_memory::from_slice_cpu(&vc_v);
13304        let bt = fuel_memory::Storage::new(
13305            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
13306                0_u32,
13307            ])),
13308            DType::U32,
13309        );
13310        let cl = fuel_memory::Storage::new(
13311            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
13312                2_u32,
13313            ])),
13314            DType::U32,
13315        );
13316        let graph = Arc::new(RwLock::new(Graph::new()));
13317        let (q_id, kc_id, vc_id, bt_id, cl_id, op_id) = {
13318            let mut g = graph.write().unwrap();
13319            let q = g.push(Node {
13320                op: Op::Const,
13321                inputs: vec![],
13322                shape: Shape::from_dims(&[1, 1, 1, 2]),
13323                dtype: DType::BF16,
13324            });
13325            let kc = g.push(Node {
13326                op: Op::Const,
13327                inputs: vec![],
13328                shape: Shape::from_dims(&[1, 2, 1, 2]),
13329                dtype: DType::BF16,
13330            });
13331            let vc = g.push(Node {
13332                op: Op::Const,
13333                inputs: vec![],
13334                shape: Shape::from_dims(&[1, 2, 1, 2]),
13335                dtype: DType::BF16,
13336            });
13337            let bt = g.push(Node {
13338                op: Op::Const,
13339                inputs: vec![],
13340                shape: Shape::from_dims(&[1, 1]),
13341                dtype: DType::U32,
13342            });
13343            let cl = g.push(Node {
13344                op: Op::Const,
13345                inputs: vec![],
13346                shape: Shape::from_dims(&[1]),
13347                dtype: DType::U32,
13348            });
13349            let op = g.push(Node {
13350                op: Op::Fused(
13351                    fuel_graph::registry::FusedOps::PAGED_ATTN,
13352                    fuel_graph::registry::FusedOpParams::PagedAttn {
13353                        softmax_scale: 1.0,
13354                        block_size: 2,
13355                        softcap: None,
13356                    },
13357                ),
13358                inputs: vec![q, kc, vc, bt, cl],
13359                shape: Shape::from_dims(&[1, 1, 1, 2]),
13360                dtype: DType::BF16,
13361            });
13362            g.set_target_backend(op, BackendId::Cpu);
13363            (q, kc, vc, bt, cl, op)
13364        };
13365        let mut inputs = StorageCache::new();
13366        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13367        inputs.insert(kc_id, Arc::new(RwLock::new(k_cache)));
13368        inputs.insert(vc_id, Arc::new(RwLock::new(v_cache)));
13369        inputs.insert(bt_id, Arc::new(RwLock::new(bt)));
13370        inputs.insert(cl_id, Arc::new(RwLock::new(cl)));
13371        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13372        let guard = result_arc.read().unwrap();
13373        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13374            panic!("expected Cpu storage");
13375        };
13376        let got: Vec<f32> = c
13377            .as_slice::<half::bf16>()
13378            .unwrap()
13379            .iter()
13380            .map(|v| v.to_f32())
13381            .collect();
13382        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
13383        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
13384        let want = [10.0 * expected_p0, 10.0 * expected_p1];
13385        for (g, w) in got.iter().zip(want.iter()) {
13386            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
13387        }
13388    }
13389
13390    /// E2E: Op::FlashAttn — F32 single-head, single-batch, no mask.
13391    /// q = [[2.0, 0.0]], k = [[1.0, 0.0], [0.0, 1.0]], v = [[10, 0], [0, 10]]
13392    /// scale = 1.0
13393    /// scores = q · kᵀ = [2.0, 0.0]
13394    /// softmax = [e^2/(e^2+1), 1/(e^2+1)] ≈ [0.8808, 0.1192]
13395    /// out = softmax @ v = [10*0.8808, 10*0.1192] ≈ [8.808, 1.192]
13396    #[test]
13397    fn pipelined_realize_flash_attn_f32() {
13398        // [B=1, H=1, S=1or2, D=2]
13399        let q = fuel_memory::from_slice_cpu(&[2.0_f32, 0.0]);
13400        let k = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13401        let v = fuel_memory::from_slice_cpu(&[10.0_f32, 0.0, 0.0, 10.0]);
13402        let graph = Arc::new(RwLock::new(Graph::new()));
13403        let (q_id, k_id, v_id, op_id) = {
13404            let mut g = graph.write().unwrap();
13405            let q = g.push(Node {
13406                op: Op::Const,
13407                inputs: vec![],
13408                shape: Shape::from_dims(&[1, 1, 1, 2]),
13409                dtype: DType::F32,
13410            });
13411            let k = g.push(Node {
13412                op: Op::Const,
13413                inputs: vec![],
13414                shape: Shape::from_dims(&[1, 1, 2, 2]),
13415                dtype: DType::F32,
13416            });
13417            let v = g.push(Node {
13418                op: Op::Const,
13419                inputs: vec![],
13420                shape: Shape::from_dims(&[1, 1, 2, 2]),
13421                dtype: DType::F32,
13422            });
13423            let op = g.push(Node {
13424                op: Op::Fused(
13425                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13426                    fuel_graph::registry::FusedOpParams::FlashAttn {
13427                        softmax_scale: 1.0,
13428                        causal: false,
13429                        window_size_left: None,
13430                        window_size_right: None,
13431                        softcap: None,
13432                        k_len: None,
13433                    },
13434                ),
13435                inputs: vec![q, k, v],
13436                shape: Shape::from_dims(&[1, 1, 1, 2]),
13437                dtype: DType::F32,
13438            });
13439            g.set_target_backend(op, BackendId::Cpu);
13440            (q, k, v, op)
13441        };
13442        let mut inputs = StorageCache::new();
13443        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13444        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13445        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13446        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13447        let guard = result_arc.read().unwrap();
13448        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13449            panic!("expected Cpu storage");
13450        };
13451        let r = c.as_slice::<f32>().unwrap();
13452        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
13453        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
13454        assert!(
13455            (r[0] - 10.0 * expected_p0).abs() < 1e-5,
13456            "row[0]: got {} expected {}",
13457            r[0],
13458            10.0 * expected_p0
13459        );
13460        assert!(
13461            (r[1] - 10.0 * expected_p1).abs() < 1e-5,
13462            "row[1]: got {} expected {}",
13463            r[1],
13464            10.0 * expected_p1
13465        );
13466    }
13467
13468    /// E2E: FlashAttn with causal mask — second query position
13469    /// attends to both keys (positions 0 and 1), first only attends
13470    /// to key 0 (everything beyond is masked).
13471    #[test]
13472    fn pipelined_realize_flash_attn_causal_f32() {
13473        // q [1,1,2,2]: query 0 = [1, 0], query 1 = [0, 1]
13474        // k [1,1,2,2]: keys = [[1, 0], [0, 1]]
13475        // v [1,1,2,2]: values = [[5, 6], [7, 8]]
13476        // softmax_scale=1, causal:
13477        //   query 0: only key 0 admissible → out = v[0] = [5, 6]
13478        //   query 1: both admissible. scores = q1·k = [0, 1]
13479        //            softmax = [1/(e+1), e/(e+1)]
13480        //            out = scores · v = [(5)/(e+1) + 7e/(e+1), 6/(e+1) + 8e/(e+1)]
13481        let q = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13482        let k = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13483        let v = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0, 7.0, 8.0]);
13484        let graph = Arc::new(RwLock::new(Graph::new()));
13485        let (q_id, k_id, v_id, op_id) = {
13486            let mut g = graph.write().unwrap();
13487            let q = g.push(Node {
13488                op: Op::Const,
13489                inputs: vec![],
13490                shape: Shape::from_dims(&[1, 1, 2, 2]),
13491                dtype: DType::F32,
13492            });
13493            let k = g.push(Node {
13494                op: Op::Const,
13495                inputs: vec![],
13496                shape: Shape::from_dims(&[1, 1, 2, 2]),
13497                dtype: DType::F32,
13498            });
13499            let v = g.push(Node {
13500                op: Op::Const,
13501                inputs: vec![],
13502                shape: Shape::from_dims(&[1, 1, 2, 2]),
13503                dtype: DType::F32,
13504            });
13505            let op = g.push(Node {
13506                op: Op::Fused(
13507                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13508                    fuel_graph::registry::FusedOpParams::FlashAttn {
13509                        softmax_scale: 1.0,
13510                        causal: true,
13511                        window_size_left: None,
13512                        window_size_right: None,
13513                        softcap: None,
13514                        k_len: None,
13515                    },
13516                ),
13517                inputs: vec![q, k, v],
13518                shape: Shape::from_dims(&[1, 1, 2, 2]),
13519                dtype: DType::F32,
13520            });
13521            g.set_target_backend(op, BackendId::Cpu);
13522            (q, k, v, op)
13523        };
13524        let mut inputs = StorageCache::new();
13525        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13526        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13527        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13528        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13529        let guard = result_arc.read().unwrap();
13530        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13531            panic!("expected Cpu storage");
13532        };
13533        let r = c.as_slice::<f32>().unwrap();
13534        // Query 0 sees only key 0 → output = v[0]
13535        assert!((r[0] - 5.0).abs() < 1e-5, "got {}", r[0]);
13536        assert!((r[1] - 6.0).abs() < 1e-5, "got {}", r[1]);
13537        // Query 1 sees both. softmax([0, 1]) = [1/(e+1), e/(e+1)]
13538        let denom = (1.0_f32).exp() + 1.0;
13539        let expected_a = 5.0 / denom + 7.0 * (1.0_f32).exp() / denom;
13540        let expected_b = 6.0 / denom + 8.0 * (1.0_f32).exp() / denom;
13541        assert!(
13542            (r[2] - expected_a).abs() < 1e-5,
13543            "row1[0]: got {} expected {}",
13544            r[2],
13545            expected_a
13546        );
13547        assert!(
13548            (r[3] - expected_b).abs() < 1e-5,
13549            "row1[1]: got {} expected {}",
13550            r[3],
13551            expected_b
13552        );
13553    }
13554
13555    /// E2E: FlashAttn over a fixed-**capacity** K/V with a runtime
13556    /// `k_len` resolved through a `SymEnv` (Phase D symbolic extents).
13557    /// Only the first `k_len` rows are attended; trailing "poison" rows
13558    /// in the capacity buffer are ignored, and the causal mask is
13559    /// bottom-right-aligned at offset `k_len - Sq`. This is flash decode
13560    /// over a persistent KV-cache: K/V are `[.., max_seq, ..]` capacity
13561    /// and the live prefix grows per token.
13562    #[test]
13563    fn pipelined_realize_flash_attn_dynamic_k_len() {
13564        use fuel_ir::{DynScalar, SymId};
13565        // q [1,1,2,2]; K/V capacity [1,1,4,2]; bind k_len = 3 so row 3
13566        // (the "poison" row) is never attended.
13567        let q = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13568        let k = fuel_memory::from_slice_cpu(&[
13569            1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0, 100.0,
13570            100.0, // poison row 3 — must be ignored (k_len=3)
13571        ]);
13572        let v = fuel_memory::from_slice_cpu(&[
13573            5.0_f32, 6.0, 7.0, 8.0, 9.0, 10.0, 999.0,
13574            999.0, // poison row 3 — must be ignored
13575        ]);
13576        let sym = SymId(0);
13577        let graph = Arc::new(RwLock::new(Graph::new()));
13578        let (q_id, k_id, v_id, op_id) = {
13579            let mut g = graph.write().unwrap();
13580            let q = g.push(Node {
13581                op: Op::Const,
13582                inputs: vec![],
13583                shape: Shape::from_dims(&[1, 1, 2, 2]),
13584                dtype: DType::F32,
13585            });
13586            let k = g.push(Node {
13587                op: Op::Const,
13588                inputs: vec![],
13589                shape: Shape::from_dims(&[1, 1, 4, 2]),
13590                dtype: DType::F32,
13591            });
13592            let v = g.push(Node {
13593                op: Op::Const,
13594                inputs: vec![],
13595                shape: Shape::from_dims(&[1, 1, 4, 2]),
13596                dtype: DType::F32,
13597            });
13598            let op = g.push(Node {
13599                op: Op::Fused(
13600                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13601                    fuel_graph::registry::FusedOpParams::FlashAttn {
13602                        softmax_scale: 1.0,
13603                        causal: true,
13604                        window_size_left: None,
13605                        window_size_right: None,
13606                        softcap: None,
13607                        k_len: Some(DynScalar::Sym(sym)),
13608                    },
13609                ),
13610                inputs: vec![q, k, v],
13611                shape: Shape::from_dims(&[1, 1, 2, 2]),
13612                dtype: DType::F32,
13613            });
13614            g.set_target_backend(op, BackendId::Cpu);
13615            (q, k, v, op)
13616        };
13617        let mut inputs = StorageCache::new();
13618        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13619        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13620        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13621        let mut env = SymEnv::new();
13622        env.bind(sym, 3).unwrap();
13623        let (result_arc, _) = PipelinedExecutor::realize_with_env(graph, op_id, inputs, env)
13624            .expect("realize_with_env");
13625        let guard = result_arc.read().unwrap();
13626        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13627            panic!("expected Cpu storage");
13628        };
13629        let r = c.as_slice::<f32>().unwrap();
13630        let e = 1.0_f32.exp();
13631        // causal_offset = k_len - Sq = 3 - 2 = 1.
13632        // Query 0 (abs pos 1): keys {0,1}. scores [1,0] → softmax [e,1]/(e+1).
13633        let d0 = e + 1.0;
13634        let e0x = (5.0 * e + 7.0) / d0;
13635        let e0y = (6.0 * e + 8.0) / d0;
13636        // Query 1 (abs pos 2): keys {0,1,2}. scores [0,1,1] → [1,e,e]/(1+2e).
13637        let d1 = 1.0 + 2.0 * e;
13638        let e1x = (5.0 + 7.0 * e + 9.0 * e) / d1;
13639        let e1y = (6.0 + 8.0 * e + 10.0 * e) / d1;
13640        for (got, want) in r.iter().zip([e0x, e0y, e1x, e1y].iter()) {
13641            assert!(
13642                (got - want).abs() < 1e-4,
13643                "flash dyn k_len: got {got}, want {want} (full output {r:?}); \
13644                 a poison-contaminated value means the capacity rows past k_len leaked in",
13645            );
13646        }
13647    }
13648
13649    /// A flash `k_len` symbol unbound in the `SymEnv` surfaces a typed
13650    /// error at realize (never a panic).
13651    #[test]
13652    fn pipelined_realize_flash_attn_dynamic_k_len_unbound_errors() {
13653        use fuel_ir::{DynScalar, SymId};
13654        let q = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13655        let k = fuel_memory::from_slice_cpu(&[0.0_f32; 16]);
13656        let v = fuel_memory::from_slice_cpu(&[0.0_f32; 16]);
13657        let graph = Arc::new(RwLock::new(Graph::new()));
13658        let (q_id, k_id, v_id, op_id) = {
13659            let mut g = graph.write().unwrap();
13660            let q = g.push(Node {
13661                op: Op::Const,
13662                inputs: vec![],
13663                shape: Shape::from_dims(&[1, 1, 2, 2]),
13664                dtype: DType::F32,
13665            });
13666            let k = g.push(Node {
13667                op: Op::Const,
13668                inputs: vec![],
13669                shape: Shape::from_dims(&[1, 1, 4, 2]),
13670                dtype: DType::F32,
13671            });
13672            let v = g.push(Node {
13673                op: Op::Const,
13674                inputs: vec![],
13675                shape: Shape::from_dims(&[1, 1, 4, 2]),
13676                dtype: DType::F32,
13677            });
13678            let op = g.push(Node {
13679                op: Op::Fused(
13680                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13681                    fuel_graph::registry::FusedOpParams::FlashAttn {
13682                        softmax_scale: 1.0,
13683                        causal: true,
13684                        window_size_left: None,
13685                        window_size_right: None,
13686                        softcap: None,
13687                        k_len: Some(DynScalar::Sym(SymId(0))),
13688                    },
13689                ),
13690                inputs: vec![q, k, v],
13691                shape: Shape::from_dims(&[1, 1, 2, 2]),
13692                dtype: DType::F32,
13693            });
13694            g.set_target_backend(op, BackendId::Cpu);
13695            (q, k, v, op)
13696        };
13697        let mut inputs = StorageCache::new();
13698        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13699        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13700        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13701        // Empty env — the k_len symbol is unbound.
13702        let result = PipelinedExecutor::realize_with_env(graph, op_id, inputs, SymEnv::new());
13703        assert!(
13704            result.is_err(),
13705            "unbound flash k_len symbol must surface a typed error"
13706        );
13707    }
13708
13709    /// E2E: FlashAttn BF16 — same single-row test as f32, tolerant.
13710    #[test]
13711    fn pipelined_realize_flash_attn_bf16() {
13712        let q_v: Vec<half::bf16> = [2.0_f32, 0.0]
13713            .iter()
13714            .map(|x| half::bf16::from_f32(*x))
13715            .collect();
13716        let k_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0]
13717            .iter()
13718            .map(|x| half::bf16::from_f32(*x))
13719            .collect();
13720        let v_v: Vec<half::bf16> = [10.0_f32, 0.0, 0.0, 10.0]
13721            .iter()
13722            .map(|x| half::bf16::from_f32(*x))
13723            .collect();
13724        let q = fuel_memory::from_slice_cpu(&q_v);
13725        let k = fuel_memory::from_slice_cpu(&k_v);
13726        let v = fuel_memory::from_slice_cpu(&v_v);
13727        let graph = Arc::new(RwLock::new(Graph::new()));
13728        let (q_id, k_id, v_id, op_id) = {
13729            let mut g = graph.write().unwrap();
13730            let q = g.push(Node {
13731                op: Op::Const,
13732                inputs: vec![],
13733                shape: Shape::from_dims(&[1, 1, 1, 2]),
13734                dtype: DType::BF16,
13735            });
13736            let k = g.push(Node {
13737                op: Op::Const,
13738                inputs: vec![],
13739                shape: Shape::from_dims(&[1, 1, 2, 2]),
13740                dtype: DType::BF16,
13741            });
13742            let v = g.push(Node {
13743                op: Op::Const,
13744                inputs: vec![],
13745                shape: Shape::from_dims(&[1, 1, 2, 2]),
13746                dtype: DType::BF16,
13747            });
13748            let op = g.push(Node {
13749                op: Op::Fused(
13750                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13751                    fuel_graph::registry::FusedOpParams::FlashAttn {
13752                        softmax_scale: 1.0,
13753                        causal: false,
13754                        window_size_left: None,
13755                        window_size_right: None,
13756                        softcap: None,
13757                        k_len: None,
13758                    },
13759                ),
13760                inputs: vec![q, k, v],
13761                shape: Shape::from_dims(&[1, 1, 1, 2]),
13762                dtype: DType::BF16,
13763            });
13764            g.set_target_backend(op, BackendId::Cpu);
13765            (q, k, v, op)
13766        };
13767        let mut inputs = StorageCache::new();
13768        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13769        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13770        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13771        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13772        let guard = result_arc.read().unwrap();
13773        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13774            panic!("expected Cpu storage");
13775        };
13776        let got: Vec<f32> = c
13777            .as_slice::<half::bf16>()
13778            .unwrap()
13779            .iter()
13780            .map(|v| v.to_f32())
13781            .collect();
13782        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
13783        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
13784        let want = [10.0 * expected_p0, 10.0 * expected_p1];
13785        for (g, w) in got.iter().zip(want.iter()) {
13786            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
13787        }
13788    }
13789
13790    /// E2E: Op::FusedLinear — F32. a[1,2,3] @ b[1,3,2] + bias[2].
13791    /// a = [[[1,2,3],[4,5,6]]], b = [[[1,0],[0,1],[1,1]]], bias=[10,20]
13792    /// matmul = [[1+0+3, 0+2+3], [4+0+6, 0+5+6]] = [[4, 5], [10, 11]]
13793    /// + bias = [[14, 25], [20, 31]]
13794    #[test]
13795    fn pipelined_realize_fused_linear_f32() {
13796        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
13797        let b = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0]);
13798        let bias = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
13799        let graph = Arc::new(RwLock::new(Graph::new()));
13800        let (a_id, b_id, bias_id, op_id) = {
13801            let mut g = graph.write().unwrap();
13802            let a = g.push(Node {
13803                op: Op::Const,
13804                inputs: vec![],
13805                shape: Shape::from_dims(&[1, 2, 3]),
13806                dtype: DType::F32,
13807            });
13808            let b = g.push(Node {
13809                op: Op::Const,
13810                inputs: vec![],
13811                shape: Shape::from_dims(&[1, 3, 2]),
13812                dtype: DType::F32,
13813            });
13814            let bias = g.push(Node {
13815                op: Op::Const,
13816                inputs: vec![],
13817                shape: Shape::from_dims(&[2]),
13818                dtype: DType::F32,
13819            });
13820            let op = g.push(Node {
13821                op: Op::Fused(
13822                    fuel_graph::registry::FusedOps::FUSED_LINEAR,
13823                    fuel_graph::registry::FusedOpParams::FusedLinear,
13824                ),
13825                inputs: vec![a, b, bias],
13826                shape: Shape::from_dims(&[1, 2, 2]),
13827                dtype: DType::F32,
13828            });
13829            g.set_target_backend(op, BackendId::Cpu);
13830            (a, b, bias, op)
13831        };
13832        let mut inputs = StorageCache::new();
13833        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13834        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13835        inputs.insert(bias_id, Arc::new(RwLock::new(bias)));
13836        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13837        let guard = result_arc.read().unwrap();
13838        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13839            panic!("expected Cpu storage");
13840        };
13841        assert_eq!(c.as_slice::<f32>().unwrap(), &[14.0, 25.0, 20.0, 31.0]);
13842    }
13843
13844    /// E2E: FusedLinear F64 — same shape test on doubles.
13845    #[test]
13846    fn pipelined_realize_fused_linear_f64() {
13847        let a = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
13848        let b = fuel_memory::from_slice_cpu(&[1.0_f64, 0.0, 0.0, 1.0, 1.0, 1.0]);
13849        let bias = fuel_memory::from_slice_cpu(&[10.0_f64, 20.0]);
13850        let graph = Arc::new(RwLock::new(Graph::new()));
13851        let (a_id, b_id, bias_id, op_id) = {
13852            let mut g = graph.write().unwrap();
13853            let a = g.push(Node {
13854                op: Op::Const,
13855                inputs: vec![],
13856                shape: Shape::from_dims(&[1, 2, 3]),
13857                dtype: DType::F64,
13858            });
13859            let b = g.push(Node {
13860                op: Op::Const,
13861                inputs: vec![],
13862                shape: Shape::from_dims(&[1, 3, 2]),
13863                dtype: DType::F64,
13864            });
13865            let bias = g.push(Node {
13866                op: Op::Const,
13867                inputs: vec![],
13868                shape: Shape::from_dims(&[2]),
13869                dtype: DType::F64,
13870            });
13871            let op = g.push(Node {
13872                op: Op::Fused(
13873                    fuel_graph::registry::FusedOps::FUSED_LINEAR,
13874                    fuel_graph::registry::FusedOpParams::FusedLinear,
13875                ),
13876                inputs: vec![a, b, bias],
13877                shape: Shape::from_dims(&[1, 2, 2]),
13878                dtype: DType::F64,
13879            });
13880            g.set_target_backend(op, BackendId::Cpu);
13881            (a, b, bias, op)
13882        };
13883        let mut inputs = StorageCache::new();
13884        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13885        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13886        inputs.insert(bias_id, Arc::new(RwLock::new(bias)));
13887        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13888        let guard = result_arc.read().unwrap();
13889        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13890            panic!("expected Cpu storage");
13891        };
13892        assert_eq!(c.as_slice::<f64>().unwrap(), &[14.0, 25.0, 20.0, 31.0]);
13893    }
13894
13895    /// E2E (row 172 item 1): RowScaledMatMul F32 on CPU. a [1,2,3] @ b [1,3,2]
13896    /// = [[4, 5], [10, 11]]... computed by hand below; each row is scaled by its
13897    /// own entry of row_scale [1,2,1] = [2, 10]. A per-column or unscaled result
13898    /// would differ, so this discriminates the epilogue.
13899    #[test]
13900    fn pipelined_realize_row_scaled_matmul_f32() {
13901        // a rows: [1,2,3], [4,5,6]; b = [[1,0],[0,1],[1,1]].
13902        // a@b = [[1+3, 2+3], [4+6, 5+6]] = [[4, 5], [10, 11]].
13903        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
13904        let b = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0]);
13905        let scale = fuel_memory::from_slice_cpu(&[2.0_f32, 10.0]);
13906        let graph = Arc::new(RwLock::new(Graph::new()));
13907        let (a_id, b_id, s_id, op_id) = {
13908            let mut g = graph.write().unwrap();
13909            let mut konst = |dims: &[usize]| {
13910                g.push(Node {
13911                    op: Op::Const,
13912                    inputs: vec![],
13913                    shape: Shape::from_dims(dims),
13914                    dtype: DType::F32,
13915                })
13916            };
13917            let (a, b, s) = (konst(&[1, 2, 3]), konst(&[1, 3, 2]), konst(&[1, 2, 1]));
13918            let op = g.push(Node {
13919                op: Op::Fused(
13920                    fuel_graph::registry::FusedOps::ROW_SCALED_MATMUL,
13921                    fuel_graph::registry::FusedOpParams::RowScaledMatMul,
13922                ),
13923                inputs: vec![a, b, s],
13924                shape: Shape::from_dims(&[1, 2, 2]),
13925                dtype: DType::F32,
13926            });
13927            g.set_target_backend(op, BackendId::Cpu);
13928            (a, b, s, op)
13929        };
13930        let mut inputs = StorageCache::new();
13931        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13932        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13933        inputs.insert(s_id, Arc::new(RwLock::new(scale)));
13934        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13935        let guard = result_arc.read().unwrap();
13936        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13937            panic!("expected Cpu storage");
13938        };
13939        assert_eq!(c.as_slice::<f32>().unwrap(), &[8.0, 10.0, 100.0, 110.0]);
13940    }
13941
13942    /// E2E: FusedLinear BF16 — tolerant compare.
13943    #[test]
13944    fn pipelined_realize_fused_linear_bf16() {
13945        let a_v: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]
13946            .iter()
13947            .map(|x| half::bf16::from_f32(*x))
13948            .collect();
13949        let b_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0]
13950            .iter()
13951            .map(|x| half::bf16::from_f32(*x))
13952            .collect();
13953        let bias_v: Vec<half::bf16> = [10.0_f32, 20.0]
13954            .iter()
13955            .map(|x| half::bf16::from_f32(*x))
13956            .collect();
13957        let a = fuel_memory::from_slice_cpu(&a_v);
13958        let b = fuel_memory::from_slice_cpu(&b_v);
13959        let bias = fuel_memory::from_slice_cpu(&bias_v);
13960        let graph = Arc::new(RwLock::new(Graph::new()));
13961        let (a_id, b_id, bias_id, op_id) = {
13962            let mut g = graph.write().unwrap();
13963            let a = g.push(Node {
13964                op: Op::Const,
13965                inputs: vec![],
13966                shape: Shape::from_dims(&[1, 2, 3]),
13967                dtype: DType::BF16,
13968            });
13969            let b = g.push(Node {
13970                op: Op::Const,
13971                inputs: vec![],
13972                shape: Shape::from_dims(&[1, 3, 2]),
13973                dtype: DType::BF16,
13974            });
13975            let bias = g.push(Node {
13976                op: Op::Const,
13977                inputs: vec![],
13978                shape: Shape::from_dims(&[2]),
13979                dtype: DType::BF16,
13980            });
13981            let op = g.push(Node {
13982                op: Op::Fused(
13983                    fuel_graph::registry::FusedOps::FUSED_LINEAR,
13984                    fuel_graph::registry::FusedOpParams::FusedLinear,
13985                ),
13986                inputs: vec![a, b, bias],
13987                shape: Shape::from_dims(&[1, 2, 2]),
13988                dtype: DType::BF16,
13989            });
13990            g.set_target_backend(op, BackendId::Cpu);
13991            (a, b, bias, op)
13992        };
13993        let mut inputs = StorageCache::new();
13994        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13995        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13996        inputs.insert(bias_id, Arc::new(RwLock::new(bias)));
13997        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13998        let guard = result_arc.read().unwrap();
13999        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14000            panic!("expected Cpu storage");
14001        };
14002        let got: Vec<f32> = c
14003            .as_slice::<half::bf16>()
14004            .unwrap()
14005            .iter()
14006            .map(|v| v.to_f32())
14007            .collect();
14008        let want = [14.0_f32, 25.0, 20.0, 31.0];
14009        for (g, w) in got.iter().zip(want.iter()) {
14010            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
14011        }
14012    }
14013
14014    /// E2E: Op::ReduceSumTo — sum the leading axis of a [2,3] tensor.
14015    /// Input [[1,2,3],[4,5,6]] → output [5,7,9].
14016    #[test]
14017    fn pipelined_realize_reduce_sum_to_f32_drops_leading_axis() {
14018        let v = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14019        let graph = Arc::new(RwLock::new(Graph::new()));
14020        let (in_id, op_id) = {
14021            let mut g = graph.write().unwrap();
14022            let in_id = g.push(Node {
14023                op: Op::Const,
14024                inputs: vec![],
14025                shape: Shape::from_dims(&[2, 3]),
14026                dtype: DType::F32,
14027            });
14028            let op_id = g.push(Node {
14029                op: Op::ReduceSumTo(Shape::from_dims(&[3])),
14030                inputs: vec![in_id],
14031                shape: Shape::from_dims(&[3]),
14032                dtype: DType::F32,
14033            });
14034            g.set_target_backend(op_id, BackendId::Cpu);
14035            (in_id, op_id)
14036        };
14037        let mut inputs = StorageCache::new();
14038        inputs.insert(in_id, Arc::new(RwLock::new(v)));
14039        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14040        let guard = result_arc.read().unwrap();
14041        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14042            panic!("expected Cpu storage");
14043        };
14044        assert_eq!(c.as_slice::<f32>().unwrap(), &[5.0, 7.0, 9.0]);
14045    }
14046
14047    /// E2E: Op::ReduceSumTo — keep-dim with 1 in the middle.
14048    /// Input [2,3,4] → [2,1,4] sums along dim 1.
14049    #[test]
14050    fn pipelined_realize_reduce_sum_to_f32_keepdim_middle() {
14051        // [2,3,4]: layer 0 = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
14052        //          layer 1 = [[13..16],[17..20],[21..24]]
14053        let mut v: Vec<f32> = (1..=24).map(|x| x as f32).collect();
14054        let _ = &mut v;
14055        let s = fuel_memory::from_slice_cpu(&v);
14056        let graph = Arc::new(RwLock::new(Graph::new()));
14057        let (in_id, op_id) = {
14058            let mut g = graph.write().unwrap();
14059            let in_id = g.push(Node {
14060                op: Op::Const,
14061                inputs: vec![],
14062                shape: Shape::from_dims(&[2, 3, 4]),
14063                dtype: DType::F32,
14064            });
14065            let op_id = g.push(Node {
14066                op: Op::ReduceSumTo(Shape::from_dims(&[2, 1, 4])),
14067                inputs: vec![in_id],
14068                shape: Shape::from_dims(&[2, 1, 4]),
14069                dtype: DType::F32,
14070            });
14071            g.set_target_backend(op_id, BackendId::Cpu);
14072            (in_id, op_id)
14073        };
14074        let mut inputs = StorageCache::new();
14075        inputs.insert(in_id, Arc::new(RwLock::new(s)));
14076        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14077        let guard = result_arc.read().unwrap();
14078        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14079            panic!("expected Cpu storage");
14080        };
14081        // layer0 dim1-sum: col j = 1+5+9, 2+6+10, 3+7+11, 4+8+12 = [15,18,21,24]
14082        // layer1 dim1-sum: col j = 13+17+21, 14+18+22, 15+19+23, 16+20+24 = [51,54,57,60]
14083        assert_eq!(
14084            c.as_slice::<f32>().unwrap(),
14085            &[15.0, 18.0, 21.0, 24.0, 51.0, 54.0, 57.0, 60.0],
14086        );
14087    }
14088
14089    /// E2E: ReduceSumTo F64 — same drop-leading-axis test on doubles.
14090    #[test]
14091    fn pipelined_realize_reduce_sum_to_f64() {
14092        let v = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
14093        let graph = Arc::new(RwLock::new(Graph::new()));
14094        let (in_id, op_id) = {
14095            let mut g = graph.write().unwrap();
14096            let in_id = g.push(Node {
14097                op: Op::Const,
14098                inputs: vec![],
14099                shape: Shape::from_dims(&[2, 3]),
14100                dtype: DType::F64,
14101            });
14102            let op_id = g.push(Node {
14103                op: Op::ReduceSumTo(Shape::from_dims(&[3])),
14104                inputs: vec![in_id],
14105                shape: Shape::from_dims(&[3]),
14106                dtype: DType::F64,
14107            });
14108            g.set_target_backend(op_id, BackendId::Cpu);
14109            (in_id, op_id)
14110        };
14111        let mut inputs = StorageCache::new();
14112        inputs.insert(in_id, Arc::new(RwLock::new(v)));
14113        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14114        let guard = result_arc.read().unwrap();
14115        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14116            panic!("expected Cpu storage");
14117        };
14118        assert_eq!(c.as_slice::<f64>().unwrap(), &[5.0, 7.0, 9.0]);
14119    }
14120
14121    /// E2E: Op::ReduceMaxTo F32 — drop the leading axis with max-reduce.
14122    #[test]
14123    fn pipelined_realize_reduce_max_to_f32_drops_leading_axis() {
14124        // Input [2,3]: row 0 = [1, 7, 3], row 1 = [4, 2, 6]. Max along
14125        // dim 0: [4, 7, 6].
14126        let v = fuel_memory::from_slice_cpu(&[1.0_f32, 7.0, 3.0, 4.0, 2.0, 6.0]);
14127        let graph = Arc::new(RwLock::new(Graph::new()));
14128        let (in_id, op_id) = {
14129            let mut g = graph.write().unwrap();
14130            let in_id = g.push(Node {
14131                op: Op::Const,
14132                inputs: vec![],
14133                shape: Shape::from_dims(&[2, 3]),
14134                dtype: DType::F32,
14135            });
14136            let op_id = g.push(Node {
14137                op: Op::ReduceMaxTo(Shape::from_dims(&[3])),
14138                inputs: vec![in_id],
14139                shape: Shape::from_dims(&[3]),
14140                dtype: DType::F32,
14141            });
14142            g.set_target_backend(op_id, BackendId::Cpu);
14143            (in_id, op_id)
14144        };
14145        let mut inputs = StorageCache::new();
14146        inputs.insert(in_id, Arc::new(RwLock::new(v)));
14147        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14148        let guard = result_arc.read().unwrap();
14149        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14150            panic!("expected Cpu storage");
14151        };
14152        assert_eq!(c.as_slice::<f32>().unwrap(), &[4.0, 7.0, 6.0]);
14153    }
14154
14155    /// E2E: Op::ReduceMaxTo F32 — keep-dim with 1 in the trailing axis.
14156    /// Mirrors the SoftmaxLastDim lowering's max-side shape: input
14157    /// [..., last] → [..., 1].
14158    #[test]
14159    fn pipelined_realize_reduce_max_to_f32_keepdim_trailing() {
14160        // Input [2, 3]: row maxes = [3, 6].
14161        let v = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14162        let graph = Arc::new(RwLock::new(Graph::new()));
14163        let (in_id, op_id) = {
14164            let mut g = graph.write().unwrap();
14165            let in_id = g.push(Node {
14166                op: Op::Const,
14167                inputs: vec![],
14168                shape: Shape::from_dims(&[2, 3]),
14169                dtype: DType::F32,
14170            });
14171            let op_id = g.push(Node {
14172                op: Op::ReduceMaxTo(Shape::from_dims(&[2, 1])),
14173                inputs: vec![in_id],
14174                shape: Shape::from_dims(&[2, 1]),
14175                dtype: DType::F32,
14176            });
14177            g.set_target_backend(op_id, BackendId::Cpu);
14178            (in_id, op_id)
14179        };
14180        let mut inputs = StorageCache::new();
14181        inputs.insert(in_id, Arc::new(RwLock::new(v)));
14182        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14183        let guard = result_arc.read().unwrap();
14184        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14185            panic!("expected Cpu storage");
14186        };
14187        assert_eq!(c.as_slice::<f32>().unwrap(), &[3.0, 6.0]);
14188    }
14189
14190    /// E2E: ReduceSumTo BF16 — tolerant compare via f32-acc.
14191    #[test]
14192    fn pipelined_realize_reduce_sum_to_bf16() {
14193        let v: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]
14194            .iter()
14195            .map(|x| half::bf16::from_f32(*x))
14196            .collect();
14197        let s = fuel_memory::from_slice_cpu(&v);
14198        let graph = Arc::new(RwLock::new(Graph::new()));
14199        let (in_id, op_id) = {
14200            let mut g = graph.write().unwrap();
14201            let in_id = g.push(Node {
14202                op: Op::Const,
14203                inputs: vec![],
14204                shape: Shape::from_dims(&[2, 3]),
14205                dtype: DType::BF16,
14206            });
14207            let op_id = g.push(Node {
14208                op: Op::ReduceSumTo(Shape::from_dims(&[3])),
14209                inputs: vec![in_id],
14210                shape: Shape::from_dims(&[3]),
14211                dtype: DType::BF16,
14212            });
14213            g.set_target_backend(op_id, BackendId::Cpu);
14214            (in_id, op_id)
14215        };
14216        let mut inputs = StorageCache::new();
14217        inputs.insert(in_id, Arc::new(RwLock::new(s)));
14218        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14219        let guard = result_arc.read().unwrap();
14220        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14221            panic!("expected Cpu storage");
14222        };
14223        let got: Vec<f32> = c
14224            .as_slice::<half::bf16>()
14225            .unwrap()
14226            .iter()
14227            .map(|v| v.to_f32())
14228            .collect();
14229        let want = [5.0_f32, 7.0, 9.0];
14230        for (g, w) in got.iter().zip(want.iter()) {
14231            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
14232        }
14233    }
14234
14235    /// E2E: Op::ConvTranspose2D — F32 spread test.
14236    /// x = [[1, 2], [3, 4]] shape [1,1,2,2], all-ones kernel
14237    /// shape [1,1,2,2], stride=1, padding=0, dilation=1, no bias.
14238    /// Expected output (3x3):
14239    ///   [[1,  3, 2],
14240    ///    [4, 10, 6],
14241    ///    [3,  7, 4]]
14242    #[test]
14243    fn pipelined_realize_conv_transpose2d_f32() {
14244        let x_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
14245        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
14246        let graph = Arc::new(RwLock::new(Graph::new()));
14247        let (x_id, w_id, c_id) = {
14248            let mut g = graph.write().unwrap();
14249            let x = g.push(Node {
14250                op: Op::Const,
14251                inputs: vec![],
14252                shape: Shape::from_dims(&[1, 1, 2, 2]),
14253                dtype: DType::F32,
14254            });
14255            let w = g.push(Node {
14256                op: Op::Const,
14257                inputs: vec![],
14258                shape: Shape::from_dims(&[1, 1, 2, 2]),
14259                dtype: DType::F32,
14260            });
14261            let c = g.push(Node {
14262                op: Op::Fused(
14263                    fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D,
14264                    fuel_graph::registry::FusedOpParams::ConvTranspose2D {
14265                        stride: (1, 1),
14266                        padding: (0, 0),
14267                        output_padding: (0, 0),
14268                        dilation: (1, 1),
14269                        groups: 1,
14270                    },
14271                ),
14272                inputs: vec![x, w],
14273                shape: Shape::from_dims(&[1, 1, 3, 3]),
14274                dtype: DType::F32,
14275            });
14276            g.set_target_backend(c, BackendId::Cpu);
14277            (x, w, c)
14278        };
14279        let mut inputs = StorageCache::new();
14280        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
14281        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
14282        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
14283        let guard = result_arc.read().unwrap();
14284        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14285            panic!("expected Cpu storage");
14286        };
14287        assert_eq!(
14288            c.as_slice::<f32>().unwrap(),
14289            &[1.0, 3.0, 2.0, 4.0, 10.0, 6.0, 3.0, 7.0, 4.0],
14290        );
14291    }
14292
14293    /// E2E: ConvTranspose2D F64 — same shape test.
14294    #[test]
14295    fn pipelined_realize_conv_transpose2d_f64() {
14296        let x_storage = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0]);
14297        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f64, 1.0, 1.0, 1.0]);
14298        let graph = Arc::new(RwLock::new(Graph::new()));
14299        let (x_id, w_id, c_id) = {
14300            let mut g = graph.write().unwrap();
14301            let x = g.push(Node {
14302                op: Op::Const,
14303                inputs: vec![],
14304                shape: Shape::from_dims(&[1, 1, 2, 2]),
14305                dtype: DType::F64,
14306            });
14307            let w = g.push(Node {
14308                op: Op::Const,
14309                inputs: vec![],
14310                shape: Shape::from_dims(&[1, 1, 2, 2]),
14311                dtype: DType::F64,
14312            });
14313            let c = g.push(Node {
14314                op: Op::Fused(
14315                    fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D,
14316                    fuel_graph::registry::FusedOpParams::ConvTranspose2D {
14317                        stride: (1, 1),
14318                        padding: (0, 0),
14319                        output_padding: (0, 0),
14320                        dilation: (1, 1),
14321                        groups: 1,
14322                    },
14323                ),
14324                inputs: vec![x, w],
14325                shape: Shape::from_dims(&[1, 1, 3, 3]),
14326                dtype: DType::F64,
14327            });
14328            g.set_target_backend(c, BackendId::Cpu);
14329            (x, w, c)
14330        };
14331        let mut inputs = StorageCache::new();
14332        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
14333        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
14334        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
14335        let guard = result_arc.read().unwrap();
14336        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14337            panic!("expected Cpu storage");
14338        };
14339        assert_eq!(
14340            c.as_slice::<f64>().unwrap(),
14341            &[1.0, 3.0, 2.0, 4.0, 10.0, 6.0, 3.0, 7.0, 4.0],
14342        );
14343    }
14344
14345    /// E2E: ConvTranspose2D BF16 — tolerant compare via f32-acc.
14346    #[test]
14347    fn pipelined_realize_conv_transpose2d_bf16() {
14348        let x: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0]
14349            .iter()
14350            .map(|v| half::bf16::from_f32(*v))
14351            .collect();
14352        let w: Vec<half::bf16> = [1.0_f32, 1.0, 1.0, 1.0]
14353            .iter()
14354            .map(|v| half::bf16::from_f32(*v))
14355            .collect();
14356        let x_storage = fuel_memory::from_slice_cpu(&x);
14357        let w_storage = fuel_memory::from_slice_cpu(&w);
14358        let graph = Arc::new(RwLock::new(Graph::new()));
14359        let (x_id, w_id, c_id) = {
14360            let mut g = graph.write().unwrap();
14361            let x = g.push(Node {
14362                op: Op::Const,
14363                inputs: vec![],
14364                shape: Shape::from_dims(&[1, 1, 2, 2]),
14365                dtype: DType::BF16,
14366            });
14367            let w = g.push(Node {
14368                op: Op::Const,
14369                inputs: vec![],
14370                shape: Shape::from_dims(&[1, 1, 2, 2]),
14371                dtype: DType::BF16,
14372            });
14373            let c = g.push(Node {
14374                op: Op::Fused(
14375                    fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D,
14376                    fuel_graph::registry::FusedOpParams::ConvTranspose2D {
14377                        stride: (1, 1),
14378                        padding: (0, 0),
14379                        output_padding: (0, 0),
14380                        dilation: (1, 1),
14381                        groups: 1,
14382                    },
14383                ),
14384                inputs: vec![x, w],
14385                shape: Shape::from_dims(&[1, 1, 3, 3]),
14386                dtype: DType::BF16,
14387            });
14388            g.set_target_backend(c, BackendId::Cpu);
14389            (x, w, c)
14390        };
14391        let mut inputs = StorageCache::new();
14392        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
14393        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
14394        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
14395        let guard = result_arc.read().unwrap();
14396        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14397            panic!("expected Cpu storage");
14398        };
14399        let got: Vec<f32> = c
14400            .as_slice::<half::bf16>()
14401            .unwrap()
14402            .iter()
14403            .map(|v| v.to_f32())
14404            .collect();
14405        let want = [1.0_f32, 3.0, 2.0, 4.0, 10.0, 6.0, 3.0, 7.0, 4.0];
14406        for (g, w) in got.iter().zip(want.iter()) {
14407            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
14408        }
14409    }
14410
14411    /// E2E: GQA-style matmul through the pipelined executor.
14412    /// lhs has 4 batch heads, rhs has 2; each rhs head is shared
14413    /// by 2 lhs heads. Output's batch dim follows lhs (4 heads).
14414    #[test]
14415    fn pipelined_realize_matmul_gqa() {
14416        // lhs [4, 1, 2]: heads 0..3 are [[1,2]], [[3,4]], [[5,6]], [[7,8]]
14417        // rhs [2, 2, 1]: heads 0,1 are [[1],[0]], [[0],[1]]
14418        // Expected out [4, 1, 1]: [[1]], [[3]], [[6]], [[8]]
14419        let lhs_storage =
14420            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]);
14421        let rhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
14422
14423        let graph = Arc::new(RwLock::new(Graph::new()));
14424        let (lhs_id, rhs_id, mm_id) = {
14425            let mut g = graph.write().unwrap();
14426            let lhs = g.push(Node {
14427                op: Op::Const,
14428                inputs: vec![],
14429                shape: Shape::from_dims(&[4, 1, 2]),
14430                dtype: DType::F32,
14431            });
14432            let rhs = g.push(Node {
14433                op: Op::Const,
14434                inputs: vec![],
14435                shape: Shape::from_dims(&[2, 2, 1]),
14436                dtype: DType::F32,
14437            });
14438            let mm = g.push(Node {
14439                op: Op::MatMul,
14440                inputs: vec![lhs, rhs],
14441                shape: Shape::from_dims(&[4, 1, 1]),
14442                dtype: DType::F32,
14443            });
14444            g.set_target_backend(mm, BackendId::Cpu);
14445            (lhs, rhs, mm)
14446        };
14447        let mut inputs = StorageCache::new();
14448        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
14449        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
14450
14451        let (result_arc, result_layout) =
14452            PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
14453        assert_eq!(result_layout.shape().dims(), &[4, 1, 1]);
14454
14455        let guard = result_arc.read().unwrap();
14456        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14457            panic!("expected Cpu storage");
14458        };
14459        assert_eq!(c.as_slice::<f32>().unwrap(), &[1.0, 3.0, 6.0, 8.0]);
14460    }
14461
14462    /// E2E: matmul with a transposed rhs — proves stage 3+4
14463    /// integration carries through the matmul path. The transpose
14464    /// is metadata-only; auto-Contiguize materializes the strided
14465    /// rhs before the matmul kernel sees it.
14466    #[test]
14467    fn pipelined_realize_matmul_with_transposed_rhs() {
14468        // lhs [[1, 2], [3, 4]], rhs original [[5, 6], [7, 8]]
14469        // rhs.T = [[5, 7], [6, 8]]
14470        // lhs @ rhs.T = [[1*5+2*6, 1*7+2*8], [3*5+4*6, 3*7+4*8]]
14471        //             = [[17, 23], [39, 53]]
14472        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
14473        let rhs_storage = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0, 7.0, 8.0]);
14474
14475        let graph = Arc::new(RwLock::new(Graph::new()));
14476        let (lhs_id, rhs_id, t_id, mm_id) = {
14477            let mut g = graph.write().unwrap();
14478            let lhs = g.push(Node {
14479                op: Op::Const,
14480                inputs: vec![],
14481                shape: Shape::from_dims(&[2, 2]),
14482                dtype: DType::F32,
14483            });
14484            let rhs = g.push(Node {
14485                op: Op::Const,
14486                inputs: vec![],
14487                shape: Shape::from_dims(&[2, 2]),
14488                dtype: DType::F32,
14489            });
14490            let t = g.push(Node {
14491                op: Op::Transpose,
14492                inputs: vec![rhs],
14493                shape: Shape::from_dims(&[2, 2]),
14494                dtype: DType::F32,
14495            });
14496            let mm = g.push(Node {
14497                op: Op::MatMul,
14498                inputs: vec![lhs, t],
14499                shape: Shape::from_dims(&[2, 2]),
14500                dtype: DType::F32,
14501            });
14502            g.set_target_backend(mm, BackendId::Cpu);
14503            (lhs, rhs, t, mm)
14504        };
14505        let _ = t_id;
14506        let mut inputs = StorageCache::new();
14507        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
14508        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
14509
14510        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
14511        let guard = result_arc.read().unwrap();
14512        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14513            panic!("expected Cpu storage");
14514        };
14515        assert_eq!(c.as_slice::<f32>().unwrap(), &[17.0, 23.0, 39.0, 53.0]);
14516    }
14517
14518    /// E2E: Const + Reshape — contiguous-input reshape is zero
14519    /// copy. The output Storage Arc is the input Arc; the layout
14520    /// is contiguous in the new shape.
14521    #[test]
14522    fn pipelined_realize_reshape_zero_copy_when_contiguous() {
14523        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14524        let graph = Arc::new(RwLock::new(Graph::new()));
14525        let (in_id, r_id) = {
14526            let mut g = graph.write().unwrap();
14527            let in_id = g.push(Node {
14528                op: Op::Const,
14529                inputs: vec![],
14530                shape: Shape::from_dims(&[2, 3]),
14531                dtype: DType::F32,
14532            });
14533            let r_id = g.push(Node {
14534                op: Op::Reshape(Shape::from_dims(&[3, 2])),
14535                inputs: vec![in_id],
14536                shape: Shape::from_dims(&[3, 2]),
14537                dtype: DType::F32,
14538            });
14539            (in_id, r_id)
14540        };
14541        let mut inputs = StorageCache::new();
14542        let in_arc = Arc::new(RwLock::new(storage));
14543        inputs.insert(in_id, Arc::clone(&in_arc));
14544
14545        let (result_arc, result_layout) =
14546            PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
14547
14548        // Zero copy — same Arc.
14549        assert!(
14550            Arc::ptr_eq(&result_arc, &in_arc),
14551            "contiguous reshape must zero-copy"
14552        );
14553        assert_eq!(result_layout.shape().dims(), &[3, 2]);
14554        assert!(result_layout.is_contiguous());
14555
14556        // Bytes are unchanged; just reinterpreted as [3, 2].
14557        let guard = result_arc.read().unwrap();
14558        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14559            panic!("expected Cpu storage");
14560        };
14561        assert_eq!(
14562            c.as_slice::<f32>().unwrap(),
14563            &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
14564        );
14565    }
14566
14567    /// E2E: Const + Transpose + Reshape — reshape on a strided
14568    /// input auto-contiguizes the bytes. Output Arc is fresh
14569    /// (NOT the input Arc); the bytes are the materialized
14570    /// transposed layout.
14571    #[test]
14572    fn pipelined_realize_reshape_materializes_when_strided() {
14573        // shape [2, 3]: 1 2 3 / 4 5 6
14574        // Transpose → [3, 2] strided
14575        // Reshape → [6] (forces materialization)
14576        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14577        let graph = Arc::new(RwLock::new(Graph::new()));
14578        let (in_id, t_id, r_id) = {
14579            let mut g = graph.write().unwrap();
14580            let in_id = g.push(Node {
14581                op: Op::Const,
14582                inputs: vec![],
14583                shape: Shape::from_dims(&[2, 3]),
14584                dtype: DType::F32,
14585            });
14586            let t_id = g.push(Node {
14587                op: Op::Transpose,
14588                inputs: vec![in_id],
14589                shape: Shape::from_dims(&[3, 2]),
14590                dtype: DType::F32,
14591            });
14592            let r_id = g.push(Node {
14593                op: Op::Reshape(Shape::from_dims(&[6])),
14594                inputs: vec![t_id],
14595                shape: Shape::from_dims(&[6]),
14596                dtype: DType::F32,
14597            });
14598            (in_id, t_id, r_id)
14599        };
14600        let _ = t_id;
14601        let mut inputs = StorageCache::new();
14602        let in_arc = Arc::new(RwLock::new(storage));
14603        inputs.insert(in_id, Arc::clone(&in_arc));
14604
14605        let (result_arc, result_layout) =
14606            PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
14607
14608        // Fresh Arc — auto-contiguize allocated new bytes.
14609        assert!(!Arc::ptr_eq(&result_arc, &in_arc));
14610        assert_eq!(result_layout.shape().dims(), &[6]);
14611        assert!(result_layout.is_contiguous());
14612
14613        // Materialized transposed bytes flattened: [1, 4, 2, 5, 3, 6].
14614        let guard = result_arc.read().unwrap();
14615        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14616            panic!("expected Cpu storage");
14617        };
14618        assert_eq!(
14619            c.as_slice::<f32>().unwrap(),
14620            &[1.0, 4.0, 2.0, 5.0, 3.0, 6.0]
14621        );
14622    }
14623
14624    /// E2E: Const + Transpose + SumDim — exercises stage 3
14625    /// (metadata-only Transpose, strided intermediate Layout) +
14626    /// stage 4 (auto-Contiguize before reduce kernel) end-to-end.
14627    /// The transpose makes the intermediate non-contiguous; the
14628    /// reduce wrapper would have failed in stage 2; with stage 4's
14629    /// auto-Contiguize, the kernel sees the materialized contiguous
14630    /// transposed bytes and produces the right answer.
14631    #[test]
14632    fn pipelined_realize_transpose_then_sum_dim_e2e() {
14633        // shape [2, 3]: rows are [1, 2, 3], [4, 5, 6]
14634        // After transpose: shape [3, 2], rows are [1, 4], [2, 5], [3, 6]
14635        // After SumDim(1): shape [3], values [5, 7, 9]
14636        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14637        let graph = Arc::new(RwLock::new(Graph::new()));
14638        let (in_id, t_id, sum_id) = {
14639            let mut g = graph.write().unwrap();
14640            let in_id = g.push(Node {
14641                op: Op::Const,
14642                inputs: vec![],
14643                shape: Shape::from_dims(&[2, 3]),
14644                dtype: DType::F32,
14645            });
14646            let t_id = g.push(Node {
14647                op: Op::Transpose,
14648                inputs: vec![in_id],
14649                shape: Shape::from_dims(&[3, 2]),
14650                dtype: DType::F32,
14651            });
14652            let sum_id = g.push(Node {
14653                op: Op::SumDim(1),
14654                inputs: vec![t_id],
14655                shape: Shape::from_dims(&[3]),
14656                dtype: DType::F32,
14657            });
14658            // Only the reduce kernel runs on the backend; the
14659            // transpose is metadata-only and doesn't need a target.
14660            g.set_target_backend(sum_id, BackendId::Cpu);
14661            (in_id, t_id, sum_id)
14662        };
14663        let _ = t_id;
14664        let mut inputs = StorageCache::new();
14665        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14666
14667        let (result_arc, result_layout) =
14668            PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
14669
14670        // The reduce output is contiguous (kernel-produced).
14671        assert_eq!(result_layout.shape().dims(), &[3]);
14672        assert!(result_layout.is_contiguous());
14673
14674        let guard = result_arc.read().unwrap();
14675        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14676            panic!("expected Cpu storage");
14677        };
14678        let typed: &[f32] = c.as_slice().unwrap();
14679        assert_eq!(typed, &[5.0, 7.0, 9.0]);
14680    }
14681
14682    /// E2E: Const + BroadcastTo + Add — broadcast intermediate
14683    /// auto-contiguizes for the Add kernel; the result is the
14684    /// expected sum.
14685    #[test]
14686    fn pipelined_realize_broadcast_then_add_e2e() {
14687        // shape [3]: [10, 20, 30]
14688        // BroadcastTo [2, 3]: [[10, 20, 30], [10, 20, 30]]
14689        // Plus shape [2, 3]: [[1, 2, 3], [4, 5, 6]]
14690        // Result: [[11, 22, 33], [14, 25, 36]]
14691        let bc_input = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
14692        let plus_input = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14693        let graph = Arc::new(RwLock::new(Graph::new()));
14694        let (bc_in_id, plus_in_id, b_id, add_id) = {
14695            let mut g = graph.write().unwrap();
14696            let bc_in = g.push(Node {
14697                op: Op::Const,
14698                inputs: vec![],
14699                shape: Shape::from_dims(&[3]),
14700                dtype: DType::F32,
14701            });
14702            let plus_in = g.push(Node {
14703                op: Op::Const,
14704                inputs: vec![],
14705                shape: Shape::from_dims(&[2, 3]),
14706                dtype: DType::F32,
14707            });
14708            let b = g.push(Node {
14709                op: Op::BroadcastTo(Shape::from_dims(&[2, 3])),
14710                inputs: vec![bc_in],
14711                shape: Shape::from_dims(&[2, 3]),
14712                dtype: DType::F32,
14713            });
14714            let add = g.push(Node {
14715                op: Op::Add,
14716                inputs: vec![b, plus_in],
14717                shape: Shape::from_dims(&[2, 3]),
14718                dtype: DType::F32,
14719            });
14720            g.set_target_backend(add, BackendId::Cpu);
14721            (bc_in, plus_in, b, add)
14722        };
14723        let _ = b_id;
14724        let mut inputs = StorageCache::new();
14725        inputs.insert(bc_in_id, Arc::new(RwLock::new(bc_input)));
14726        inputs.insert(plus_in_id, Arc::new(RwLock::new(plus_input)));
14727
14728        let (result_arc, _result_layout) =
14729            PipelinedExecutor::realize(graph, add_id, inputs).expect("realize");
14730        let guard = result_arc.read().unwrap();
14731        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14732            panic!("expected Cpu storage");
14733        };
14734        let typed: &[f32] = c.as_slice().unwrap();
14735        assert_eq!(typed, &[11.0, 22.0, 33.0, 14.0, 25.0, 36.0]);
14736    }
14737
14738    /// E2E: Const + SumDim — verifies that `OpParams::Reduce`
14739    /// flows from the graph (input shape via `op_to_op_params`)
14740    /// through compile_one and reaches the reduce kernel.
14741    #[test]
14742    fn pipelined_realize_sum_dim() {
14743        // shape [2, 3]; reduce dim 1 → output shape [2]
14744        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14745        let graph = Arc::new(RwLock::new(Graph::new()));
14746        let (in_id, sum_id) = {
14747            let mut g = graph.write().unwrap();
14748            let in_id = g.push(Node {
14749                op: Op::Const,
14750                inputs: vec![],
14751                shape: Shape::from_dims(&[2, 3]),
14752                dtype: DType::F32,
14753            });
14754            let sum_id = g.push(Node {
14755                op: Op::SumDim(1),
14756                inputs: vec![in_id],
14757                shape: Shape::from_dims(&[2]),
14758                dtype: DType::F32,
14759            });
14760            g.set_target_backend(sum_id, BackendId::Cpu);
14761            (in_id, sum_id)
14762        };
14763        let mut inputs = StorageCache::new();
14764        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14765
14766        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
14767        let guard = result_arc.read().unwrap();
14768        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14769            let typed: &[f32] = c.as_slice().unwrap();
14770            assert_eq!(typed, &[6.0, 15.0]);
14771        }
14772    }
14773
14774    /// E2E: SumAll on a rank-3 input, exercising the all-dims branch
14775    /// of `op_to_op_params` (every dim reduced, rank-0 output).
14776    #[test]
14777    fn pipelined_realize_sum_all_rank3() {
14778        let data: Vec<f32> = (1..=24).map(|x| x as f32).collect();
14779        let storage = fuel_memory::from_slice_cpu(&data);
14780        let graph = Arc::new(RwLock::new(Graph::new()));
14781        let (in_id, sum_id) = {
14782            let mut g = graph.write().unwrap();
14783            let in_id = g.push(Node {
14784                op: Op::Const,
14785                inputs: vec![],
14786                shape: Shape::from_dims(&[2, 3, 4]),
14787                dtype: DType::F32,
14788            });
14789            let sum_id = g.push(Node {
14790                op: Op::SumAll,
14791                inputs: vec![in_id],
14792                shape: Shape::from_dims(&[]),
14793                dtype: DType::F32,
14794            });
14795            g.set_target_backend(sum_id, BackendId::Cpu);
14796            (in_id, sum_id)
14797        };
14798        let mut inputs = StorageCache::new();
14799        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14800
14801        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
14802        let guard = result_arc.read().unwrap();
14803        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14804            let typed: &[f32] = c.as_slice().unwrap();
14805            // 1 + 2 + ... + 24 = 300
14806            assert_eq!(typed, &[300.0]);
14807        }
14808    }
14809
14810    /// E2E: MaxDim + MeanDim chained — verifies all four reduce
14811    /// OpKinds reach their wrappers via the OpParams plumbing.
14812    #[test]
14813    fn pipelined_realize_max_then_mean() {
14814        // shape [2, 3], MaxDim(1) → [2], MeanDim(0) → []
14815        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 9.0, 3.0, 4.0, 2.0, 8.0]);
14816        let graph = Arc::new(RwLock::new(Graph::new()));
14817        let (in_id, mean_id) = {
14818            let mut g = graph.write().unwrap();
14819            let in_id = g.push(Node {
14820                op: Op::Const,
14821                inputs: vec![],
14822                shape: Shape::from_dims(&[2, 3]),
14823                dtype: DType::F32,
14824            });
14825            let max_id = g.push(Node {
14826                op: Op::MaxDim(1),
14827                inputs: vec![in_id],
14828                shape: Shape::from_dims(&[2]),
14829                dtype: DType::F32,
14830            });
14831            let mean_id = g.push(Node {
14832                op: Op::MeanDim(0),
14833                inputs: vec![max_id],
14834                shape: Shape::from_dims(&[]),
14835                dtype: DType::F32,
14836            });
14837            g.set_target_backend(max_id, BackendId::Cpu);
14838            g.set_target_backend(mean_id, BackendId::Cpu);
14839            (in_id, mean_id)
14840        };
14841        let mut inputs = StorageCache::new();
14842        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14843
14844        let (result_arc, _) = PipelinedExecutor::realize(graph, mean_id, inputs).expect("realize");
14845        let guard = result_arc.read().unwrap();
14846        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14847            let typed: &[f32] = c.as_slice().unwrap();
14848            // MaxDim(1) on [[1,9,3],[4,2,8]] = [9, 8]; MeanDim(0) = 8.5
14849            assert_eq!(typed, &[8.5]);
14850        }
14851    }
14852
14853    /// E2E: Sigmoid + Silu — exercises two of the more compositional
14854    /// new unary kernels through the pipelined executor. Verifies
14855    /// the additional `op_to_op_kind` mappings reach the right
14856    /// dispatch wrappers.
14857    #[test]
14858    fn pipelined_realize_sigmoid_then_silu() {
14859        let storage = fuel_memory::from_slice_cpu(&[0.0_f32, 1.0, -1.0]);
14860        let graph = Arc::new(RwLock::new(Graph::new()));
14861        let (in_id, sig_id, silu_id) = {
14862            let mut g = graph.write().unwrap();
14863            let in_id = g.push(Node {
14864                op: Op::Const,
14865                inputs: vec![],
14866                shape: Shape::from_dims(&[3]),
14867                dtype: DType::F32,
14868            });
14869            let sig_id = g.push(Node {
14870                op: Op::Sigmoid,
14871                inputs: vec![in_id],
14872                shape: Shape::from_dims(&[3]),
14873                dtype: DType::F32,
14874            });
14875            // Silu of the sigmoid output — chains to confirm cache flow.
14876            let silu_id = g.push(Node {
14877                op: Op::Silu,
14878                inputs: vec![sig_id],
14879                shape: Shape::from_dims(&[3]),
14880                dtype: DType::F32,
14881            });
14882            g.set_target_backend(sig_id, BackendId::Cpu);
14883            g.set_target_backend(silu_id, BackendId::Cpu);
14884            (in_id, sig_id, silu_id)
14885        };
14886        let _ = sig_id;
14887        let mut inputs = StorageCache::new();
14888        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14889
14890        let (result_arc, _) = PipelinedExecutor::realize(graph, silu_id, inputs).expect("realize");
14891        let guard = result_arc.read().unwrap();
14892        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14893            let typed: &[f32] = c.as_slice().unwrap();
14894            // sigmoid(0) = 0.5; silu(0.5) = 0.5 * sigmoid(0.5) ≈ 0.3112
14895            assert!((typed[0] - 0.5 * (1.0 / (1.0 + (-0.5_f32).exp()))).abs() < 1e-6);
14896        }
14897    }
14898
14899    /// E2E: chained unary ops — Const + Sqr + Sqrt should be a noop
14900    /// for non-negative inputs. Exercises the cache reuse path.
14901    #[test]
14902    fn pipelined_realize_chained_unary_sqr_then_sqrt() {
14903        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 4.0, 9.0]);
14904        let graph = Arc::new(RwLock::new(Graph::new()));
14905        let (in_id, sqrt_id) = {
14906            let mut g = graph.write().unwrap();
14907            let in_id = g.push(Node {
14908                op: Op::Const,
14909                inputs: vec![],
14910                shape: Shape::from_dims(&[3]),
14911                dtype: DType::F32,
14912            });
14913            let sqr_id = g.push(Node {
14914                op: Op::Sqr,
14915                inputs: vec![in_id],
14916                shape: Shape::from_dims(&[3]),
14917                dtype: DType::F32,
14918            });
14919            let sqrt_id = g.push(Node {
14920                op: Op::Sqrt,
14921                inputs: vec![sqr_id],
14922                shape: Shape::from_dims(&[3]),
14923                dtype: DType::F32,
14924            });
14925            g.set_target_backend(sqr_id, BackendId::Cpu);
14926            g.set_target_backend(sqrt_id, BackendId::Cpu);
14927            (in_id, sqrt_id)
14928        };
14929        let mut inputs = StorageCache::new();
14930        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14931
14932        let (result_arc, _) = PipelinedExecutor::realize(graph, sqrt_id, inputs).expect("realize");
14933        let guard = result_arc.read().unwrap();
14934        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14935            let typed: &[f32] = c.as_slice().unwrap();
14936            // sqrt(sqr(x)) == |x| == x for non-negative inputs.
14937            assert_eq!(typed, &[1.0, 4.0, 9.0]);
14938        }
14939    }
14940
14941    /// Multi-stage pipelined: Const + Const + Add + Add (chain of
14942    /// two adds). Tests that work items are processed in topo order
14943    /// and intermediate results are cached and reused.
14944    #[test]
14945    fn pipelined_realize_chained_adds() {
14946        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
14947        let b_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
14948        let c_storage = fuel_memory::from_slice_cpu(&[100.0_f32, 200.0]);
14949
14950        let graph = Arc::new(RwLock::new(Graph::new()));
14951        let (a_id, b_id, c_id, ab_id, abc_id) = {
14952            let mut g = graph.write().unwrap();
14953            let a = g.push(Node {
14954                op: Op::Const,
14955                inputs: vec![],
14956                shape: Shape::from_dims(&[2]),
14957                dtype: DType::F32,
14958            });
14959            let b = g.push(Node {
14960                op: Op::Const,
14961                inputs: vec![],
14962                shape: Shape::from_dims(&[2]),
14963                dtype: DType::F32,
14964            });
14965            let c = g.push(Node {
14966                op: Op::Const,
14967                inputs: vec![],
14968                shape: Shape::from_dims(&[2]),
14969                dtype: DType::F32,
14970            });
14971            let ab = g.push(Node {
14972                op: Op::Add,
14973                inputs: vec![a, b],
14974                shape: Shape::from_dims(&[2]),
14975                dtype: DType::F32,
14976            });
14977            let abc = g.push(Node {
14978                op: Op::Add,
14979                inputs: vec![ab, c],
14980                shape: Shape::from_dims(&[2]),
14981                dtype: DType::F32,
14982            });
14983            g.set_target_backend(ab, BackendId::Cpu);
14984            g.set_target_backend(abc, BackendId::Cpu);
14985            (a, b, c, ab, abc)
14986        };
14987
14988        let mut inputs = StorageCache::new();
14989        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
14990        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
14991        inputs.insert(c_id, Arc::new(RwLock::new(c_storage)));
14992
14993        let (result_arc, _) = PipelinedExecutor::realize(graph, abc_id, inputs).expect("realize");
14994        // Suppress unused warning for the intermediate id.
14995        let _ = ab_id;
14996
14997        let guard = result_arc.read().unwrap();
14998        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14999            let typed: &[f32] = c.as_slice().unwrap();
15000            // (1+10) + 100 = 111;  (2+20) + 200 = 222.
15001            assert_eq!(typed, &[111.0, 222.0]);
15002        }
15003    }
15004
15005    /// E2E: triu(diagonal=0) on a 3×3 matrix.
15006    /// Input:  [1 2 3 / 4 5 6 / 7 8 9]
15007    /// Output: [1 2 3 / 0 5 6 / 0 0 9]
15008    #[test]
15009    fn pipelined_realize_triu_3x3_diag0() {
15010        let storage =
15011            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
15012        let graph = Arc::new(RwLock::new(Graph::new()));
15013        let (in_id, out_id) = {
15014            let mut g = graph.write().unwrap();
15015            let in_id = g.push(Node {
15016                op: Op::Const,
15017                inputs: vec![],
15018                shape: Shape::from_dims(&[3, 3]),
15019                dtype: DType::F32,
15020            });
15021            let out_id = g.push(Node {
15022                op: Op::Triu { diagonal: 0 },
15023                inputs: vec![in_id],
15024                shape: Shape::from_dims(&[3, 3]),
15025                dtype: DType::F32,
15026            });
15027            g.set_target_backend(out_id, BackendId::Cpu);
15028            (in_id, out_id)
15029        };
15030        let mut inputs = StorageCache::new();
15031        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
15032        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
15033        let guard = result_arc.read().unwrap();
15034        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15035            panic!("expected Cpu storage");
15036        };
15037        let out: &[f32] = c.as_slice().unwrap();
15038        assert_eq!(out, &[1.0, 2.0, 3.0, 0.0, 5.0, 6.0, 0.0, 0.0, 9.0,]);
15039    }
15040
15041    /// E2E: tril(diagonal=0) on a 3×3 matrix — the canonical causal mask.
15042    /// Output: [1 0 0 / 4 5 0 / 7 8 9]
15043    #[test]
15044    fn pipelined_realize_tril_3x3_diag0_causal_mask() {
15045        let storage =
15046            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
15047        let graph = Arc::new(RwLock::new(Graph::new()));
15048        let (in_id, out_id) = {
15049            let mut g = graph.write().unwrap();
15050            let in_id = g.push(Node {
15051                op: Op::Const,
15052                inputs: vec![],
15053                shape: Shape::from_dims(&[3, 3]),
15054                dtype: DType::F32,
15055            });
15056            let out_id = g.push(Node {
15057                op: Op::Tril { diagonal: 0 },
15058                inputs: vec![in_id],
15059                shape: Shape::from_dims(&[3, 3]),
15060                dtype: DType::F32,
15061            });
15062            g.set_target_backend(out_id, BackendId::Cpu);
15063            (in_id, out_id)
15064        };
15065        let mut inputs = StorageCache::new();
15066        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
15067        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
15068        let guard = result_arc.read().unwrap();
15069        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15070            panic!("expected Cpu storage");
15071        };
15072        let out: &[f32] = c.as_slice().unwrap();
15073        assert_eq!(out, &[1.0, 0.0, 0.0, 4.0, 5.0, 0.0, 7.0, 8.0, 9.0,]);
15074    }
15075
15076    /// E2E: log_softmax over a 2×3 input. Rows are [1,2,3] and [3,2,1].
15077    /// log_softmax(row) = row - max - log(sum exp(row - max)).
15078    /// Row 0: max=3, exp(-2)+exp(-1)+exp(0) = 0.135+0.368+1.0 = 1.503;
15079    ///        log(1.503) ≈ 0.4076; out = [1-3-0.4076, 2-3-0.4076, 3-3-0.4076]
15080    ///                              = [-2.4076, -1.4076, -0.4076]
15081    /// Row 1 is row 0 reversed: [-0.4076, -1.4076, -2.4076].
15082    #[test]
15083    fn pipelined_realize_log_softmax_last_dim() {
15084        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 3.0, 2.0, 1.0]);
15085        let graph = Arc::new(RwLock::new(Graph::new()));
15086        let (in_id, out_id) = {
15087            let mut g = graph.write().unwrap();
15088            let in_id = g.push(Node {
15089                op: Op::Const,
15090                inputs: vec![],
15091                shape: Shape::from_dims(&[2, 3]),
15092                dtype: DType::F32,
15093            });
15094            let out_id = g.push(Node {
15095                op: Op::LogSoftmaxLastDim,
15096                inputs: vec![in_id],
15097                shape: Shape::from_dims(&[2, 3]),
15098                dtype: DType::F32,
15099            });
15100            g.set_target_backend(out_id, BackendId::Cpu);
15101            (in_id, out_id)
15102        };
15103        let mut inputs = StorageCache::new();
15104        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
15105        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
15106        let guard = result_arc.read().unwrap();
15107        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15108            panic!("expected Cpu storage");
15109        };
15110        let out: &[f32] = c.as_slice().unwrap();
15111        let expected = [
15112            -2.407_606,
15113            -1.4076059,
15114            -0.40760595_f32,
15115            -0.40760595,
15116            -1.4076059,
15117            -2.407_606,
15118        ];
15119        for (a, b) in out.iter().zip(expected.iter()) {
15120            assert!((a - b).abs() < 1e-5, "log_softmax mismatch: {a} vs {b}");
15121        }
15122        // The exp() of the output should sum to 1 per row.
15123        for row in out.chunks(3) {
15124            let sum: f32 = row.iter().map(|x| x.exp()).sum();
15125            assert!(
15126                (sum - 1.0).abs() < 1e-5,
15127                "softmax(log_softmax) row sum != 1: {sum}"
15128            );
15129        }
15130    }
15131
15132    // --- side-effect roots + destructive cleanup (9c Phase B) -----
15133
15134    /// Side-effect roots get merged into the realize walk even when
15135    /// not reachable from the user's targets. The production trigger
15136    /// is `Op::Release` (emitted by `ResidencyEvictionRule`); this
15137    /// test uses that exact shape.
15138    ///
15139    /// Graph: Const(a) + Const(b) → Add (user target); separate
15140    /// Const(c) → Release(c) (side-effect root, not reachable from
15141    /// Add). After realize_many on `[add]`, the Add should be in the
15142    /// output AND the Release should have fired (verified by the
15143    /// fact that realize succeeded — Op::Release in the walk used to
15144    /// fail compilation pre-Phase B+).
15145    #[test]
15146    fn pipelined_realize_merges_op_release_side_effect_root() {
15147        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
15148        let b = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
15149        let c = fuel_memory::from_slice_cpu(&[100.0_f32, 200.0]);
15150        let graph = Arc::new(RwLock::new(Graph::new()));
15151        let (a_id, b_id, c_id, add_id, release_id) = {
15152            let mut g = graph.write().unwrap();
15153            let a = g.push(Node {
15154                op: Op::Const,
15155                inputs: vec![],
15156                shape: Shape::from_dims(&[2]),
15157                dtype: DType::F32,
15158            });
15159            let b = g.push(Node {
15160                op: Op::Const,
15161                inputs: vec![],
15162                shape: Shape::from_dims(&[2]),
15163                dtype: DType::F32,
15164            });
15165            // c is NOT reachable from add; its Release IS marked as
15166            // a side-effect root.
15167            let c = g.push(Node {
15168                op: Op::Const,
15169                inputs: vec![],
15170                shape: Shape::from_dims(&[2]),
15171                dtype: DType::F32,
15172            });
15173            let add = g.push(Node {
15174                op: Op::Add,
15175                inputs: vec![a, b],
15176                shape: Shape::from_dims(&[2]),
15177                dtype: DType::F32,
15178            });
15179            // Production shape: Op::Release on c, marked as
15180            // side-effect root so it fires even though no graph
15181            // node reads its output.
15182            let release = g.push(Node {
15183                op: Op::Release,
15184                inputs: vec![c],
15185                shape: Shape::from_dims(&[0]),
15186                dtype: DType::F32,
15187            });
15188            g.set_target_backend(add, BackendId::Cpu);
15189            g.set_target_backend(release, BackendId::Cpu);
15190            g.add_side_effect_root(release);
15191            (a, b, c, add, release)
15192        };
15193        let mut inputs = StorageCache::new();
15194        inputs.insert(a_id, Arc::new(RwLock::new(a)));
15195        inputs.insert(b_id, Arc::new(RwLock::new(b)));
15196        let c_arc = Arc::new(RwLock::new(c));
15197        let c_arc_external = Arc::clone(&c_arc);
15198        inputs.insert(c_id, c_arc);
15199
15200        // Only `add` is requested. The Release on c is a side-effect
15201        // root that must still fire.
15202        let out = PipelinedExecutor::realize_many(graph, &[add_id], inputs).expect("realize_many");
15203        assert_eq!(out.len(), 1);
15204        let add_guard = out[0].0.read().unwrap();
15205        let fuel_memory::BackendStorage::Cpu(arr) = &add_guard.inner else {
15206            panic!()
15207        };
15208        assert_eq!(arr.as_slice::<f32>().unwrap(), &[11.0, 22.0]);
15209
15210        // The Release's destructive_input cleanup dropped the
15211        // cache's Arc to c. The only Arc to c that survives is the
15212        // external one this test holds — confirms the eviction
15213        // actually freed the cache's reference.
15214        assert_eq!(
15215            Arc::strong_count(&c_arc_external),
15216            1,
15217            "Op::Release should evict the cache's Arc to its source; \
15218             only the test's external clone should remain",
15219        );
15220        let _ = release_id;
15221    }
15222
15223    /// `compile_one` emits a `WorkItemKind::ReleaseMarker` for
15224    /// `Op::Release` with `destructive_input = Some(0)`. Verify
15225    /// the WorkItem shape via a direct compile_one call.
15226    #[test]
15227    fn compile_one_emits_release_marker_with_destructive_input() {
15228        let graph_rc = Arc::new(RwLock::new(Graph::new()));
15229        let (src_id, release_id) = {
15230            let mut g = graph_rc.write().unwrap();
15231            let src = g.push(Node {
15232                op: Op::Const,
15233                inputs: vec![],
15234                shape: Shape::from_dims(&[2]),
15235                dtype: DType::F32,
15236            });
15237            let release = g.push(Node {
15238                op: Op::Release,
15239                inputs: vec![src],
15240                shape: Shape::from_dims(&[0]),
15241                dtype: DType::F32,
15242            });
15243            g.set_target_backend(release, BackendId::Cpu);
15244            (src, release)
15245        };
15246        let g = graph_rc.read().unwrap();
15247        let bindings = crate::dispatch::global_bindings();
15248        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
15249        let item = compile_one(
15250            &g,
15251            release_id,
15252            &mut layout_cache,
15253            &bindings,
15254            &SymEnv::default(),
15255        )
15256        .expect("compile_one Op::Release");
15257        assert!(matches!(item.kind, WorkItemKind::ReleaseMarker));
15258        assert_eq!(item.destructive_input, Some(0));
15259        assert_eq!(item.inputs, vec![src_id]);
15260        assert_eq!(
15261            item.elem_count, 0,
15262            "Release output is the zero-element marker"
15263        );
15264    }
15265
15266    // --- Op::Move (executor-unification Session 1, gap 13) --------
15267
15268    /// `compile_one` emits a `WorkItemKind::Move` for `Op::Move` with
15269    /// `destructive_input = Some(0)` and a resolved transfer kernel
15270    /// (binding-table lookup at `(OpKind::Copy, [dt, dt], source
15271    /// backend)` — Move shares Op::Copy's data-movement kernel).
15272    #[test]
15273    fn compile_one_emits_move_with_destructive_input() {
15274        let graph_rc = Arc::new(RwLock::new(Graph::new()));
15275        let (src_id, move_id) = {
15276            let mut g = graph_rc.write().unwrap();
15277            let src = g.push(Node {
15278                op: Op::Const,
15279                inputs: vec![],
15280                shape: Shape::from_dims(&[2]),
15281                dtype: DType::F32,
15282            });
15283            let mv = g.push(Node {
15284                op: Op::Move {
15285                    target: DeviceLocation::Cpu,
15286                },
15287                inputs: vec![src],
15288                shape: Shape::from_dims(&[2]),
15289                dtype: DType::F32,
15290            });
15291            g.set_target_backend(mv, BackendId::Cpu);
15292            (src, mv)
15293        };
15294        let g = graph_rc.read().unwrap();
15295        let bindings = crate::dispatch::global_bindings();
15296        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
15297        let item = compile_one(
15298            &g,
15299            move_id,
15300            &mut layout_cache,
15301            &bindings,
15302            &SymEnv::default(),
15303        )
15304        .expect("compile_one Op::Move");
15305        assert!(matches!(
15306            item.kind,
15307            WorkItemKind::Move {
15308                target_location: DeviceLocation::Cpu
15309            },
15310        ));
15311        assert_eq!(item.destructive_input, Some(0), "Move destroys its source");
15312        assert_eq!(item.inputs, vec![src_id]);
15313        assert!(
15314            item.compiled.is_some(),
15315            "Move resolves a transfer kernel at (OpKind::Copy, [dt, dt], source backend)",
15316        );
15317    }
15318
15319    // --- runtime fused op (JIT-adopted Tier-2 kernel) --------------
15320
15321    /// `compile_one` resolves an `Op::Fused(fid, Runtime)` node with
15322    /// `fid.is_runtime()` from the runtime-kernel sidecar (never the
15323    /// binding table): `WorkItemKind::Kernel`, `compiled.op ==
15324    /// OpKind::RuntimeFused`, and the kernel pointer is exactly the one
15325    /// `adopt_runtime_fused` bound.
15326    #[test]
15327    fn compile_one_resolves_runtime_fused_from_the_sidecar() {
15328        fn sentinel_kernel(
15329            _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
15330            _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
15331            _layouts: &[Layout],
15332            _params: &crate::kernel::OpParams,
15333        ) -> Result<()> {
15334            Ok(())
15335        }
15336        // A region shape unique to this test (process-global sidecar; see
15337        // runtime_fused_pathfinder's tests for the collision rationale).
15338        let region = fuel_graph::jit::PatternNode::Op {
15339            op: fuel_graph::jit::OpTag::Exp,
15340            attrs: fuel_graph::jit::OpAttrs::default(),
15341            operands: vec![fuel_graph::jit::PatternNode::Op {
15342                op: fuel_graph::jit::OpTag::Sub,
15343                attrs: fuel_graph::jit::OpAttrs::default(),
15344                operands: vec![
15345                    fuel_graph::jit::PatternNode::Bind { index: 0 },
15346                    fuel_graph::jit::PatternNode::Bind { index: 1 },
15347                ],
15348            }],
15349        };
15350        let rid = crate::runtime_fused_kernels::adopt_runtime_fused(
15351            "test::compile_one::exp_sub",
15352            region,
15353            sentinel_kernel as crate::kernel::KernelRef,
15354            vec![DType::F32, DType::F32, DType::F32],
15355            BackendId::Cpu,
15356        )
15357        .expect("registrable region");
15358
15359        let graph_rc = Arc::new(RwLock::new(Graph::new()));
15360        let fused_id = {
15361            let mut g = graph_rc.write().unwrap();
15362            let s = Shape::from_dims(&[4]);
15363            let a = g.push(Node {
15364                op: Op::Const,
15365                inputs: vec![],
15366                shape: s.clone(),
15367                dtype: DType::F32,
15368            });
15369            let b = g.push(Node {
15370                op: Op::Const,
15371                inputs: vec![],
15372                shape: s.clone(),
15373                dtype: DType::F32,
15374            });
15375            let fused = g.push(Node {
15376                op: Op::Fused(
15377                    rid,
15378                    fuel_graph::registry::FusedOpParams::Runtime {
15379                        scalars: Vec::new(),
15380                    },
15381                ),
15382                inputs: vec![a, b],
15383                shape: s,
15384                dtype: DType::F32,
15385            });
15386            // The arm emitter pins the backend; mirror that here.
15387            g.set_target_backend(fused, BackendId::Cpu);
15388            fused
15389        };
15390        let g = graph_rc.read().unwrap();
15391        let bindings = crate::dispatch::global_bindings();
15392        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
15393        let item = compile_one(
15394            &g,
15395            fused_id,
15396            &mut layout_cache,
15397            &bindings,
15398            &SymEnv::default(),
15399        )
15400        .expect("compile_one runtime fused op");
15401        assert!(matches!(item.kind, WorkItemKind::Kernel));
15402        let compiled = item.compiled.expect("resolved a kernel");
15403        assert_eq!(compiled.op, fuel_ir::dispatch::OpKind::RuntimeFused);
15404        assert_eq!(compiled.backend, BackendId::Cpu);
15405        assert!(
15406            std::ptr::fn_addr_eq(compiled.kernel, sentinel_kernel as crate::kernel::KernelRef),
15407            "the kernel pointer is exactly the adopted one",
15408        );
15409        assert!(
15410            layout_cache.contains_key(&fused_id),
15411            "output layout cached for consumers"
15412        );
15413    }
15414
15415    /// The dtype belt-and-suspenders guard: an `Op::Fused(runtime)` node
15416    /// whose per-operand dtypes disagree with the adopted kernel's tuple is
15417    /// a typed error, not a silent wrong-kernel dispatch.
15418    #[test]
15419    fn compile_one_rejects_runtime_fused_dtype_mismatch() {
15420        fn noop_kernel(
15421            _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
15422            _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
15423            _layouts: &[Layout],
15424            _params: &crate::kernel::OpParams,
15425        ) -> Result<()> {
15426            Ok(())
15427        }
15428        let region = fuel_graph::jit::PatternNode::Op {
15429            op: fuel_graph::jit::OpTag::Log,
15430            attrs: fuel_graph::jit::OpAttrs::default(),
15431            operands: vec![fuel_graph::jit::PatternNode::Op {
15432                op: fuel_graph::jit::OpTag::Maximum,
15433                attrs: fuel_graph::jit::OpAttrs::default(),
15434                operands: vec![
15435                    fuel_graph::jit::PatternNode::Bind { index: 0 },
15436                    fuel_graph::jit::PatternNode::Bind { index: 1 },
15437                ],
15438            }],
15439        };
15440        // Adopted for F32 operands…
15441        let rid = crate::runtime_fused_kernels::adopt_runtime_fused(
15442            "test::compile_one::log_maximum",
15443            region,
15444            noop_kernel as crate::kernel::KernelRef,
15445            vec![DType::F32, DType::F32, DType::F32],
15446            BackendId::Cpu,
15447        )
15448        .expect("registrable region");
15449
15450        let graph_rc = Arc::new(RwLock::new(Graph::new()));
15451        let fused_id = {
15452            let mut g = graph_rc.write().unwrap();
15453            let s = Shape::from_dims(&[4]);
15454            // …but the node's operands are F64.
15455            let a = g.push(Node {
15456                op: Op::Const,
15457                inputs: vec![],
15458                shape: s.clone(),
15459                dtype: DType::F64,
15460            });
15461            let b = g.push(Node {
15462                op: Op::Const,
15463                inputs: vec![],
15464                shape: s.clone(),
15465                dtype: DType::F64,
15466            });
15467            let fused = g.push(Node {
15468                op: Op::Fused(
15469                    rid,
15470                    fuel_graph::registry::FusedOpParams::Runtime {
15471                        scalars: Vec::new(),
15472                    },
15473                ),
15474                inputs: vec![a, b],
15475                shape: s,
15476                dtype: DType::F64,
15477            });
15478            g.set_target_backend(fused, BackendId::Cpu);
15479            fused
15480        };
15481        let g = graph_rc.read().unwrap();
15482        let bindings = crate::dispatch::global_bindings();
15483        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
15484        let err = match compile_one(
15485            &g,
15486            fused_id,
15487            &mut layout_cache,
15488            &bindings,
15489            &SymEnv::default(),
15490        ) {
15491            Ok(_) => panic!("dtype mismatch must be a typed error"),
15492            Err(e) => e,
15493        };
15494        // Post-fold, the dtype tuple IS the binding key: a mismatch is the
15495        // same honest `NoBackendForOp` miss as an absent kernel — reported
15496        // with the `RuntimeFused` diagnostic op tag, never a wrong-kernel bind.
15497        assert!(
15498            matches!(
15499                err,
15500                fuel_ir::Error::NoBackendForOp {
15501                    op: fuel_ir::dispatch::OpKind::RuntimeFused,
15502                    ..
15503                }
15504            ),
15505            "a dtype mismatch is an honest binding miss: {err}",
15506        );
15507    }
15508
15509    /// A runtime fused node carrying live `Runtime { scalars }` compiles with
15510    /// `OpParams::JitScalars` — the launch channel for the kernel's trailing
15511    /// `p{i}` args. (A param-free node keeps `OpParams::None`, covered by
15512    /// `compile_one_resolves_runtime_fused_from_the_sidecar`.)
15513    #[test]
15514    fn compile_one_maps_runtime_scalars_to_jit_scalars() {
15515        fn noop_kernel(
15516            _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
15517            _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
15518            _layouts: &[Layout],
15519            _params: &crate::kernel::OpParams,
15520        ) -> Result<()> {
15521            Ok(())
15522        }
15523        // Unique slot-template region (process-global sidecar).
15524        let region = fuel_graph::jit::PatternNode::Op {
15525            op: fuel_graph::jit::OpTag::Floor,
15526            attrs: fuel_graph::jit::OpAttrs::default(),
15527            operands: vec![fuel_graph::jit::PatternNode::Op {
15528                op: fuel_graph::jit::OpTag::MulScalar,
15529                attrs: fuel_graph::jit::OpAttrs::default(), // open slot
15530                operands: vec![fuel_graph::jit::PatternNode::Bind { index: 0 }],
15531            }],
15532        };
15533        let rid = crate::runtime_fused_kernels::adopt_runtime_fused(
15534            "test::compile_one::floor_mul_scalar",
15535            region,
15536            noop_kernel as crate::kernel::KernelRef,
15537            vec![DType::F32, DType::F32],
15538            BackendId::Cpu,
15539        )
15540        .expect("slot template registrable");
15541
15542        let graph_rc = Arc::new(RwLock::new(Graph::new()));
15543        let fused_id = {
15544            let mut g = graph_rc.write().unwrap();
15545            let s = Shape::from_dims(&[4]);
15546            let x = g.push(Node {
15547                op: Op::Const,
15548                inputs: vec![],
15549                shape: s.clone(),
15550                dtype: DType::F32,
15551            });
15552            let fused = g.push(Node {
15553                op: Op::Fused(
15554                    rid,
15555                    fuel_graph::registry::FusedOpParams::Runtime {
15556                        scalars: vec![3.5, -1.25],
15557                    },
15558                ),
15559                inputs: vec![x],
15560                shape: s,
15561                dtype: DType::F32,
15562            });
15563            g.set_target_backend(fused, BackendId::Cpu);
15564            fused
15565        };
15566        let g = graph_rc.read().unwrap();
15567        let bindings = crate::dispatch::global_bindings();
15568        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
15569        let item = compile_one(
15570            &g,
15571            fused_id,
15572            &mut layout_cache,
15573            &bindings,
15574            &SymEnv::default(),
15575        )
15576        .expect("compile_one runtime fused op with scalars");
15577        let compiled = item.compiled.expect("resolved a kernel");
15578        assert!(
15579            matches!(
15580                &compiled.op_params,
15581                crate::kernel::OpParams::JitScalars { scalars } if scalars == &vec![3.5, -1.25]
15582            ),
15583            "Runtime scalars ride into OpParams::JitScalars, got {:?}",
15584            compiled.op_params,
15585        );
15586    }
15587
15588    /// Move-to-same-device is the degenerate case: per the legacy
15589    /// `GraphExecutor` contract (`Op::Copy | Op::Move` shared arm →
15590    /// `backend.copy_to`) it is a plain copy — fresh storage on the
15591    /// same device, data intact — and the source is still evicted
15592    /// afterward (destructive semantics don't depend on the devices
15593    /// differing).
15594    #[test]
15595    fn pipelined_op_move_same_device_is_plain_copy() {
15596        let src = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
15597        let graph = Arc::new(RwLock::new(Graph::new()));
15598        let (src_id, move_id) = {
15599            let mut g = graph.write().unwrap();
15600            let src = g.push(Node {
15601                op: Op::Const,
15602                inputs: vec![],
15603                shape: Shape::from_dims(&[4]),
15604                dtype: DType::F32,
15605            });
15606            let mv = g.push(Node {
15607                op: Op::Move {
15608                    target: DeviceLocation::Cpu,
15609                },
15610                inputs: vec![src],
15611                shape: Shape::from_dims(&[4]),
15612                dtype: DType::F32,
15613            });
15614            g.set_target_backend(mv, BackendId::Cpu);
15615            (src, mv)
15616        };
15617        let src_arc = Arc::new(RwLock::new(src));
15618        let src_arc_external = Arc::clone(&src_arc);
15619        let mut inputs = StorageCache::new();
15620        inputs.insert(src_id, src_arc);
15621
15622        let (out, layout) =
15623            PipelinedExecutor::realize(graph, move_id, inputs).expect("realize Op::Move");
15624        let guard = out.read().unwrap();
15625        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15626            panic!()
15627        };
15628        assert_eq!(
15629            c.as_slice::<f32>().unwrap(),
15630            &[1.0, 2.0, 3.0, 4.0],
15631            "Op::Move output should carry input's data to target",
15632        );
15633        assert!(layout.is_contiguous());
15634        drop(guard);
15635        assert!(
15636            !Arc::ptr_eq(&out, &src_arc_external),
15637            "same-device Move is a plain copy — fresh storage, not an alias",
15638        );
15639        // The realize loop's destructive_input cleanup dropped the
15640        // cache's Arc to the source; only the test's external clone
15641        // survives.
15642        assert_eq!(
15643            Arc::strong_count(&src_arc_external),
15644            1,
15645            "Op::Move should evict the cache's Arc to its source",
15646        );
15647    }
15648
15649    /// The multiple-consumer-source case: a Move must NOT strand
15650    /// another consumer of its source. `execution_plan` (via
15651    /// `derive_ordering`, keyed off `destructive_input`) pins the
15652    /// Move AFTER the sibling reader; the executor's post-Move cache
15653    /// eviction then can't break the reader. Mirrors the legacy
15654    /// `op_move_pinned_after_sibling_reader_via_derive_ordering`
15655    /// test in fuel-graph-router/tests/cross_device.rs.
15656    ///
15657    ///   a   = const [1, 2, 3, 4]
15658    ///   b   = relu(a)        (non-destructive sibling reader)
15659    ///   m   = move(a, Cpu)   (destructive — evicts a once run)
15660    ///   out = add(b, m)      → [2, 4, 6, 8]
15661    #[test]
15662    fn pipelined_op_move_multi_consumer_source_not_stranded() {
15663        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
15664        let graph = Arc::new(RwLock::new(Graph::new()));
15665        let (a_id, out_id) = {
15666            let mut g = graph.write().unwrap();
15667            let a = g.push(Node {
15668                op: Op::Const,
15669                inputs: vec![],
15670                shape: Shape::from_dims(&[4]),
15671                dtype: DType::F32,
15672            });
15673            let b = g.push(Node {
15674                op: Op::Relu,
15675                inputs: vec![a],
15676                shape: Shape::from_dims(&[4]),
15677                dtype: DType::F32,
15678            });
15679            let m = g.push(Node {
15680                op: Op::Move {
15681                    target: DeviceLocation::Cpu,
15682                },
15683                inputs: vec![a],
15684                shape: Shape::from_dims(&[4]),
15685                dtype: DType::F32,
15686            });
15687            let out = g.push(Node {
15688                op: Op::Add,
15689                inputs: vec![b, m],
15690                shape: Shape::from_dims(&[4]),
15691                dtype: DType::F32,
15692            });
15693            g.set_target_backend(b, BackendId::Cpu);
15694            g.set_target_backend(m, BackendId::Cpu);
15695            g.set_target_backend(out, BackendId::Cpu);
15696            (a, out)
15697        };
15698        let mut inputs = StorageCache::new();
15699        inputs.insert(a_id, Arc::new(RwLock::new(a)));
15700
15701        let (out, _) = PipelinedExecutor::realize(graph, out_id, inputs)
15702            .expect("realize add(relu(a), move(a))");
15703        let guard = out.read().unwrap();
15704        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15705            panic!()
15706        };
15707        assert_eq!(
15708            c.as_slice::<f32>().unwrap(),
15709            &[2.0, 4.0, 6.0, 8.0],
15710            "relu(a) must run before move(a) evicts a",
15711        );
15712    }
15713
15714    /// A Move whose source is itself in the realize target set must
15715    /// not evict it — the caller asked for the source's storage. The
15716    /// destructive cleanup's `target_set` gate covers Move exactly
15717    /// like Release.
15718    #[test]
15719    fn pipelined_op_move_source_in_target_set_not_evicted() {
15720        let a = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0]);
15721        let graph = Arc::new(RwLock::new(Graph::new()));
15722        let (a_id, move_id) = {
15723            let mut g = graph.write().unwrap();
15724            let a = g.push(Node {
15725                op: Op::Const,
15726                inputs: vec![],
15727                shape: Shape::from_dims(&[2]),
15728                dtype: DType::F32,
15729            });
15730            let mv = g.push(Node {
15731                op: Op::Move {
15732                    target: DeviceLocation::Cpu,
15733                },
15734                inputs: vec![a],
15735                shape: Shape::from_dims(&[2]),
15736                dtype: DType::F32,
15737            });
15738            g.set_target_backend(mv, BackendId::Cpu);
15739            (a, mv)
15740        };
15741        let a_arc = Arc::new(RwLock::new(a));
15742        let a_arc_external = Arc::clone(&a_arc);
15743        let mut inputs = StorageCache::new();
15744        inputs.insert(a_id, a_arc);
15745
15746        let out = PipelinedExecutor::realize_many(graph, &[move_id, a_id], inputs)
15747            .expect("realize_many [move, source]");
15748        assert_eq!(out.len(), 2);
15749        let mv_guard = out[0].0.read().unwrap();
15750        let fuel_memory::BackendStorage::Cpu(c) = &mv_guard.inner else {
15751            panic!()
15752        };
15753        assert_eq!(c.as_slice::<f32>().unwrap(), &[5.0, 6.0]);
15754        assert!(
15755            Arc::ptr_eq(&out[1].0, &a_arc_external),
15756            "requested source must survive the Move's destructive cleanup",
15757        );
15758    }
15759
15760    // --- realize_many (Phase 7.6 step 9c Phase A) ----------------
15761
15762    /// realize_many on empty targets returns an empty Vec — no graph
15763    /// walk, no panic.
15764    #[test]
15765    fn pipelined_realize_many_empty_targets() {
15766        let graph = Arc::new(RwLock::new(Graph::new()));
15767        let inputs = StorageCache::new();
15768        let out = PipelinedExecutor::realize_many(graph, &[], inputs).expect("realize_many");
15769        assert!(out.is_empty());
15770    }
15771
15772    /// realize_many with two independent target chains. Each chain's
15773    /// output is in the cache; the shared topo walk realizes both.
15774    /// Verifies parallel chain handling + return order matches input.
15775    #[test]
15776    fn pipelined_realize_many_two_independent_targets() {
15777        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
15778        let rhs = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
15779        let graph = Arc::new(RwLock::new(Graph::new()));
15780        let (lhs_id, rhs_id, add_id, mul_id) = {
15781            let mut g = graph.write().unwrap();
15782            let lhs = g.push(Node {
15783                op: Op::Const,
15784                inputs: vec![],
15785                shape: Shape::from_dims(&[3]),
15786                dtype: DType::F32,
15787            });
15788            let rhs = g.push(Node {
15789                op: Op::Const,
15790                inputs: vec![],
15791                shape: Shape::from_dims(&[3]),
15792                dtype: DType::F32,
15793            });
15794            let add = g.push(Node {
15795                op: Op::Add,
15796                inputs: vec![lhs, rhs],
15797                shape: Shape::from_dims(&[3]),
15798                dtype: DType::F32,
15799            });
15800            let mul = g.push(Node {
15801                op: Op::Mul,
15802                inputs: vec![lhs, rhs],
15803                shape: Shape::from_dims(&[3]),
15804                dtype: DType::F32,
15805            });
15806            g.set_target_backend(add, BackendId::Cpu);
15807            g.set_target_backend(mul, BackendId::Cpu);
15808            (lhs, rhs, add, mul)
15809        };
15810        let mut inputs = StorageCache::new();
15811        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs)));
15812        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs)));
15813
15814        // Pass mul first to confirm return order matches targets order
15815        // (not graph order — graph order would put add first).
15816        let out = PipelinedExecutor::realize_many(graph, &[mul_id, add_id], inputs)
15817            .expect("realize_many");
15818        assert_eq!(out.len(), 2);
15819
15820        let mul_guard = out[0].0.read().unwrap();
15821        let fuel_memory::BackendStorage::Cpu(c) = &mul_guard.inner else {
15822            panic!()
15823        };
15824        assert_eq!(c.as_slice::<f32>().unwrap(), &[10.0, 40.0, 90.0]);
15825
15826        let add_guard = out[1].0.read().unwrap();
15827        let fuel_memory::BackendStorage::Cpu(c) = &add_guard.inner else {
15828            panic!()
15829        };
15830        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 22.0, 33.0]);
15831    }
15832
15833    /// realize_many with the same NodeId twice — caller asking for
15834    /// the same output twice. Both outputs are the same Arc (cheap).
15835    #[test]
15836    fn pipelined_realize_many_duplicate_target_returns_same_arc() {
15837        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
15838        let graph = Arc::new(RwLock::new(Graph::new()));
15839        let (in_id, neg_id) = {
15840            let mut g = graph.write().unwrap();
15841            let in_id = g.push(Node {
15842                op: Op::Const,
15843                inputs: vec![],
15844                shape: Shape::from_dims(&[3]),
15845                dtype: DType::F32,
15846            });
15847            let neg = g.push(Node {
15848                op: Op::Neg,
15849                inputs: vec![in_id],
15850                shape: Shape::from_dims(&[3]),
15851                dtype: DType::F32,
15852            });
15853            g.set_target_backend(neg, BackendId::Cpu);
15854            (in_id, neg)
15855        };
15856        let mut inputs = StorageCache::new();
15857        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
15858
15859        let out = PipelinedExecutor::realize_many(graph, &[neg_id, neg_id], inputs)
15860            .expect("realize_many");
15861        assert_eq!(out.len(), 2);
15862        assert!(
15863            Arc::ptr_eq(&out[0].0, &out[1].0),
15864            "duplicate target should share the same storage Arc",
15865        );
15866    }
15867
15868    /// realize_many with shared upstream nodes evaluates the shared
15869    /// chunk exactly once. Two targets `f = a + b` and `g = (a + b) * a`
15870    /// — `a + b` is computed once.
15871    #[test]
15872    fn pipelined_realize_many_shared_subgraph_evaluates_once() {
15873        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
15874        let b_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
15875        let graph = Arc::new(RwLock::new(Graph::new()));
15876        let (a_id, b_id, add_id, mul_id) = {
15877            let mut g = graph.write().unwrap();
15878            let a = g.push(Node {
15879                op: Op::Const,
15880                inputs: vec![],
15881                shape: Shape::from_dims(&[3]),
15882                dtype: DType::F32,
15883            });
15884            let b = g.push(Node {
15885                op: Op::Const,
15886                inputs: vec![],
15887                shape: Shape::from_dims(&[3]),
15888                dtype: DType::F32,
15889            });
15890            let add = g.push(Node {
15891                op: Op::Add,
15892                inputs: vec![a, b],
15893                shape: Shape::from_dims(&[3]),
15894                dtype: DType::F32,
15895            });
15896            let mul = g.push(Node {
15897                op: Op::Mul,
15898                inputs: vec![add, a],
15899                shape: Shape::from_dims(&[3]),
15900                dtype: DType::F32,
15901            });
15902            g.set_target_backend(add, BackendId::Cpu);
15903            g.set_target_backend(mul, BackendId::Cpu);
15904            (a, b, add, mul)
15905        };
15906        let mut inputs = StorageCache::new();
15907        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
15908        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
15909
15910        let out = PipelinedExecutor::realize_many(graph, &[add_id, mul_id], inputs)
15911            .expect("realize_many");
15912        assert_eq!(out.len(), 2);
15913
15914        let add_guard = out[0].0.read().unwrap();
15915        let fuel_memory::BackendStorage::Cpu(c) = &add_guard.inner else {
15916            panic!()
15917        };
15918        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 22.0, 33.0]);
15919
15920        let mul_guard = out[1].0.read().unwrap();
15921        let fuel_memory::BackendStorage::Cpu(c) = &mul_guard.inner else {
15922            panic!()
15923        };
15924        // (a + b) * a = [11*1, 22*2, 33*3] = [11, 44, 99].
15925        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 44.0, 99.0]);
15926    }
15927
15928    /// E2E: masked_fill with -inf — the attention masking pattern.
15929    /// x = [1, 2, 3, 4]; mask = [0, 1, 0, 1]; value = -1000.
15930    /// out = [1, -1000, 3, -1000].
15931    #[test]
15932    fn pipelined_realize_masked_fill_attention_pattern() {
15933        let x_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
15934        let mut mask_storage = fuel_memory::from_slice_cpu(&[0u8, 1, 0, 1]);
15935        mask_storage.dtype = DType::Bool; // GAP-168(c): a Bool mask, not U8 bytes
15936        let graph = Arc::new(RwLock::new(Graph::new()));
15937        let (x_id, mask_id, out_id) = {
15938            let mut g = graph.write().unwrap();
15939            let x = g.push(Node {
15940                op: Op::Const,
15941                inputs: vec![],
15942                shape: Shape::from_dims(&[4]),
15943                dtype: DType::F32,
15944            });
15945            let mask = g.push(Node {
15946                op: Op::Const,
15947                inputs: vec![],
15948                shape: Shape::from_dims(&[4]),
15949                dtype: DType::Bool,
15950            });
15951            let out = g.push(Node {
15952                op: Op::MaskedFill {
15953                    value: fuel_ir::Scalar::F32(-1000.0),
15954                },
15955                inputs: vec![x, mask],
15956                shape: Shape::from_dims(&[4]),
15957                dtype: DType::F32,
15958            });
15959            g.set_target_backend(out, BackendId::Cpu);
15960            (x, mask, out)
15961        };
15962        let mut inputs = StorageCache::new();
15963        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
15964        inputs.insert(mask_id, Arc::new(RwLock::new(mask_storage)));
15965        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
15966        let guard = result_arc.read().unwrap();
15967        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15968            panic!("expected Cpu storage");
15969        };
15970        let out: &[f32] = c.as_slice().unwrap();
15971        assert_eq!(out, &[1.0, -1000.0, 3.0, -1000.0]);
15972    }
15973
15974    // ---- WriteSlice (Phase 7.6 step 9c E.3.2) -------------------------------
15975
15976    /// E2E: pipelined realize of `Op::WriteSlice` writing a [1, 3, 2]
15977    /// source slab into a [4, 3, 2] destination at axis-0 row 2 — the
15978    /// canonical KV-cache append shape.
15979    #[test]
15980    fn pipelined_realize_write_slice_kv_cache_append() {
15981        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 24]);
15982        let src_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
15983        let graph = Arc::new(RwLock::new(Graph::new()));
15984        let (dest_id, src_id, ws_id) = {
15985            let mut g = graph.write().unwrap();
15986            let dest = g.push(Node {
15987                op: Op::Const,
15988                inputs: vec![],
15989                shape: Shape::from_dims(&[4, 3, 2]),
15990                dtype: DType::F32,
15991            });
15992            let src = g.push(Node {
15993                op: Op::Const,
15994                inputs: vec![],
15995                shape: Shape::from_dims(&[1, 3, 2]),
15996                dtype: DType::F32,
15997            });
15998            let ws = g.push(Node {
15999                op: Op::WriteSlice {
16000                    ranges: vec![(2, 3), (0, 3), (0, 2)],
16001                    dyn_offset: None,
16002                },
16003                inputs: vec![dest, src],
16004                shape: Shape::from_dims(&[4, 3, 2]), // adopts dest shape
16005                dtype: DType::F32,
16006            });
16007            g.set_target_backend(ws, BackendId::Cpu);
16008            (dest, src, ws)
16009        };
16010        let mut inputs = StorageCache::new();
16011        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
16012        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
16013        let (result_arc, _) = PipelinedExecutor::realize(graph, ws_id, inputs).expect("realize");
16014        let guard = result_arc.read().unwrap();
16015        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16016            panic!("expected Cpu storage");
16017        };
16018        let out: &[f32] = c.as_slice().unwrap();
16019        let expected = [
16020            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0,
16021            6.0, // row 2 = source
16022            0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
16023        ];
16024        assert_eq!(out, &expected);
16025    }
16026
16027    /// E2E: pipelined realize of `Op::WriteSlice` adopts the
16028    /// destination's Storage Arc as the output slot (in-place
16029    /// alias) — the resulting Arc points to the SAME bytes the
16030    /// destination was constructed from.
16031    #[test]
16032    fn pipelined_realize_write_slice_aliases_dest_storage() {
16033        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
16034        let src_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
16035        let graph = Arc::new(RwLock::new(Graph::new()));
16036        let (dest_id, src_id, ws_id, dest_arc_external) = {
16037            let mut g = graph.write().unwrap();
16038            let dest = g.push(Node {
16039                op: Op::Const,
16040                inputs: vec![],
16041                shape: Shape::from_dims(&[3, 2]),
16042                dtype: DType::F32,
16043            });
16044            let src = g.push(Node {
16045                op: Op::Const,
16046                inputs: vec![],
16047                shape: Shape::from_dims(&[1, 2]),
16048                dtype: DType::F32,
16049            });
16050            let ws = g.push(Node {
16051                op: Op::WriteSlice {
16052                    ranges: vec![(1, 2), (0, 2)],
16053                    dyn_offset: None,
16054                },
16055                inputs: vec![dest, src],
16056                shape: Shape::from_dims(&[3, 2]),
16057                dtype: DType::F32,
16058            });
16059            g.set_target_backend(ws, BackendId::Cpu);
16060            let arc = Arc::new(RwLock::new(dest_storage));
16061            (dest, src, ws, arc)
16062        };
16063        let mut inputs = StorageCache::new();
16064        inputs.insert(dest_id, Arc::clone(&dest_arc_external));
16065        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
16066        let (result_arc, _) = PipelinedExecutor::realize(graph, ws_id, inputs).expect("realize");
16067        // Bytes were written into the same Arc the caller held —
16068        // the WriteSlice op aliases dest's Storage Arc, not allocates
16069        // a fresh buffer.
16070        assert!(
16071            Arc::ptr_eq(&result_arc, &dest_arc_external),
16072            "WriteSlice output Arc must be the same Arc as the destination's"
16073        );
16074        let guard = dest_arc_external.read().unwrap();
16075        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16076            panic!("expected Cpu storage");
16077        };
16078        let out: &[f32] = c.as_slice().unwrap();
16079        assert_eq!(out, &[0.0, 0.0, 10.0, 20.0, 0.0, 0.0]);
16080    }
16081
16082    // ---- WriteSlice dynamic offset (Phase D symbolic extents) ---------------
16083
16084    /// E2E: pipelined realize of `Op::WriteSlice` with a runtime start
16085    /// offset (`dyn_offset`) resolved through a per-pass `SymEnv`. The
16086    /// width-2 source slab lands at the bound offset (3), not the static
16087    /// `ranges[0].0` placeholder (0) — the persistent-decode KV-cache
16088    /// write at a per-token `cached_len`.
16089    #[test]
16090    fn pipelined_realize_write_slice_dynamic_offset() {
16091        use fuel_ir::{DynScalar, SymId};
16092        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
16093        let src_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0]);
16094        let graph = Arc::new(RwLock::new(Graph::new()));
16095        let sym = SymId(0);
16096        let (dest_id, src_id, ws_id) = {
16097            let mut g = graph.write().unwrap();
16098            let dest = g.push(Node {
16099                op: Op::Const,
16100                inputs: vec![],
16101                shape: Shape::from_dims(&[6]),
16102                dtype: DType::F32,
16103            });
16104            let src = g.push(Node {
16105                op: Op::Const,
16106                inputs: vec![],
16107                shape: Shape::from_dims(&[2]),
16108                dtype: DType::F32,
16109            });
16110            let ws = g.push(Node {
16111                // ranges[0] = (0, 2): the start is a placeholder (ignored —
16112                // overridden by dyn_offset); only the width (2) is read.
16113                op: Op::WriteSlice {
16114                    ranges: vec![(0, 2)],
16115                    dyn_offset: Some((0, DynScalar::Sym(sym))),
16116                },
16117                inputs: vec![dest, src],
16118                shape: Shape::from_dims(&[6]),
16119                dtype: DType::F32,
16120            });
16121            g.set_target_backend(ws, BackendId::Cpu);
16122            (dest, src, ws)
16123        };
16124        let mut inputs = StorageCache::new();
16125        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
16126        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
16127
16128        // Bind cached_len = 3: the slab must land at indices [3, 4].
16129        let mut env = SymEnv::new();
16130        env.bind(sym, 3).unwrap();
16131
16132        let (result_arc, _) = PipelinedExecutor::realize_with_env(graph, ws_id, inputs, env)
16133            .expect("realize_with_env");
16134        let guard = result_arc.read().unwrap();
16135        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16136            panic!("expected Cpu storage");
16137        };
16138        let out: &[f32] = c.as_slice().unwrap();
16139        assert_eq!(
16140            out,
16141            &[0.0, 0.0, 0.0, 7.0, 8.0, 0.0],
16142            "slab must land at the SymEnv-bound offset 3, not the static placeholder 0",
16143        );
16144    }
16145
16146    /// Increment 2a — the data-determined bind seam. After
16147    /// `Op::NonZeroIndices` realizes, the executor reads its runtime count
16148    /// from bundle slot 1 and PUBLISHES it into the produced `SymEnv` under
16149    /// `count_sym`. This is the first op to bind a *data-determined* symbol
16150    /// mid-realize (all prior binds are host-known before realize) — the
16151    /// keystone capability for SSM decode / MoE sparsity / MLA KV.
16152    #[test]
16153    fn pipelined_realize_nonzero_indices_publishes_count() {
16154        use fuel_ir::SymId;
16155        use fuel_ir::storage::{OutputViewSpec, compose_bundle};
16156        // flat [0,1,0,1,1,0] → 3 nonzeros at 1,3,4; capacity 6.
16157        let x_storage = fuel_memory::from_slice_cpu(&[0.0_f32, 1.0, 0.0, 1.0, 1.0, 0.0]);
16158        let graph = Arc::new(RwLock::new(Graph::new()));
16159        let count_sym = SymId(0);
16160        let (x_id, nzi_id) = {
16161            let mut g = graph.write().unwrap();
16162            let x = g.push(Node {
16163                op: Op::Const,
16164                inputs: vec![],
16165                shape: Shape::from_dims(&[2, 3]),
16166                dtype: DType::F32,
16167            });
16168            let capacity = 6usize;
16169            let idx_shape = Shape::from_dims(&[capacity]);
16170            let cnt_shape = Shape::from_dims(&[1]);
16171            let specs = vec![
16172                OutputViewSpec {
16173                    dtype: DType::U32,
16174                    shape: idx_shape.clone(),
16175                    layout: Layout::contiguous(idx_shape.clone()),
16176                    name: Some("indices"),
16177                },
16178                OutputViewSpec {
16179                    dtype: DType::U32,
16180                    shape: cnt_shape.clone(),
16181                    layout: Layout::contiguous(cnt_shape),
16182                    name: Some("count"),
16183                },
16184            ];
16185            let (_bytes, views) = compose_bundle(&specs).unwrap();
16186            let nzi = g.push(Node {
16187                op: Op::NonZeroIndices { count_sym },
16188                inputs: vec![x],
16189                shape: idx_shape,
16190                dtype: DType::U32,
16191            });
16192            g.set_output_views(nzi, Arc::from(views.into_boxed_slice()))
16193                .unwrap();
16194            g.set_target_backend(nzi, BackendId::Cpu);
16195            (x, nzi)
16196        };
16197        let mut inputs = StorageCache::new();
16198        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
16199
16200        let (_arc, _layout, produced) =
16201            PipelinedExecutor::realize_with_env_producing(graph, nzi_id, inputs, SymEnv::new())
16202                .expect("realize_with_env_producing");
16203
16204        assert_eq!(
16205            produced.get(count_sym),
16206            Some(3),
16207            "the executor must publish the data-determined nonzero count into the SymEnv",
16208        );
16209    }
16210
16211    /// A `dyn_offset` whose symbol is unbound in the `SymEnv` surfaces a
16212    /// typed error at realize (never a panic).
16213    #[test]
16214    fn pipelined_realize_write_slice_dynamic_offset_unbound_errors() {
16215        use fuel_ir::{DynScalar, SymId};
16216        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
16217        let src_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0]);
16218        let graph = Arc::new(RwLock::new(Graph::new()));
16219        let (dest_id, src_id, ws_id) = {
16220            let mut g = graph.write().unwrap();
16221            let dest = g.push(Node {
16222                op: Op::Const,
16223                inputs: vec![],
16224                shape: Shape::from_dims(&[6]),
16225                dtype: DType::F32,
16226            });
16227            let src = g.push(Node {
16228                op: Op::Const,
16229                inputs: vec![],
16230                shape: Shape::from_dims(&[2]),
16231                dtype: DType::F32,
16232            });
16233            let ws = g.push(Node {
16234                op: Op::WriteSlice {
16235                    ranges: vec![(0, 2)],
16236                    dyn_offset: Some((0, DynScalar::Sym(SymId(0)))),
16237                },
16238                inputs: vec![dest, src],
16239                shape: Shape::from_dims(&[6]),
16240                dtype: DType::F32,
16241            });
16242            g.set_target_backend(ws, BackendId::Cpu);
16243            (dest, src, ws)
16244        };
16245        let mut inputs = StorageCache::new();
16246        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
16247        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
16248        // Empty env — the symbol is unbound.
16249        let result = PipelinedExecutor::realize_with_env(graph, ws_id, inputs, SymEnv::new());
16250        assert!(
16251            result.is_err(),
16252            "unbound dyn_offset symbol must surface a typed error, not a panic",
16253        );
16254    }
16255
16256    /// A runtime offset whose resolved slab runs past the destination
16257    /// capacity errors at realize (never an out-of-bounds write).
16258    #[test]
16259    fn pipelined_realize_write_slice_dynamic_offset_out_of_capacity_errors() {
16260        use fuel_ir::{DynScalar, SymId};
16261        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
16262        let src_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0]);
16263        let graph = Arc::new(RwLock::new(Graph::new()));
16264        let sym = SymId(0);
16265        let (dest_id, src_id, ws_id) = {
16266            let mut g = graph.write().unwrap();
16267            let dest = g.push(Node {
16268                op: Op::Const,
16269                inputs: vec![],
16270                shape: Shape::from_dims(&[6]),
16271                dtype: DType::F32,
16272            });
16273            let src = g.push(Node {
16274                op: Op::Const,
16275                inputs: vec![],
16276                shape: Shape::from_dims(&[2]),
16277                dtype: DType::F32,
16278            });
16279            let ws = g.push(Node {
16280                op: Op::WriteSlice {
16281                    ranges: vec![(0, 2)],
16282                    dyn_offset: Some((0, DynScalar::Sym(sym))),
16283                },
16284                inputs: vec![dest, src],
16285                shape: Shape::from_dims(&[6]),
16286                dtype: DType::F32,
16287            });
16288            g.set_target_backend(ws, BackendId::Cpu);
16289            (dest, src, ws)
16290        };
16291        let mut inputs = StorageCache::new();
16292        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
16293        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
16294        // offset 5 + width 2 = 7 > capacity 6.
16295        let mut env = SymEnv::new();
16296        env.bind(sym, 5).unwrap();
16297        let result = PipelinedExecutor::realize_with_env(graph, ws_id, inputs, env);
16298        assert!(
16299            result.is_err(),
16300            "resolved slab past destination capacity must surface a typed error",
16301        );
16302    }
16303
16304    /// Regression for the PipelinedExecutor ordering-integration session.
16305    ///
16306    /// Graph: `x = Const`, `step_x = Step(x)`, `y = SigmoidInplace(x)`.
16307    /// `Step` and `SigmoidInplace` are both readers of `x`; `Step` is
16308    /// non-destructive, `SigmoidInplace` mutates `x`'s storage. The
16309    /// correct semantic is for `Step` to read PRE-mutation bytes.
16310    ///
16311    /// Pre-this-session (raw `topo_order_multi`): the two are siblings
16312    /// in topo order and the tie-break is unspecified — `SigmoidInplace`
16313    /// could run first, making `step_x` see post-sigmoid bytes
16314    /// (`[1, 1, 1, 1]` because every sigmoid output is positive).
16315    ///
16316    /// Post-this-session: `execution_plan` consults `derive_ordering`,
16317    /// which pins `SigmoidInplace` AFTER every other reader of `x`.
16318    /// `step_x` deterministically sees `x` and is `[1, 0, 1, 0]`.
16319    #[test]
16320    fn pipelined_inplace_with_multiple_readers_orders_correctly() {
16321        use fuel_ir::Shape;
16322        let data = [1.0_f32, -2.0, 3.0, -4.0];
16323        let src_storage = fuel_memory::from_slice_cpu(&data);
16324
16325        let graph = Arc::new(RwLock::new(Graph::new()));
16326        let (x_id, step_id, sig_id) = {
16327            let mut g = graph.write().unwrap();
16328            let x = g.push(Node {
16329                op: Op::Const,
16330                inputs: vec![],
16331                shape: Shape::from_dims(&[4]),
16332                dtype: DType::F32,
16333            });
16334            let step = g.push(Node {
16335                op: Op::Step,
16336                inputs: vec![x],
16337                shape: Shape::from_dims(&[4]),
16338                dtype: DType::F32,
16339            });
16340            let sig = g.push(Node {
16341                op: Op::SigmoidInplace,
16342                inputs: vec![x],
16343                shape: Shape::from_dims(&[4]),
16344                dtype: DType::F32,
16345            });
16346            g.set_target_backend(step, BackendId::Cpu);
16347            g.set_target_backend(sig, BackendId::Cpu);
16348            (x, step, sig)
16349        };
16350
16351        let mut cache = StorageCache::new();
16352        cache.insert(x_id, Arc::new(RwLock::new(src_storage)));
16353
16354        let results = PipelinedExecutor::realize_many(graph, &[step_id, sig_id], cache)
16355            .expect("realize_many");
16356
16357        // step_x must reflect pre-mutation x: sign of [1, -2, 3, -4] →
16358        // [1, 0, 1, 0]. If the executor ran SigmoidInplace first, step
16359        // would see all-positive sigmoid outputs and produce [1, 1, 1, 1].
16360        let step_guard = results[0].0.read().unwrap();
16361        let fuel_memory::BackendStorage::Cpu(c) = &step_guard.inner else {
16362            panic!("expected Cpu storage for step output");
16363        };
16364        let step_out: &[f32] = c.as_slice().expect("f32 cast");
16365        assert_eq!(
16366            step_out,
16367            &[1.0_f32, 0.0, 1.0, 0.0],
16368            "Step must run before SigmoidInplace; got post-mutation bytes"
16369        );
16370        drop(step_guard);
16371
16372        // SigmoidInplace's output Arc IS the mutated cache entry — bytes
16373        // approximate sigmoid([1, -2, 3, -4]).
16374        let sig_guard = results[1].0.read().unwrap();
16375        let fuel_memory::BackendStorage::Cpu(c) = &sig_guard.inner else {
16376            panic!("expected Cpu storage for sigmoid output");
16377        };
16378        let sig_out: &[f32] = c.as_slice().expect("f32 cast");
16379        let sig_ref = [
16380            1.0_f32 / (1.0 + (-1.0_f32).exp()),
16381            1.0_f32 / (1.0 + (2.0_f32).exp()),
16382            1.0_f32 / (1.0 + (-3.0_f32).exp()),
16383            1.0_f32 / (1.0 + (4.0_f32).exp()),
16384        ];
16385        for (got, want) in sig_out.iter().zip(sig_ref.iter()) {
16386            assert!((got - want).abs() < 1e-6, "sigmoid: got {got}, want {want}");
16387        }
16388    }
16389
16390    /// Regression for the PipelinedExecutor ordering-integration session.
16391    ///
16392    /// Canonical residual-connection pattern:
16393    ///   `x = Const`, `y = ReluInplace(x)`, `z = Add(y, x)`.
16394    ///
16395    /// Pre-this-session: `derive_ordering` was never run, so the cycle
16396    /// (Add must precede ReluInplace per ordering edge; Add must follow
16397    /// ReluInplace per data-flow edge through y) was undetected. The
16398    /// executor produced `z = relu(x) + relu(x) = [2, 0, 6, 0]` —
16399    /// silently wrong.
16400    ///
16401    /// Post-this-session: `insert_safety_copies` runs before
16402    /// `execution_plan`, inserts `Op::Copy(x) → x_safe`, rewires Add's
16403    /// `x` input to `x_safe`. Result: `z = relu(x) + x = [2, -2, 6, -4]`.
16404    #[test]
16405    fn pipelined_residual_connection_inserts_safety_copy() {
16406        use fuel_ir::Shape;
16407        let data = [1.0_f32, -2.0, 3.0, -4.0];
16408        let src_storage = fuel_memory::from_slice_cpu(&data);
16409
16410        let graph = Arc::new(RwLock::new(Graph::new()));
16411        let (x_id, _y_id, z_id) = {
16412            let mut g = graph.write().unwrap();
16413            let x = g.push(Node {
16414                op: Op::Const,
16415                inputs: vec![],
16416                shape: Shape::from_dims(&[4]),
16417                dtype: DType::F32,
16418            });
16419            let y = g.push(Node {
16420                op: Op::ReluInplace,
16421                inputs: vec![x],
16422                shape: Shape::from_dims(&[4]),
16423                dtype: DType::F32,
16424            });
16425            let z = g.push(Node {
16426                op: Op::Add,
16427                inputs: vec![y, x],
16428                shape: Shape::from_dims(&[4]),
16429                dtype: DType::F32,
16430            });
16431            g.set_target_backend(y, BackendId::Cpu);
16432            g.set_target_backend(z, BackendId::Cpu);
16433            (x, y, z)
16434        };
16435
16436        let mut cache = StorageCache::new();
16437        cache.insert(x_id, Arc::new(RwLock::new(src_storage)));
16438
16439        let (result_arc, _) = PipelinedExecutor::realize(graph, z_id, cache)
16440            .expect("realize z — insert_safety_copies must break the cycle");
16441
16442        let guard = result_arc.read().unwrap();
16443        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16444            panic!("expected Cpu storage");
16445        };
16446        let got: &[f32] = c.as_slice().expect("f32 cast");
16447        assert_eq!(
16448            got,
16449            &[2.0_f32, -2.0, 6.0, -4.0],
16450            "Add must read pre-mutation x via the inserted safety copy"
16451        );
16452    }
16453
16454    // ------------------------------------------------------------------
16455    // Item 3 end-to-end: SelectiveScan through the bundled-output
16456    // PipelinedExecutor path. The producer allocates bundled
16457    // (y_bytes + last_state_bytes), the kernel writes both slots,
16458    // and the bundled-tuple builder returns each via Op::View.
16459    // ------------------------------------------------------------------
16460
16461    fn cpu_const_f32(
16462        graph: &Arc<RwLock<Graph>>,
16463        cache: &mut StorageCache,
16464        data: &[f32],
16465        dims: &[usize],
16466    ) -> NodeId {
16467        let id = {
16468            let mut g = graph.write().unwrap();
16469            g.push(Node {
16470                op: Op::Const,
16471                inputs: vec![],
16472                shape: Shape::from_dims(dims),
16473                dtype: DType::F32,
16474            })
16475        };
16476        cache.insert(id, Arc::new(RwLock::new(fuel_memory::from_slice_cpu(data))));
16477        id
16478    }
16479
16480    /// `selective_scan_bundled` realizes both `y` and `last_state` in
16481    /// a single `realize_many` pass; the Views project the same
16482    /// producer's bundled Storage Arc and the numerics match the
16483    /// hand-computed single-step kernel test (b=1,s=1,d=1,k=1).
16484    #[test]
16485    fn pipelined_realize_selective_scan_bundled_produces_y_and_last_state() {
16486        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16487        let mut cache = StorageCache::new();
16488
16489        let u_id = cpu_const_f32(&graph, &mut cache, &[3.0], &[1, 1, 1]);
16490        let delta_id = cpu_const_f32(&graph, &mut cache, &[1.0], &[1, 1, 1]);
16491        let a_id = cpu_const_f32(&graph, &mut cache, &[-1.0], &[1, 1]);
16492        let b_id = cpu_const_f32(&graph, &mut cache, &[2.0], &[1, 1, 1]);
16493        let c_id = cpu_const_f32(&graph, &mut cache, &[0.5], &[1, 1, 1]);
16494
16495        let (y_id, last_state_id) = {
16496            let u_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), u_id);
16497            let delta_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), delta_id);
16498            let a_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), a_id);
16499            let b_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), b_id);
16500            let c_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), c_id);
16501            let (y, last_state) = u_t
16502                .selective_scan_bundled(&delta_t, &a_t, &b_t, &c_t, /* delta_softplus */ false)
16503                .expect("selective_scan_bundled");
16504            (y.id(), last_state.id())
16505        };
16506        // Set target_backend on the producer (View nodes inherit it).
16507        {
16508            let mut g = graph.write().unwrap();
16509            let producer = g.node(y_id).inputs[0];
16510            g.set_target_backend(producer, BackendId::Cpu);
16511        }
16512
16513        let outputs =
16514            PipelinedExecutor::realize_many(Arc::clone(&graph), &[y_id, last_state_id], cache)
16515                .expect("realize_many");
16516        let (y_arc, y_layout) = outputs[0].clone();
16517        let (last_state_arc, last_state_layout) = outputs[1].clone();
16518
16519        // Both Views project the same bundled producer Storage Arc.
16520        assert!(
16521            Arc::ptr_eq(&y_arc, &last_state_arc),
16522            "y and last_state Views project the SAME bundled producer Storage",
16523        );
16524
16525        // Hand-computed numerics (single-step recurrence):
16526        // h[0,0,0] = exp(1.0 * -1.0) * 0 + 1.0 * 2.0 * 3.0 = 6.0
16527        // y[0,0,0] = h * c = 6.0 * 0.5 = 3.0
16528        // last_state[0,0,0] = h = 6.0
16529        let guard = y_arc.read().unwrap();
16530        let fuel_memory::BackendStorage::Cpu(c_bytes) = &guard.inner else {
16531            panic!("expected Cpu storage");
16532        };
16533        let typed: &[f32] = c_bytes.as_slice().expect("f32 cast");
16534        assert_eq!(y_layout.start_offset(), 0);
16535        let y_value = typed[y_layout.start_offset()];
16536        assert!((y_value - 3.0).abs() < 1e-5, "y expected 3.0 got {y_value}");
16537        assert_eq!(
16538            last_state_layout.start_offset(),
16539            1,
16540            "slot 1 byte_offset 4 / sizeof(f32) = 1",
16541        );
16542        let ls_value = typed[last_state_layout.start_offset()];
16543        assert!(
16544            (ls_value - 6.0).abs() < 1e-5,
16545            "last_state expected 6.0 got {ls_value}"
16546        );
16547    }
16548
16549    /// E2E (row 172 item 2): TopKLastDim f32 on CPU through the bundled
16550    /// two-slot output. Row 0 has a NaN and tied values, row 1 distinct values;
16551    /// k = 3. The `values` View reads slot 0 and the `indices` View slot 1 of the
16552    /// SAME bundled storage (the indices slot starts 4-byte aligned).
16553    #[test]
16554    fn pipelined_realize_top_k_last_dim_bundled_values_and_indices() {
16555        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16556        let mut cache = StorageCache::new();
16557        let x_id = cpu_const_f32(
16558            &graph,
16559            &mut cache,
16560            &[1.0, 5.0, f32::NAN, 5.0, 2.0, 3.0, 3.0, 3.0, -1.0, 9.0],
16561            &[2, 5],
16562        );
16563        let (v_id, i_id) = {
16564            let x = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), x_id);
16565            let (v, i) = x.top_k_last_dim(3).expect("top_k_last_dim");
16566            (v.id(), i.id())
16567        };
16568        {
16569            let mut g = graph.write().unwrap();
16570            let producer = g.node(v_id).inputs[0];
16571            g.set_target_backend(producer, BackendId::Cpu);
16572        }
16573        let outputs = PipelinedExecutor::realize_many(Arc::clone(&graph), &[v_id, i_id], cache)
16574            .expect("realize_many");
16575        let (arc, v_layout) = outputs[0].clone();
16576        let (_, i_layout) = outputs[1].clone();
16577        let guard = arc.read().unwrap();
16578        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16579            panic!("expected Cpu storage");
16580        };
16581        let bytes = c.bytes();
16582        let vo = v_layout.start_offset() * 4;
16583        let io = i_layout.start_offset() * 4;
16584        let vals: Vec<f32> = bytes[vo..vo + 24]
16585            .chunks(4)
16586            .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
16587            .collect();
16588        let idx: Vec<u32> = bytes[io..io + 24]
16589            .chunks(4)
16590            .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
16591            .collect();
16592        assert_eq!(idx, vec![2, 1, 3, 4, 0, 1], "NaN first, ties by index");
16593        assert!(vals[0].is_nan());
16594        assert_eq!(&vals[1..], &[5.0, 5.0, 9.0, 3.0, 3.0]);
16595    }
16596
16597    /// E2E (row 172 item 2 step B): MatMulTopK f32 on CPU. Distinct matmul
16598    /// results, so the selection does not depend on accumulation order; the
16599    /// values and indices equal a hand matmul + top-2.
16600    #[test]
16601    fn pipelined_realize_matmul_top_k_f32() {
16602        // a [1, 2, 3], b [1, 3, 4]; row r of the result = a[r] @ b.
16603        let a = [1.0_f32, 2.0, 3.0, -1.0, 0.5, 2.0];
16604        let b = [
16605            1.0_f32, 0.0, 2.0, 1.0, 0.0, 1.0, 1.0, -1.0, 2.0, 1.0, 0.0, 3.0,
16606        ];
16607        let mut want_v = Vec::new();
16608        let mut want_i = Vec::new();
16609        for r in 0..2 {
16610            let row: Vec<f32> = (0..4)
16611                .map(|j| (0..3).map(|q| a[r * 3 + q] * b[q * 4 + j]).sum())
16612                .collect();
16613            let mut idx: Vec<usize> = (0..4).collect();
16614            idx.sort_by(|&x, &y| row[y].partial_cmp(&row[x]).unwrap());
16615            for &i in &idx[..2] {
16616                want_v.push(row[i]);
16617                want_i.push(i as u32);
16618            }
16619        }
16620        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16621        let mut cache = StorageCache::new();
16622        let a_id = cpu_const_f32(&graph, &mut cache, &a, &[1, 2, 3]);
16623        let b_id = cpu_const_f32(&graph, &mut cache, &b, &[1, 3, 4]);
16624        let (v_id, i_id) = {
16625            let at = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), a_id);
16626            let bt = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), b_id);
16627            let (v, i) = at.matmul_top_k(&bt, 2).expect("matmul_top_k");
16628            (v.id(), i.id())
16629        };
16630        {
16631            let mut g = graph.write().unwrap();
16632            let producer = g.node(v_id).inputs[0];
16633            g.set_target_backend(producer, BackendId::Cpu);
16634        }
16635        let outputs = PipelinedExecutor::realize_many(Arc::clone(&graph), &[v_id, i_id], cache)
16636            .expect("realize_many");
16637        let (arc, v_layout) = outputs[0].clone();
16638        let (_, i_layout) = outputs[1].clone();
16639        let guard = arc.read().unwrap();
16640        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16641            panic!("expected Cpu storage");
16642        };
16643        let bytes = c.bytes();
16644        let (vo, io) = (v_layout.start_offset() * 4, i_layout.start_offset() * 4);
16645        let vals: Vec<f32> = bytes[vo..vo + 16]
16646            .chunks(4)
16647            .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
16648            .collect();
16649        let idx: Vec<u32> = bytes[io..io + 16]
16650            .chunks(4)
16651            .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
16652            .collect();
16653        assert_eq!(idx, want_i);
16654        assert_eq!(vals, want_v);
16655    }
16656
16657    // ---- Ordering-defect repros (MLA decode multi-round WriteSlice) -----
16658
16659    /// DIAGNOSTIC (not a repro by itself): a plain single-hop view chain
16660    /// `S = Slice(X); K = Relu(S)` competing with a SECOND destructive
16661    /// WriteSlice on `X` (`Y = WriteSlice(X, ...)`) within one
16662    /// `realize_many` call. `collect_alias_set` adds `S` to `X`'s alias
16663    /// set (Slice IS `is_view_op`), so `derive_ordering` pins `Y` after
16664    /// `S`'s reader `K` directly. This form is expected to STAY GREEN —
16665    /// recorded here as the control that isolates the Reshape-specific
16666    /// gap exercised by the next test.
16667    #[test]
16668    fn pipelined_write_slice_round2_plain_slice_reader_not_stranded() {
16669        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16670        let mut cache = StorageCache::new();
16671
16672        let b_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16673        let src1_id = cpu_const_f32(&graph, &mut cache, &[1.0, 2.0], &[2]);
16674        let src2_id = cpu_const_f32(&graph, &mut cache, &[99.0, 98.0], &[2]);
16675
16676        let (k_id, y_id) = {
16677            let mut g = graph.write().unwrap();
16678            let x_id = g.push(Node {
16679                op: Op::WriteSlice {
16680                    ranges: vec![(0, 2)],
16681                    dyn_offset: None,
16682                },
16683                inputs: vec![b_id, src1_id],
16684                shape: Shape::from_dims(&[4]),
16685                dtype: DType::F32,
16686            });
16687            let s_id = g.push(Node {
16688                op: Op::Slice {
16689                    dim: 0,
16690                    start: 0,
16691                    len: 2,
16692                },
16693                inputs: vec![x_id],
16694                shape: Shape::from_dims(&[2]),
16695                dtype: DType::F32,
16696            });
16697            let k_id = g.push(Node {
16698                op: Op::Relu,
16699                inputs: vec![s_id],
16700                shape: Shape::from_dims(&[2]),
16701                dtype: DType::F32,
16702            });
16703            // Round 2 OVERLAPS round 1's [0,2) range so a wrong-order
16704            // execution would be numerically visible in K's output.
16705            let y_id = g.push(Node {
16706                op: Op::WriteSlice {
16707                    ranges: vec![(0, 2)],
16708                    dyn_offset: None,
16709                },
16710                inputs: vec![x_id, src2_id],
16711                shape: Shape::from_dims(&[4]),
16712                dtype: DType::F32,
16713            });
16714            g.set_target_backend(x_id, BackendId::Cpu);
16715            g.set_target_backend(k_id, BackendId::Cpu);
16716            g.set_target_backend(y_id, BackendId::Cpu);
16717            (k_id, y_id)
16718        };
16719
16720        let plan = fuel_graph::opt::execution_plan(&graph.read().unwrap(), &[k_id, y_id]);
16721        eprintln!("[diagnostic plain-slice] execution_plan = {:?}", plan,);
16722
16723        let outputs = PipelinedExecutor::realize_many(Arc::clone(&graph), &[k_id, y_id], cache)
16724            .expect("realize_many: plain slice reader must not error");
16725        let (k_arc, _) = &outputs[0];
16726        let guard = k_arc.read().unwrap();
16727        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16728            panic!("expected Cpu storage");
16729        };
16730        let out: &[f32] = c.as_slice().unwrap();
16731        assert_eq!(
16732            out,
16733            &[1.0, 2.0],
16734            "K = relu(slice(X,0,2)) must read PRE-round-2 bytes; got {:?}",
16735            out,
16736        );
16737    }
16738
16739    /// CRITICAL SUSPECT #2 repro: `Op::Reshape`/`Op::Contiguize` compile
16740    /// to `WorkItemKind::ContiguizeOf`, which zero-copy ADOPTS the
16741    /// input's Storage Arc when the input is contiguous at offset 0 —
16742    /// but `Op::Reshape` is NOT in `collect_alias_set`'s alias-extending
16743    /// predicate (only `Op::is_view_op` + `Op::View{..}`). So for
16744    /// `X = write_slice(B, src1); S = X.slice(0, 0, 2) [offset-0
16745    /// contiguous]; R = S.reshape([2]); K = relu(R); Y =
16746    /// write_slice(X, src2)`, `collect_alias_set(X)` stops at `{X, S}`
16747    /// — `R` never enters the alias set, so `derive_ordering` never
16748    /// scans `R`'s consumers (`K`) for pinning against `Y`. `K` and `Y`
16749    /// become simultaneously "ready" once `R` completes, and
16750    /// `execution_plan`'s stable tiebreak (smaller `topo_order_multi`
16751    /// position wins) can schedule `Y` (destructive) BEFORE `K` — `K`
16752    /// then dereferences `R`'s adopted Arc (== `X`'s Arc, mutated
16753    /// in-place by `Y`) and silently reads POST-`Y` bytes. No error;
16754    /// wrong numbers.
16755    #[test]
16756    fn pipelined_write_slice_reshape_adopted_arc_reader_reads_pre_write_bytes() {
16757        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16758        let mut cache = StorageCache::new();
16759
16760        let b_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16761        let src1_id = cpu_const_f32(&graph, &mut cache, &[1.0, 2.0], &[2]);
16762        let src2_id = cpu_const_f32(&graph, &mut cache, &[99.0, 98.0], &[2]);
16763
16764        let (x_id, k_id, y_id) = {
16765            let mut g = graph.write().unwrap();
16766            let x_id = g.push(Node {
16767                op: Op::WriteSlice {
16768                    ranges: vec![(0, 2)],
16769                    dyn_offset: None,
16770                },
16771                inputs: vec![b_id, src1_id],
16772                shape: Shape::from_dims(&[4]),
16773                dtype: DType::F32,
16774            });
16775            let s_id = g.push(Node {
16776                // OFFSET-0 contiguous prefix slice — ContiguizeOf's
16777                // zero-copy fast path requires this at execute time.
16778                op: Op::Slice {
16779                    dim: 0,
16780                    start: 0,
16781                    len: 2,
16782                },
16783                inputs: vec![x_id],
16784                shape: Shape::from_dims(&[2]),
16785                dtype: DType::F32,
16786            });
16787            let r_id = g.push(Node {
16788                op: Op::Reshape(Shape::from_dims(&[2])),
16789                inputs: vec![s_id],
16790                shape: Shape::from_dims(&[2]),
16791                dtype: DType::F32,
16792            });
16793            let k_id = g.push(Node {
16794                op: Op::Relu,
16795                inputs: vec![r_id],
16796                shape: Shape::from_dims(&[2]),
16797                dtype: DType::F32,
16798            });
16799            // Round 2 OVERLAPS round 1's [0,2) range (not the [2,4)
16800            // tail) so a wrong-order execution is numerically visible
16801            // in K's output — a disjoint round 2 would corrupt bytes
16802            // K never reads, masking the defect.
16803            let y_id = g.push(Node {
16804                op: Op::WriteSlice {
16805                    ranges: vec![(0, 2)],
16806                    dyn_offset: None,
16807                },
16808                inputs: vec![x_id, src2_id],
16809                shape: Shape::from_dims(&[4]),
16810                dtype: DType::F32,
16811            });
16812            g.set_target_backend(x_id, BackendId::Cpu);
16813            g.set_target_backend(k_id, BackendId::Cpu);
16814            g.set_target_backend(y_id, BackendId::Cpu);
16815            (x_id, k_id, y_id)
16816        };
16817        let _ = x_id;
16818
16819        let plan = fuel_graph::opt::execution_plan(&graph.read().unwrap(), &[k_id, y_id]);
16820        eprintln!(
16821            "[diagnostic reshape-adopted-arc] execution_plan = {:?}",
16822            plan,
16823        );
16824
16825        let outputs = PipelinedExecutor::realize_many(Arc::clone(&graph), &[k_id, y_id], cache)
16826            .expect("realize_many");
16827        let (k_arc, _) = &outputs[0];
16828        let guard = k_arc.read().unwrap();
16829        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16830            panic!("expected Cpu storage");
16831        };
16832        let out: &[f32] = c.as_slice().unwrap();
16833        // K = relu(reshape(slice(X,0,2))) must read PRE-round-2 bytes:
16834        // relu([1.0, 2.0]) = [1.0, 2.0]. Round 2 overwrites the SAME
16835        // [0,2) range with [99.0, 98.0] — if Y (round 2) runs before K
16836        // (the ordering defect), K instead observes [99.0, 98.0].
16837        assert_eq!(
16838            out,
16839            &[1.0, 2.0],
16840            "K must read PRE-round-2 bytes through the adopted Arc; got {:?} \
16841             (post-round-2 corruption if this fails)",
16842            out,
16843        );
16844    }
16845
16846    /// The MLA-decode shape from `rebind_latent_cache_fresh_graph`'s doc
16847    /// (`fuel-core/src/lazy_deepseek2.rs`): layer L's post-append buffer
16848    /// `X_L_N` (round N) is read TWICE within one realize call — once
16849    /// (non-destructively) through a Slice+Reshape "attention math" view
16850    /// chain whose result becomes an ancestor of layer L+1's round-N
16851    /// write, and again as the DESTINATION of layer L's round-(N+1)
16852    /// append. Reproduces the same Reshape-adoption gap as
16853    /// `pipelined_write_slice_reshape_adopted_arc_reader_reads_pre_write_bytes`
16854    /// at 2-layer scale, confirming the defect is not an artifact of the
16855    /// single-hop minimal form.
16856    #[test]
16857    fn pipelined_write_slice_mla_two_layer_round2_reshape_reader_not_stranded() {
16858        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16859        let mut cache = StorageCache::new();
16860
16861        let b_l_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16862        let src_l_n_id = cpu_const_f32(&graph, &mut cache, &[1.0, 2.0], &[2]);
16863        let b_l1_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16864        let src_l_n1_id = cpu_const_f32(&graph, &mut cache, &[99.0, 98.0], &[2]);
16865
16866        let (x_l_n1_id, x_l1_n_id) = {
16867            let mut g = graph.write().unwrap();
16868            // Round N, layer L: append src_l_n into b_l.
16869            let x_l_n = g.push(Node {
16870                op: Op::WriteSlice {
16871                    ranges: vec![(0, 2)],
16872                    dyn_offset: None,
16873                },
16874                inputs: vec![b_l_id, src_l_n_id],
16875                shape: Shape::from_dims(&[4]),
16876                dtype: DType::F32,
16877            });
16878            // "Attention math" for round N at layer L: read the filled
16879            // prefix, reshape (head-split-style hop), then a kernel.
16880            let s_l_n = g.push(Node {
16881                op: Op::Slice {
16882                    dim: 0,
16883                    start: 0,
16884                    len: 2,
16885                },
16886                inputs: vec![x_l_n],
16887                shape: Shape::from_dims(&[2]),
16888                dtype: DType::F32,
16889            });
16890            let rs_l_n = g.push(Node {
16891                op: Op::Reshape(Shape::from_dims(&[2])),
16892                inputs: vec![s_l_n],
16893                shape: Shape::from_dims(&[2]),
16894                dtype: DType::F32,
16895            });
16896            let r_l_n = g.push(Node {
16897                op: Op::Relu,
16898                inputs: vec![rs_l_n],
16899                shape: Shape::from_dims(&[2]),
16900                dtype: DType::F32,
16901            });
16902            // Round N, layer L+1: append the attention-math result.
16903            let x_l1_n = g.push(Node {
16904                op: Op::WriteSlice {
16905                    ranges: vec![(0, 2)],
16906                    dyn_offset: None,
16907                },
16908                inputs: vec![b_l1_id, r_l_n],
16909                shape: Shape::from_dims(&[4]),
16910                dtype: DType::F32,
16911            });
16912            // Round N+1, layer L: append into x_l_n directly (SAME node
16913            // s_l_n/rs_l_n/r_l_n read from) — OVERLAPPING range so a
16914            // wrong-order execution is numerically visible downstream.
16915            let x_l_n1 = g.push(Node {
16916                op: Op::WriteSlice {
16917                    ranges: vec![(0, 2)],
16918                    dyn_offset: None,
16919                },
16920                inputs: vec![x_l_n, src_l_n1_id],
16921                shape: Shape::from_dims(&[4]),
16922                dtype: DType::F32,
16923            });
16924            g.set_target_backend(x_l_n, BackendId::Cpu);
16925            g.set_target_backend(r_l_n, BackendId::Cpu);
16926            g.set_target_backend(x_l1_n, BackendId::Cpu);
16927            g.set_target_backend(x_l_n1, BackendId::Cpu);
16928            (x_l_n1, x_l1_n)
16929        };
16930
16931        let plan = fuel_graph::opt::execution_plan(&graph.read().unwrap(), &[x_l1_n_id, x_l_n1_id]);
16932        eprintln!("[diagnostic mla-2-layer] execution_plan = {:?}", plan);
16933
16934        let outputs =
16935            PipelinedExecutor::realize_many(Arc::clone(&graph), &[x_l1_n_id, x_l_n1_id], cache)
16936                .expect("realize_many");
16937        // outputs[0] = x_l1_n = write_slice(b_l1, relu(reshape(slice(x_l_n))))
16938        // Must reflect round-N's PRE-round-(N+1) bytes: relu([1,2]) = [1,2].
16939        let (x_l1_n_arc, _) = &outputs[0];
16940        let guard = x_l1_n_arc.read().unwrap();
16941        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16942            panic!("expected Cpu storage");
16943        };
16944        let out: &[f32] = c.as_slice().unwrap();
16945        assert_eq!(
16946            out,
16947            &[1.0, 2.0, 0.0, 0.0],
16948            "layer L+1's round-N append must reflect PRE-round-(N+1) attention \
16949             math output; got {:?} (post-round-(N+1) corruption if this fails)",
16950            out,
16951        );
16952    }
16953}