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        for item in &items {
1571            let _handle = execute_work_item(
1572                item,
1573                &mut warm_cache,
1574                &mut warm_devices,
1575                &mut warm_layouts,
1576                &mut warm_syms,
1577                false,
1578                Some(&mut persistent),
1579            )
1580            .map_err(|e| with_node_location(&graph, item.node_id, e))?;
1581        }
1582        // Flush all warm launches before capture (device idle; result stable).
1583        sync_active_cuda_devices(&warm_cache)?;
1584
1585        let output = warm_cache.get(&target).cloned().ok_or_else(|| {
1586            Error::Msg(format!(
1587                "capture_decode: target {:?} not realized in warm run",
1588                target,
1589            ))
1590            .bt()
1591        })?;
1592        let output_layout = warm_layouts.get(&target).cloned().ok_or_else(|| {
1593            Error::Msg(format!("capture_decode: target {:?} has no layout", target)).bt()
1594        })?;
1595
1596        // Derive the CUDA device from the target's storage for capture_run.
1597        let device = {
1598            let guard = output.read().map_err(|_| poisoned("output storage"))?;
1599            match &guard.inner {
1600                BackendStorage::Cuda(c) => c.device().clone(),
1601                other => {
1602                    return Err(Error::Msg(format!(
1603                        "capture_decode: target {:?} is BackendStorage::{:?}, not Cuda",
1604                        target,
1605                        other.backend_id(),
1606                    ))
1607                    .bt());
1608                }
1609            }
1610        };
1611
1612        // ---- Pass 2: capture (reuse) — record the launch sequence ----------
1613        let mut reuse = PersistentOutputs::reuse(persistent.into_map());
1614        // Retain EVERY input buffer before `inputs` is consumed: the captured
1615        // graph bakes their device addresses, so they must outlive it even if
1616        // the caller doesn't independently hold them.
1617        let retained_inputs: Vec<Arc<RwLock<Storage>>> = inputs.values().cloned().collect();
1618        let mut cap_cache: StorageCache = inputs;
1619        let mut cap_layouts = seed_layouts;
1620        let mut cap_syms = SymEnv::new();
1621        let mut cap_devices = cuda_registry_of_inputs(&cap_cache);
1622        let mut inner_err: Option<Error> = None;
1623        let items_ref = &items;
1624        let graph_ref = &graph;
1625        let run = device.capture_run(|_stream| {
1626            // Inside the capture scope: NO device alloc, NO host sync. Each
1627            // kernel launches on device.stream() (now capturing) and writes
1628            // into its reused fixed buffer.
1629            for item in items_ref {
1630                match execute_work_item(
1631                    item,
1632                    &mut cap_cache,
1633                    &mut cap_devices,
1634                    &mut cap_layouts,
1635                    &mut cap_syms,
1636                    false,
1637                    Some(&mut reuse),
1638                ) {
1639                    Ok(_handle) => {}
1640                    Err(e) => {
1641                        inner_err = Some(with_node_location(graph_ref, item.node_id, e));
1642                        break;
1643                    }
1644                }
1645            }
1646            Ok(())
1647        })?;
1648        if let Some(e) = inner_err {
1649            return Err(e);
1650        }
1651
1652        Ok(CapturedDecode {
1653            run,
1654            output,
1655            output_layout,
1656            retained_inputs,
1657            persistent: reuse.into_map(),
1658        })
1659    }
1660
1661    fn realize_inner(
1662        graph: Arc<RwLock<Graph>>,
1663        target: NodeId,
1664        inputs: StorageCache,
1665        order_source: OrderSource<'_>,
1666        sym_env: SymEnv,
1667    ) -> Result<(Arc<RwLock<Storage>>, Layout, SymEnv)> {
1668        Self::realize_inner_with(
1669            graph,
1670            target,
1671            inputs,
1672            order_source,
1673            sym_env,
1674            DeviceRegistry::new(),
1675        )
1676    }
1677
1678    /// [`Self::realize_inner`] with the device handles the caller already holds.
1679    fn realize_inner_with(
1680        graph: Arc<RwLock<Graph>>,
1681        target: NodeId,
1682        inputs: StorageCache,
1683        order_source: OrderSource<'_>,
1684        sym_env: SymEnv,
1685        device_handles: DeviceRegistry,
1686    ) -> Result<(Arc<RwLock<Storage>>, Layout, SymEnv)> {
1687        // Auto-insert safety copies for in-place ops whose target
1688        // has additional readers in this realize set (residual-
1689        // connection cycle break). No-op when no destructive ops
1690        // are present.
1691        {
1692            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.safety_copies");
1693            let mut g = graph.write().map_err(|_| poisoned("graph lock"))?;
1694            let effective_roots = extend_with_side_effect_roots(&g, &[target]);
1695            insert_safety_copies(&mut g, &effective_roots);
1696        }
1697
1698        // Execution plan + initial layouts for the input cache
1699        // entries, computed on the calling thread to keep the
1700        // compiler thread free of graph-locking responsibilities.
1701        // Side-effect roots (Op::Print, Op::Save, etc.) are merged
1702        // into the walk so their effects fire even when not
1703        // reachable from the user's `target`. `execution_plan`
1704        // integrates `derive_ordering`'s view-aware pinning so
1705        // destructive ops run AFTER non-destructive readers of
1706        // their targets.
1707        let (compiler_work, wait_set, mut layout_cache): (
1708            CompilerWork,
1709            WaitSet,
1710            HashMap<NodeId, Layout>,
1711        ) = {
1712            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.plan_order");
1713            let g = graph.read().map_err(|_| poisoned("graph lock"))?;
1714            let effective_roots = extend_with_side_effect_roots(&g, &[target]);
1715            // PR-A3b-1: the OptimizedGraph path lowers via
1716            // `extract_runs`/`lower_run` (computed here, AFTER
1717            // `insert_safety_copies`, so the order covers freshly
1718            // inserted safety-copy nodes). The default path keeps the
1719            // pre-A3b-1 `execution_plan` walk. On a branchless graph the
1720            // two sequences are identical (A3a equivalence gate).
1721            //
1722            // PR-C1: a `Streaming` source is NOT flattened here — it is
1723            // handed to the compiler thread as a `CompilerWork::Streaming`
1724            // spec so the thread resolves each branch lazily at the
1725            // frontier (see `compiler_thread_body`).
1726            //
1727            // Step E A4b open question #4: the SAME pass also derives the
1728            // `WaitSet` from the materialized order ("event only where
1729            // waited" — see `compiler_work_and_wait_set_for`).
1730            let (work, wait_set) =
1731                compiler_work_and_wait_set_for(&g, &effective_roots, &order_source);
1732            let mut layouts = HashMap::with_capacity(inputs.len());
1733            for &id in inputs.keys() {
1734                layouts.insert(id, g.layout(id));
1735            }
1736            (work, wait_set, layouts)
1737        };
1738
1739        let (tx, rx) = channel::<Result<WorkItem>>();
1740        let graph_for_compiler = Arc::clone(&graph);
1741
1742        // Compiler thread: read graph nodes, resolve kernels,
1743        // push WorkItems. On error, push the error and bail. PR-C1: for a
1744        // `Streaming` work spec the thread also resolves each branch's arm
1745        // at the frontier (the SAME VRAM-only selector the one-shot picker
1746        // uses) before compiling that arm's runs.
1747        let compiler = {
1748            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.spawn_compiler");
1749            thread::spawn(move || {
1750                let _t = crate::compiled::op_profile::PhaseTimer::start(
1751                    "compiler_thread (runs concurrently)",
1752                );
1753                compiler_thread_body(graph_for_compiler, compiler_work, sym_env, tx);
1754            })
1755        };
1756
1757        // Executor on this thread: consume WorkItems, gather
1758        // inputs from the cache, allocate outputs, call kernels,
1759        // populate the cache. After each destructive op
1760        // (Op::Release / Op::Move) evict the destroyed input from
1761        // the cache, unless it's the realize target.
1762        //
1763        // Phase 4.3: at each dispatch-chunk boundary (target_backend
1764        // change), check the live SystemTopology generation against
1765        // the plan's stamped generation. Mismatch surfaces
1766        // `Error::TopologyChanged`; the realize layer
1767        // (`pipelined_bridge`) catches it, rebuilds the plan against
1768        // the fresh topology, and retries.
1769        let plan_generation: Option<u64> = generation_for(&order_source);
1770        let mut current_chunk_backend: Option<BackendId> = None;
1771        let mut cache: StorageCache = inputs;
1772        let mut devices = device_handles;
1773        // Data-dependent dynamic-shapes: symbols BOUND BY PRODUCERS during
1774        // this pass (e.g. `Op::NonZeroIndices`'s runtime count). Distinct
1775        // from the compile-time `sym_env` (input-determined, moved into the
1776        // compiler thread): these become known only as ops execute. Returned
1777        // to the caller so a downstream pass can consume them.
1778        let mut produced_syms = SymEnv::new();
1779        // Step E A4b-1: per-node async-completion handles. Each producing node's
1780        // `execute_compiled` returns a `CompletionHandle` (CUDA → a recorded
1781        // `Event`; CPU/Vulkan → `Ready`) instead of being `wait`ed inline. We
1782        // store them here, wait the SOURCE producer's handle before a
1783        // cross-device copy (A4b-3, below), and drain whatever remains at
1784        // realize-end.
1785        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
1786        // Step E A4b-4: eagerly-submitted-but-not-yet-waited Vulkan batches. The
1787        // OVERLAP enabler — when we LEAVE a Vulkan chunk (or are about to block on
1788        // a CUDA copy) we `submit_pending` the open Vulkan batch so the iGPU runs
1789        // it while the executor records/dispatches the next (CUDA) chunk, instead
1790        // of letting it sit merely-recorded until realize-end (the A4b-2 behavior,
1791        // which never overlapped). Each submitted batch is tracked here and waited
1792        // at the in-flight-lifetime guard (before a Vulkan read / Vulkan-referenced
1793        // eviction / realize-end). `multi_backend` gates ALL eager submits so a
1794        // single-device realize never touches this path (byte-identical to A4b-2).
1795        let mut inflight_vulkan: Vec<InflightVulkan> = Vec::new();
1796        // Step E A4b-4: set true the first time the dispatch order transitions
1797        // between two DIFFERENT non-CPU... actually any two distinct backends — a
1798        // genuine backend switch. On a pure-CUDA or pure-Vulkan graph there is no
1799        // switch, so this stays false and the eager-submit / in-flight machinery is
1800        // unreachable (single-device byte-identical + throughput-neutral, §5).
1801        let mut multi_backend = false;
1802        let loop_total = crate::compiled::op_profile::PhaseTimer::start("realize.loop_total");
1803        loop {
1804            let t_wait =
1805                crate::compiled::op_profile::PhaseTimer::start("realize.wait_for_compiler");
1806            let Ok(item) = rx.recv() else {
1807                break;
1808            };
1809            drop(t_wait);
1810            let item = item?;
1811            // Chunk-boundary hook (target_backend change). Existing duty: the
1812            // `TopologyChanged` generation check. Step E A4b-4 adds two duties:
1813            // (1) detect a genuine backend switch → arm `multi_backend`; (2) when
1814            // LEAVING a Vulkan chunk on a multi-backend graph, eager-submit the
1815            // open Vulkan batch so the iGPU starts it concurrently with the chunk
1816            // we are about to dispatch (the overlap win).
1817            if !is_backend_neutral(&item.kind) && current_chunk_backend != Some(item.target_backend)
1818            {
1819                if let Some(plan_gen) = plan_generation {
1820                    let live = crate::dispatch::topology_generation();
1821                    if live != plan_gen {
1822                        return Err(Error::TopologyChanged {
1823                            plan_generation: plan_gen,
1824                            current_generation: live,
1825                        }
1826                        .bt());
1827                    }
1828                }
1829                let leaving = current_chunk_backend;
1830                if let Some(prev) = leaving
1831                    && prev != item.target_backend
1832                {
1833                    // A real backend switch occurred — this realize is
1834                    // genuinely multi-backend.
1835                    multi_backend = true;
1836                    // Leaving a Vulkan chunk → submit it NOW so it runs on the
1837                    // iGPU while we record/dispatch the next chunk. Whole-chunk
1838                    // granularity (the open batch IS the just-finished Vulkan
1839                    // chunk with all its intra-CB barriers) — UAF/race-safe per
1840                    // `eager_submit_all_vulkan`'s contract.
1841                    if prev == BackendId::Vulkan {
1842                        {
1843                            let _pt = crate::compiled::op_profile::PhaseTimer::start(
1844                                "realize.eager_submit_vulkan",
1845                            );
1846                            eager_submit_all_vulkan(&cache, &mut inflight_vulkan)?;
1847                        }
1848                    }
1849                }
1850                current_chunk_backend = Some(item.target_backend);
1851            }
1852            // Vulkan realizes run the async path (deferred eviction, size-based eager
1853            // submit) even on a single device: ordering between batches is structural
1854            // (inter-batch barrier + epoch-gated buffer reuse), not a host wait.
1855            if item.target_backend == BackendId::Vulkan && matches!(item.kind, WorkItemKind::Kernel)
1856            {
1857                multi_backend = true;
1858            }
1859            // Same-device cross-chunk RAW/WAR safety between Vulkan batches (the old
1860            // "Invariant E": wait every in-flight Vulkan batch on the HOST before
1861            // recording a new Vulkan op) is now structural: the Vulkan recorder
1862            // starts every batch with a memory barrier whose first scope covers all
1863            // earlier submissions on the queue (`Recorder::record_inter_batch_barrier`),
1864            // so a later batch cannot read or overwrite what an earlier in-flight
1865            // one is still using. The host therefore keeps recording while the
1866            // GPU runs the batches already submitted; waits remain only where the
1867            // host needs a result (D2H reads), before freeing a buffer, and at
1868            // realize-end.
1869            // Step E A4b-3 + A4b-4: the cross-device residency boundary.
1870            if matches!(
1871                item.kind,
1872                WorkItemKind::Copy { .. } | WorkItemKind::Move { .. }
1873            ) {
1874                // A4b-4: before we (possibly) block the host on the CUDA producer,
1875                // eager-submit any open Vulkan chunk so the iGPU runs it WHILE we
1876                // wait on CUDA (the §5.1 ordering — submit Vulkan *before* draining
1877                // CUDA). Cheap + safe; gated to multi-backend (no-op single-device).
1878                if multi_backend {
1879                    {
1880                        let _pt = crate::compiled::op_profile::PhaseTimer::start(
1881                            "realize.eager_submit_vulkan",
1882                        );
1883                        eager_submit_all_vulkan(&cache, &mut inflight_vulkan)?;
1884                    }
1885                }
1886                if let Some(&producer) = item.inputs.first() {
1887                    // A4b-4: a VULKAN-source D2H must read COMPLETED data, and the
1888                    // Vulkan download path only flushes the OPEN batch (not our
1889                    // in-flight ones) — so wait the in-flight Vulkan batches here.
1890                    // For a CUDA/CPU source we do NOT wait Vulkan (the copy reads no
1891                    // Vulkan buffer); waiting it would needlessly serialize the
1892                    // independent Vulkan sub-DAG and kill the overlap. The Vulkan
1893                    // work that was eager-submitted at the chunk boundary keeps
1894                    // running concurrently until ITS result is the one being copied.
1895                    if multi_backend && copy_source_is_vulkan(&cache, producer)? {
1896                        {
1897                            let _pt = crate::compiled::op_profile::PhaseTimer::start(
1898                                "realize.drain_inflight_vulkan",
1899                            );
1900                            drain_inflight_vulkan(&mut inflight_vulkan)?;
1901                        }
1902                    }
1903                    // Step E A4b-3: FINER CUDA source-drain — wait ONLY the source
1904                    // producer's recorded event (not the whole source device), so
1905                    // the OTHER sub-DAG's independent in-flight CUDA work keeps
1906                    // running. No-op for a Vulkan/CPU producer (no CUDA handle).
1907                    wait_producer_handle(&mut handles, producer)?;
1908                }
1909            }
1910            let t_exec =
1911                crate::compiled::op_profile::PhaseTimer::start(work_item_kind_name(&item.kind));
1912            let handle = execute_work_item(
1913                &item,
1914                &mut cache,
1915                &mut devices,
1916                &mut layout_cache,
1917                &mut produced_syms,
1918                will_be_waited(&wait_set, item.node_id),
1919                // No persistent-output mode on the standard realize paths —
1920                // fresh alloc per node, byte-identical to pre-CapturedRun.
1921                None,
1922            )
1923            .map_err(|e| with_node_location(&graph, item.node_id, e))?;
1924            drop(t_exec);
1925            store_handle(&mut handles, item.node_id, handle);
1926            if let Some(d_idx) = item.destructive_input
1927                && let Some(&destroyed) = item.inputs.get(d_idx)
1928                && destroyed != target
1929            {
1930                // Step E A2.1 (in-flight-batch DATA-BUFFER lifetime — the
1931                // UAF guard, now DEFERRED-DELETION instead of a drain). A
1932                // `SubmittedBatch` owns its CB/descriptors/transients but
1933                // NOT the DATA buffers it reads (those live here in the
1934                // cache); recycling a data buffer an in-flight/open CB still
1935                // reads is a use-after-free. PRE-A2.1 we host-blocked here —
1936                // `drain_inflight_vulkan` (wait every in-flight batch) +
1937                // `force_flush` (submit+wait the open batch) — which stalled
1938                // the iGPU work we were overlapping with CUDA at EVERY such
1939                // eviction. A2.1 instead RETAINS the evicted buffer until the
1940                // reader fences signal: it eager-submits the open batch (no
1941                // wait → it becomes a fenced in-flight batch) and moves a
1942                // refcount clone of the buffer into every in-flight batch, so
1943                // the buffer frees POST-fence on each batch's `Drop`
1944                // (follow-on #2) with NO host block. Conservative over all
1945                // batches (no cheap buffer→batch map — the same reason the old
1946                // drain waited all of them). CUDA eviction is stream-ordered-
1947                // safe via A3. Single-device (multi_backend == false) keeps the
1948                // pre-A2.1 blocking force_flush of the OPEN batch (the else
1949                // branch) — byte-identical + UAF-safe there; the deferred path is
1950                // unsafe single-device (no eager-submit/in-flight tracking, and the
1951                // cross-batch RAW guard at :832 doesn't run — see
1952                // force_flush_vulkan's doc).
1953                let _t =
1954                    crate::compiled::op_profile::PhaseTimer::start("realize.evict_destroyed_input");
1955                if multi_backend {
1956                    defer_evicted_vulkan_buffer(&cache, destroyed, &mut inflight_vulkan)?;
1957                } else if let Some(d_arc) = cache.get(&destroyed) {
1958                    let _f = crate::compiled::op_profile::PhaseTimer::start(
1959                        "realize.evict_force_flush_vulkan",
1960                    );
1961                    force_flush_vulkan(d_arc)?;
1962                }
1963                cache.remove(&destroyed);
1964                layout_cache.remove(&destroyed);
1965                // Drop the evicted node's CUDA handle (if still present)
1966                // so the realize-end drain's empty-map assert stays
1967                // meaningful. The free itself is stream-ordered-safe (A3).
1968                handles.remove(&destroyed);
1969            }
1970        }
1971
1972        drop(loop_total);
1973        {
1974            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.join_compiler");
1975            compiler
1976                .join()
1977                .map_err(|_| Error::Msg("compiler thread panicked".to_string()).bt())?;
1978        }
1979
1980        // Step E A4b-1: drain every outstanding async handle before the result is
1981        // read / the cache drops (freeing intermediates). For CUDA this waits the
1982        // recorded events (one stream/device ⇒ waiting the latest drains all prior
1983        // stream work too; see `drain_handles`).
1984        let post_loop = crate::compiled::op_profile::PhaseTimer::start("realize.post_loop_drains");
1985        drain_handles(&mut handles)?;
1986        // Step E A4b open question #4 — "event only where waited": most CUDA
1987        // nodes in this realize never got an Event (elided per the `WaitSet`),
1988        // so `drain_handles` above only retired the (typically few) tracked
1989        // handles. This blanket per-device `cuStreamSynchronize` flushes the
1990        // elided work too — safe + sufficient because of single-stream-per-
1991        // device ordering (see `sync_active_cuda_devices`'s doc).
1992        sync_active_cuda_devices(&cache)?;
1993        // Step E A4b-4: wait every eagerly-submitted (in-flight) Vulkan batch
1994        // before the cache drops, freeing the data buffers their CBs read. Empty
1995        // on a single-device realize (nothing was eager-submitted).
1996        {
1997            let _pt =
1998                crate::compiled::op_profile::PhaseTimer::start("realize.drain_inflight_vulkan");
1999            drain_inflight_vulkan(&mut inflight_vulkan)?;
2000        }
2001        // Step E A4b-2: drain all deferred Vulkan work before reading/returning
2002        // the result (and before the cache drops, freeing buffers). The A2
2003        // submit+wait is now SPLIT — `drain_vulkan_pending` submits the open
2004        // batch then waits it via a `VulkanCompletion` handle. Byte-identical to
2005        // A2 for pure-Vulkan (one submission at realize-end, just split).
2006        drain_vulkan_pending(&cache)?;
2007        debug_assert!(
2008            inflight_vulkan.is_empty(),
2009            "A4b-4: in-flight Vulkan batch list must be empty after realize-end drain",
2010        );
2011
2012        drop(post_loop);
2013        let storage = cache.remove(&target).ok_or_else(|| {
2014            Error::Msg(format!(
2015                "PipelinedExecutor::realize: target slot {:?} not populated after execution",
2016                target
2017            ))
2018            .bt()
2019        })?;
2020        let layout = layout_cache.remove(&target).ok_or_else(|| {
2021            Error::Msg(format!(
2022                "PipelinedExecutor::realize: target layout {:?} not populated after execution",
2023                target
2024            ))
2025            .bt()
2026        })?;
2027        {
2028            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.drop_cache");
2029            drop(cache);
2030            drop(handles);
2031            drop(layout_cache);
2032        }
2033        Ok((storage, layout, produced_syms))
2034    }
2035
2036    /// Realize multiple targets in one walk. Each target's transitive
2037    /// dependency set is collapsed into a single execution plan
2038    /// (via [`execution_plan`]); shared subgraphs are evaluated
2039    /// once. Returns a `Vec<(Storage, Layout)>` whose order matches
2040    /// `targets`.
2041    ///
2042    /// This is Phase A of Phase 7.6 step 9c — feature-parity with the
2043    /// legacy `GraphExecutor::realize_many_f32`. Multi-session
2044    /// migration target ([memory: project_phase_7_6_step_9c_parity_audit.md]).
2045    ///
2046    /// Pre-conditions: every reachable `Op::Const` must be in
2047    /// `inputs`; every reachable non-`Const` must have its
2048    /// `target_backend` set; the op + dtype must be registered in
2049    /// `global_bindings()`. Same as single-target [`Self::realize`].
2050    pub fn realize_many(
2051        graph: Arc<RwLock<Graph>>,
2052        targets: &[NodeId],
2053        inputs: StorageCache,
2054    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2055        Self::realize_many_inner(
2056            graph,
2057            targets,
2058            inputs,
2059            OrderSource::Default,
2060            SymEnv::default(),
2061        )
2062    }
2063
2064    /// [`Self::realize_many`] with the device handles the caller already holds (ROADMAP row 137, seam S3
2065    /// step 3b).
2066    pub fn realize_many_with_devices(
2067        graph: Arc<RwLock<Graph>>,
2068        targets: &[NodeId],
2069        inputs: StorageCache,
2070        devices: DeviceRegistry,
2071    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2072        Self::realize_many_inner_with(
2073            graph,
2074            targets,
2075            inputs,
2076            OrderSource::Default,
2077            SymEnv::default(),
2078            devices,
2079        )
2080    }
2081
2082    /// [`Self::realize_many_with_optimized_picking_env`] with the device handles the caller already holds.
2083    #[allow(clippy::too_many_arguments)]
2084    pub fn realize_many_with_optimized_picking_env_with_devices(
2085        graph: Arc<RwLock<Graph>>,
2086        targets: &[NodeId],
2087        inputs: StorageCache,
2088        optimized: &OptimizedGraph,
2089        selector: Option<Arc<dyn RuntimeSelector>>,
2090        lookup: Option<BackendRuntimeLookup>,
2091        sym_env: SymEnv,
2092        devices: DeviceRegistry,
2093    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2094        let order_source = match Self::streaming_pick_for(&graph, selector, lookup)? {
2095            Some(pick) => {
2096                return Self::realize_many_inner_with(
2097                    graph,
2098                    targets,
2099                    inputs,
2100                    OrderSource::Streaming {
2101                        optimized,
2102                        pick: &pick,
2103                    },
2104                    sym_env,
2105                    devices,
2106                );
2107            }
2108            None => OrderSource::Optimized {
2109                optimized,
2110                route: None,
2111            },
2112        };
2113        Self::realize_many_inner_with(graph, targets, inputs, order_source, sym_env, devices)
2114    }
2115
2116    /// Multi-target PR-A3b-1 entry — the `realize_many` sibling of
2117    /// [`Self::realize_with_optimized`]. Drives the executor from the
2118    /// `OptimizedGraph`'s run lowering via the binding-table-lookup
2119    /// path, with the optimize-time `generation` keying the
2120    /// `TopologyChanged` chunk-boundary check.
2121    pub fn realize_many_with_optimized(
2122        graph: Arc<RwLock<Graph>>,
2123        targets: &[NodeId],
2124        inputs: StorageCache,
2125        optimized: &OptimizedGraph,
2126    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2127        Self::realize_many_inner(
2128            graph,
2129            targets,
2130            inputs,
2131            OrderSource::Optimized {
2132                optimized,
2133                route: None,
2134            },
2135            SymEnv::default(),
2136        )
2137    }
2138
2139    /// Env-carrying sibling of [`Self::realize_many_with_optimized`] (Phase D
2140    /// symbolic extents). An empty env is byte-identical to it.
2141    pub fn realize_many_with_optimized_env(
2142        graph: Arc<RwLock<Graph>>,
2143        targets: &[NodeId],
2144        inputs: StorageCache,
2145        optimized: &OptimizedGraph,
2146        sym_env: SymEnv,
2147    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2148        Self::realize_many_inner(
2149            graph,
2150            targets,
2151            inputs,
2152            OrderSource::Optimized {
2153                optimized,
2154                route: None,
2155            },
2156            sym_env,
2157        )
2158    }
2159
2160    /// Multi-target PR-C1 entry — the `realize_many` sibling of
2161    /// [`Self::realize_with_optimized_route`]. Lowers each target's runs
2162    /// following the picker's chosen arms via
2163    /// [`fuel_graph::lower_picked_route`].
2164    pub fn realize_many_with_optimized_route(
2165        graph: Arc<RwLock<Graph>>,
2166        targets: &[NodeId],
2167        inputs: StorageCache,
2168        optimized: &OptimizedGraph,
2169        route: &PickedRoute,
2170    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2171        Self::realize_many_inner(
2172            graph,
2173            targets,
2174            inputs,
2175            OrderSource::Optimized {
2176                optimized,
2177                route: Some(route),
2178            },
2179            SymEnv::default(),
2180        )
2181    }
2182
2183    /// Env-carrying sibling of [`Self::realize_many_with_optimized_route`]
2184    /// (Phase D symbolic extents). An empty env is byte-identical to it.
2185    pub fn realize_many_with_optimized_route_env(
2186        graph: Arc<RwLock<Graph>>,
2187        targets: &[NodeId],
2188        inputs: StorageCache,
2189        optimized: &OptimizedGraph,
2190        route: &PickedRoute,
2191        sym_env: SymEnv,
2192    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2193        Self::realize_many_inner(
2194            graph,
2195            targets,
2196            inputs,
2197            OrderSource::Optimized {
2198                optimized,
2199                route: Some(route),
2200            },
2201            sym_env,
2202        )
2203    }
2204
2205    /// Multi-target sibling of [`Self::realize_with_optimized_picking_env`] —
2206    /// the executor resolves one arm per `Op::Branch` (cleanup Step C/D) over
2207    /// the effective targets. PR C1: a branched graph routes to the
2208    /// `OrderSource::Streaming` walk (lazy per-branch resolution at the
2209    /// frontier); branchless / no-selector falls to the untouched arm-0 path.
2210    pub fn realize_many_with_optimized_picking_env(
2211        graph: Arc<RwLock<Graph>>,
2212        targets: &[NodeId],
2213        inputs: StorageCache,
2214        optimized: &OptimizedGraph,
2215        selector: Option<Arc<dyn RuntimeSelector>>,
2216        lookup: Option<BackendRuntimeLookup>,
2217        sym_env: SymEnv,
2218    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2219        match Self::streaming_pick_for(&graph, selector, lookup)? {
2220            Some(pick) => Self::realize_many_inner(
2221                graph,
2222                targets,
2223                inputs,
2224                OrderSource::Streaming {
2225                    optimized,
2226                    pick: &pick,
2227                },
2228                sym_env,
2229            ),
2230            None => {
2231                Self::realize_many_with_optimized_env(graph, targets, inputs, optimized, sym_env)
2232            }
2233        }
2234    }
2235
2236    fn realize_many_inner(
2237        graph: Arc<RwLock<Graph>>,
2238        targets: &[NodeId],
2239        inputs: StorageCache,
2240        order_source: OrderSource<'_>,
2241        sym_env: SymEnv,
2242    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2243        Self::realize_many_inner_with(
2244            graph,
2245            targets,
2246            inputs,
2247            order_source,
2248            sym_env,
2249            DeviceRegistry::new(),
2250        )
2251    }
2252
2253    /// [`Self::realize_many_inner`] with the device handles the caller already holds.
2254    fn realize_many_inner_with(
2255        graph: Arc<RwLock<Graph>>,
2256        targets: &[NodeId],
2257        inputs: StorageCache,
2258        order_source: OrderSource<'_>,
2259        sym_env: SymEnv,
2260        device_handles: DeviceRegistry,
2261    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2262        if targets.is_empty() {
2263            return Ok(Vec::new());
2264        }
2265
2266        // Auto-insert safety copies for in-place ops whose target
2267        // has additional readers in this realize set (residual-
2268        // connection cycle break). No-op when no destructive ops
2269        // are present.
2270        {
2271            let mut g = graph.write().map_err(|_| poisoned("graph lock"))?;
2272            let effective_roots = extend_with_side_effect_roots(&g, targets);
2273            insert_safety_copies(&mut g, &effective_roots);
2274        }
2275
2276        // Execution plan covering every target's dependency set +
2277        // initial layouts for the input cache entries. Side-effect
2278        // roots merge in so their effects fire even when not
2279        // reachable from any target. `execution_plan` integrates
2280        // `derive_ordering`'s view-aware pinning so destructive ops
2281        // run AFTER non-destructive readers of their targets.
2282        let (compiler_work, wait_set, mut layout_cache): (
2283            CompilerWork,
2284            WaitSet,
2285            HashMap<NodeId, Layout>,
2286        ) = {
2287            let g = graph.read().map_err(|_| poisoned("graph lock"))?;
2288            let effective_roots = extend_with_side_effect_roots(&g, targets);
2289            // PR-A3b-1: derive from the OptimizedGraph's run lowering
2290            // when present (post-safety-copies); else the legacy
2291            // `execution_plan` walk. Identical on branchless graphs.
2292            //
2293            // PR-C1: a `Streaming` source is handed to the compiler thread
2294            // unflattened (resolves branches at the frontier).
2295            //
2296            // Step E A4b open question #4: also derives the `WaitSet`
2297            // ("event only where waited") from the same materialized order.
2298            let (work, wait_set) =
2299                compiler_work_and_wait_set_for(&g, &effective_roots, &order_source);
2300            let mut layouts = HashMap::with_capacity(inputs.len());
2301            for &id in inputs.keys() {
2302                layouts.insert(id, g.layout(id));
2303            }
2304            (work, wait_set, layouts)
2305        };
2306
2307        // Caller's target set — used to gate destructive-input
2308        // eviction so we don't drop a tensor the caller asked for.
2309        let target_set: std::collections::HashSet<NodeId> = targets.iter().copied().collect();
2310
2311        let (tx, rx) = channel::<Result<WorkItem>>();
2312        let graph_for_compiler = Arc::clone(&graph);
2313
2314        let compiler = thread::spawn(move || {
2315            compiler_thread_body(graph_for_compiler, compiler_work, sym_env, tx);
2316        });
2317
2318        // Phase 4.3: per-chunk SystemTopology generation check (see
2319        // realize_inner for the rationale). PR-A3b-1: the OptimizedGraph
2320        // path supplies its own optimize-time generation.
2321        let plan_generation: Option<u64> = generation_for(&order_source);
2322        let mut current_chunk_backend: Option<BackendId> = None;
2323        let mut cache: StorageCache = inputs;
2324        let mut devices = device_handles;
2325        // Data-dependent dynamic-shapes producer-bound symbols (see
2326        // `realize_inner`). `realize_many` does not expose them today; the
2327        // env is dropped at pass end (producers still publish, keeping the
2328        // seam uniform across both realize loops).
2329        let mut produced_syms = SymEnv::new();
2330        // Step E A4b-1/A4b-3: per-node async-completion handles (see realize_inner
2331        // for the full rationale). Map drained at realize-end; the cross-device
2332        // copy waits the SOURCE producer's handle (A4b-3).
2333        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
2334        // Step E A4b-4: eagerly-submitted in-flight Vulkan batches + the
2335        // multi-backend gate. See realize_inner for the full rationale — this is
2336        // the identical eager-submit / in-flight-lifetime machinery applied to the
2337        // multi-target walk. `multi_backend` arms on a genuine backend switch and
2338        // gates every eager submit, so a single-device realize_many is
2339        // byte-identical to A4b-2.
2340        let mut inflight_vulkan: Vec<InflightVulkan> = Vec::new();
2341        let mut multi_backend = false;
2342        for item in rx {
2343            let item = item?;
2344            // Chunk-boundary hook: TopologyChanged check + (A4b-4) backend-switch
2345            // detection + eager-submit-on-leaving-a-Vulkan-chunk.
2346            if !is_backend_neutral(&item.kind) && current_chunk_backend != Some(item.target_backend)
2347            {
2348                if let Some(plan_gen) = plan_generation {
2349                    let live = crate::dispatch::topology_generation();
2350                    if live != plan_gen {
2351                        return Err(Error::TopologyChanged {
2352                            plan_generation: plan_gen,
2353                            current_generation: live,
2354                        }
2355                        .bt());
2356                    }
2357                }
2358                let leaving = current_chunk_backend;
2359                if let Some(prev) = leaving
2360                    && prev != item.target_backend
2361                {
2362                    multi_backend = true;
2363                    if prev == BackendId::Vulkan {
2364                        eager_submit_all_vulkan(&cache, &mut inflight_vulkan)?;
2365                    }
2366                }
2367                current_chunk_backend = Some(item.target_backend);
2368            }
2369            // Vulkan realizes run the async path (deferred eviction, size-based eager
2370            // submit) even on a single device: ordering between batches is structural
2371            // (inter-batch barrier + epoch-gated buffer reuse), not a host wait.
2372            if item.target_backend == BackendId::Vulkan && matches!(item.kind, WorkItemKind::Kernel)
2373            {
2374                multi_backend = true;
2375            }
2376            // Inter-batch Vulkan ordering is structural (see realize_inner): no host
2377            // wait before recording a new Vulkan op.
2378            // Step E A4b-3 + A4b-4: cross-device residency boundary. See
2379            // realize_inner for the full rationale.
2380            if matches!(
2381                item.kind,
2382                WorkItemKind::Copy { .. } | WorkItemKind::Move { .. }
2383            ) {
2384                // A4b-4: submit any open Vulkan chunk so the iGPU runs while the
2385                // host (possibly) waits on the CUDA producer.
2386                if multi_backend {
2387                    eager_submit_all_vulkan(&cache, &mut inflight_vulkan)?;
2388                }
2389                if let Some(&producer) = item.inputs.first() {
2390                    // A4b-4: wait in-flight Vulkan ONLY for a Vulkan-source D2H
2391                    // (reads completed data; download flushes only the OPEN batch).
2392                    // A CUDA/CPU source does NOT wait Vulkan (preserves overlap).
2393                    if multi_backend && copy_source_is_vulkan(&cache, producer)? {
2394                        drain_inflight_vulkan(&mut inflight_vulkan)?;
2395                    }
2396                    // Step E A4b-3: finer CUDA source-drain — wait ONLY the producer.
2397                    wait_producer_handle(&mut handles, producer)?;
2398                }
2399            }
2400            let handle = execute_work_item(
2401                &item,
2402                &mut cache,
2403                &mut devices,
2404                &mut layout_cache,
2405                &mut produced_syms,
2406                will_be_waited(&wait_set, item.node_id),
2407                // No persistent-output mode on the standard realize paths —
2408                // fresh alloc per node, byte-identical to pre-CapturedRun.
2409                None,
2410            )
2411            .map_err(|e| with_node_location(&graph, item.node_id, e))?;
2412            store_handle(&mut handles, item.node_id, handle);
2413            if let Some(d_idx) = item.destructive_input
2414                && let Some(&destroyed) = item.inputs.get(d_idx)
2415                && !target_set.contains(&destroyed)
2416            {
2417                // Step E A2.1 (in-flight DATA-BUFFER lifetime — UAF guard,
2418                // now DEFERRED-DELETION instead of a drain): retain the
2419                // evicted buffer until the reader fences signal — eager-
2420                // submit the open batch (no wait) + move a refcount clone of
2421                // the buffer into every in-flight batch, freeing it post-
2422                // fence on each batch's `Drop` with NO host block. Replaces
2423                // the pre-A2.1 `drain_inflight_vulkan` + open-batch
2424                // `force_flush` (two host-blocking fence waits). See
2425                // `defer_evicted_vulkan_buffer` / realize_inner for the
2426                // UAF/leak argument. CUDA eviction is A3 stream-safe.
2427                // Single-device (multi_backend == false) keeps the pre-A2.1
2428                // blocking force_flush of the OPEN batch (the else branch) —
2429                // byte-identical + UAF-safe; the deferred path is unsafe there
2430                // (see force_flush_vulkan's doc).
2431                if multi_backend {
2432                    defer_evicted_vulkan_buffer(&cache, destroyed, &mut inflight_vulkan)?;
2433                } else if let Some(d_arc) = cache.get(&destroyed) {
2434                    force_flush_vulkan(d_arc)?;
2435                }
2436                cache.remove(&destroyed);
2437                layout_cache.remove(&destroyed);
2438                // CUDA eviction is stream-ordered-safe (A3); drop the
2439                // handle so the realize-end empty-map assert stays valid.
2440                handles.remove(&destroyed);
2441            }
2442        }
2443
2444        compiler
2445            .join()
2446            .map_err(|_| Error::Msg("compiler thread panicked".to_string()).bt())?;
2447
2448        // Step E A4b-1: drain every outstanding async handle (CUDA events) before
2449        // results are read / the cache drops.
2450        drain_handles(&mut handles)?;
2451        // Step E A4b open question #4: blanket per-device stream sync for the
2452        // elided nodes `drain_handles` never tracked — see `realize_inner`'s
2453        // identical comment / `sync_active_cuda_devices`'s doc for the argument.
2454        sync_active_cuda_devices(&cache)?;
2455        // Step E A4b-4: wait every eagerly-submitted in-flight Vulkan batch before
2456        // the cache drops. Empty on a single-device realize.
2457        drain_inflight_vulkan(&mut inflight_vulkan)?;
2458        // Step E A4b-2: drain all deferred Vulkan work — submit the open batch
2459        // then wait it via a `VulkanCompletion` handle (the A2 submit+wait, split;
2460        // byte-identical for pure-Vulkan — one submission at realize-end).
2461        drain_vulkan_pending(&cache)?;
2462        debug_assert!(
2463            inflight_vulkan.is_empty(),
2464            "A4b-4: in-flight Vulkan batch list must be empty after realize-end drain",
2465        );
2466
2467        // Verify every target was realized + collect outputs in
2468        // target order. We don't `remove` from the cache because the
2469        // same NodeId can appear twice in `targets` (caller wants the
2470        // same storage twice) — clone the Arc instead.
2471        let mut out = Vec::with_capacity(targets.len());
2472        for &target in targets {
2473            let storage = cache.get(&target).cloned().ok_or_else(|| {
2474                Error::Msg(format!(
2475                    "PipelinedExecutor::realize_many: target {:?} not populated after execution",
2476                    target
2477                ))
2478                .bt()
2479            })?;
2480            let layout = layout_cache.get(&target).cloned().ok_or_else(|| {
2481                Error::Msg(format!(
2482                    "PipelinedExecutor::realize_many: target layout {:?} not populated after execution",
2483                    target
2484                ))
2485                .bt()
2486            })?;
2487            out.push((storage, layout));
2488        }
2489        Ok(out)
2490    }
2491}
2492
2493/// Resolve the executor's dispatch order from the configured
2494/// [`OrderSource`]. PR-A3b-1: `Optimized` lowers the in-place
2495/// "plan IS the graph" form via `extract_runs`/`lower_run`; `Default`
2496/// keeps the pre-A3b-1 `execution_plan` walk. Both produce the same
2497/// `NodeId` sequence on a branchless graph (A3a equivalence gate),
2498/// computed here AFTER safety-copy insertion so either path covers
2499/// any freshly inserted copies.
2500fn order_for(
2501    graph: &Graph,
2502    effective_roots: &[NodeId],
2503    order_source: &OrderSource<'_>,
2504) -> Vec<NodeId> {
2505    match order_source {
2506        OrderSource::Default => execution_plan(graph, effective_roots),
2507        // The streaming walk is driven in the compiler thread (it
2508        // interleaves arm resolution with compilation), so `order_for`
2509        // never flattens it on the production path. This arm exists only
2510        // for match totality / non-pipelined callers: it collects the SAME
2511        // lazily-resolved order eagerly (the streaming walk with the same
2512        // `resolve_branch` over the threaded selector), which equals the
2513        // one-shot `lower_picked_route(pick_route(..))` order.
2514        OrderSource::Streaming {
2515            optimized: _optimized,
2516            pick,
2517        } => {
2518            let bindings = global_bindings();
2519            fuel_graph::lower_picked_route_streaming(graph, effective_roots, |branch| {
2520                resolve_branch(graph, branch, &bindings, pick.selector.as_ref())
2521            })
2522        }
2523        OrderSource::Optimized { optimized, route } => {
2524            // Lower the runs over the *effective* roots (user targets +
2525            // any spliced/side-effect roots) so the order matches the
2526            // walk's reachable set rather than only the optimize-time
2527            // roots. On a branchless graph this is the same concatenated
2528            // `lower_run` sequence the OptimizedGraph reports.
2529            //
2530            // PR-C1: when the picker supplied a route, follow the chosen
2531            // arms (`lower_picked_route`); otherwise the arm-0 lowering
2532            // (`OptimizedGraph::dispatch_order`). An empty route is
2533            // byte-identical to arm-0, so the two paths agree whenever
2534            // the picker chose arm-0 everywhere (the no-pressure case).
2535            match route {
2536                Some(route) => fuel_graph::lower_picked_route(graph, effective_roots, route),
2537                None => {
2538                    // A transient view built solely to call `dispatch_order`;
2539                    // it does no planning, so it carries no placements. The
2540                    // real optimization's map lives on `optimized`.
2541                    let view = OptimizedGraph {
2542                        roots: effective_roots.to_vec(),
2543                        generation: optimized.generation,
2544                        placements: None,
2545                        eviction: None,
2546                    };
2547                    view.dispatch_order(graph)
2548                }
2549            }
2550        }
2551        // Resolved by `compiler_work_and_wait_set_for` before delegating
2552        // here (the whole point of `Cached` is to skip this computation
2553        // on a hit) — never reached. Kept exhaustive rather than wildcarded
2554        // so a future `OrderSource` variant can't silently fall through.
2555        OrderSource::Cached { .. } => {
2556            unreachable!("OrderSource::Cached is resolved before order_for is called")
2557        }
2558    }
2559}
2560
2561/// Step E A4b open question #4 — "event only where waited". The producer
2562/// [`NodeId`]s that some later `Op::Copy`/`Op::Move` node in `order` will
2563/// `wait_producer_handle` on (the executor's cross-device residency
2564/// boundary — see `wait_producer_handle`, whose `item.inputs.first()` read
2565/// this mirrors exactly). A CUDA node whose id is absent from the returned
2566/// set has NO mid-walk reader: same-device consumers are correct via stream
2567/// ordering alone (they never `wait`), and nothing touches its handle before
2568/// the realize-end drain, so [`crate::compiled::execute_compiled_with_wait_hint`]
2569/// can skip recording an `Event` for it entirely.
2570///
2571/// Requires a materialized `order` (works for [`OrderSource::Default`] /
2572/// [`OrderSource::Optimized`], whose [`CompilerWork::Order`] is a frozen
2573/// `Vec<NodeId>` computed up front) — see
2574/// [`compiler_work_and_wait_set_for`] for the [`OrderSource::Streaming`]
2575/// fallback.
2576fn build_wait_set(graph: &Graph, order: &[NodeId]) -> HashSet<NodeId> {
2577    let mut set = HashSet::new();
2578    for &id in order {
2579        let node = graph.node(id);
2580        if matches!(node.op, Op::Copy { .. } | Op::Move { .. })
2581            && let Some(&producer) = node.inputs.first()
2582        {
2583            set.insert(producer);
2584        }
2585    }
2586    set
2587}
2588
2589/// Step E A4b open question #4: the executor's per-realize wait-set.
2590/// `None` is the CONSERVATIVE fallback — every CUDA node still gets an Event
2591/// (today's pre-elision behavior, byte-identical). `Some(set)` restricts
2592/// event production to `set`'s members ([`build_wait_set`]'s output);
2593/// everything else gets `CompletionHandle::Ready` with no Event recorded.
2594type WaitSet = Option<HashSet<NodeId>>;
2595
2596/// Whether `node_id`'s completion handle must be individually observable
2597/// (i.e. `execute_compiled_with_wait_hint`'s `will_be_waited`). `None` (the
2598/// [`OrderSource::Streaming`] fallback — never elides) is always `true`.
2599#[inline]
2600fn will_be_waited(wait_set: &WaitSet, node_id: NodeId) -> bool {
2601    match wait_set {
2602        None => true,
2603        Some(set) => set.contains(&node_id),
2604    }
2605}
2606
2607/// Build the [`CompilerWork`] the compiler thread walks for the configured
2608/// [`OrderSource`], plus the [`WaitSet`] "event only where waited" (open
2609/// question #4) consults. The non-streaming sources flatten up front via
2610/// [`order_for`] (unchanged) and the SAME materialized order feeds
2611/// [`build_wait_set`], so the pre-scan and the dispatch order never
2612/// disagree. [`OrderSource::Streaming`] is handed to the compiler thread as
2613/// a [`CompilerWork::Streaming`] spec — NOT flattened here — so the thread
2614/// resolves branches lazily at the frontier (Step E Phase C, PR C1); the lazy
2615/// order can't be pre-scanned without eagerly resolving it (which would
2616/// defeat the point of streaming), so it falls back to the conservative
2617/// `WaitSet::None` — event every node, unchanged behavior. Holds the graph
2618/// read-lock only for the flattening branches; the streaming branch defers
2619/// the lock to the compiler thread.
2620fn compiler_work_and_wait_set_for(
2621    graph: &Graph,
2622    effective_roots: &[NodeId],
2623    order_source: &OrderSource<'_>,
2624) -> (CompilerWork, WaitSet) {
2625    match order_source {
2626        OrderSource::Streaming { pick, .. } => (
2627            CompilerWork::Streaming {
2628                roots: effective_roots.to_vec(),
2629                pick: (*pick).clone(),
2630            },
2631            None,
2632        ),
2633        OrderSource::Cached {
2634            optimized,
2635            order_cache,
2636        } => {
2637            let order = order_cache.get_or_init(|| {
2638                order_for(
2639                    graph,
2640                    effective_roots,
2641                    &OrderSource::Optimized {
2642                        optimized,
2643                        route: None,
2644                    },
2645                )
2646            });
2647            let wait_set = build_wait_set(graph, order);
2648            (CompilerWork::Order(order.clone()), Some(wait_set))
2649        }
2650        other => {
2651            let order = order_for(graph, effective_roots, other);
2652            let wait_set = build_wait_set(graph, &order);
2653            (CompilerWork::Order(order), Some(wait_set))
2654        }
2655    }
2656}
2657
2658/// The topology generation that keys the executor's `TopologyChanged`
2659/// chunk-boundary check. Uses the `OptimizedGraph`'s optimize-time
2660/// generation (PR-A3b-1 path). `None` ⇒ no check (the plain
2661/// `realize`/`realize_many` entries).
2662fn generation_for(order_source: &OrderSource<'_>) -> Option<u64> {
2663    match order_source {
2664        OrderSource::Optimized { optimized, .. } => Some(optimized.generation),
2665        OrderSource::Streaming { optimized, .. } => Some(optimized.generation),
2666        OrderSource::Cached { optimized, .. } => Some(optimized.generation),
2667        OrderSource::Default => None,
2668    }
2669}
2670
2671/// What the compiler thread walks: either a pre-flattened dispatch
2672/// `Order` (the `Default` / `Optimized` paths — unchanged), or a
2673/// `Streaming` spec the thread resolves branch-by-branch at the frontier
2674/// (Step E Phase C, PR C1).
2675enum CompilerWork {
2676    /// A frozen topological order (computed up front by `order_for`). The
2677    /// compiler thread compiles each node and sends it in turn.
2678    Order(Vec<NodeId>),
2679    /// The streaming run-walk: the compiler thread drives
2680    /// [`fuel_graph::walk_picked_route_streaming`] over `roots`, resolving
2681    /// each `Op::Branch` lazily via [`resolve_branch`] as the frontier
2682    /// reaches its arm-entry, and compiling + sending only the chosen
2683    /// arm's runs. `roots` are the effective roots (same set `order_for`
2684    /// lowers over). Byte-identical to `Order(lower_picked_route(
2685    /// pick_route(..)))` in C1 (same VRAM-only selector).
2686    Streaming {
2687        roots: Vec<NodeId>,
2688        pick: StreamingPick,
2689    },
2690}
2691
2692/// Compiler thread body. Holds the graph read-lock + a thread-local
2693/// layout cache and emits `WorkItem`s in topological order. For
2694/// [`CompilerWork::Order`] it walks the frozen order; for
2695/// [`CompilerWork::Streaming`] it resolves each branch at the frontier and
2696/// emits only the chosen arm's runs (Step E Phase C, PR C1). Sends
2697/// `Err(...)` and stops on the first failure.
2698fn compiler_thread_body(
2699    graph: Arc<RwLock<Graph>>,
2700    work: CompilerWork,
2701    sym_env: SymEnv,
2702    tx: Sender<Result<WorkItem>>,
2703) {
2704    let bindings = global_bindings();
2705
2706    let g = match graph.read() {
2707        Ok(g) => g,
2708        Err(_) => {
2709            let _ = tx.send(Err(poisoned("graph lock in compiler")));
2710            return;
2711        }
2712    };
2713
2714    // Compiler-thread-local layout cache. Populated as compile_one
2715    // walks topologically; downstream nodes look up their inputs'
2716    // layouts here (rather than from the graph side-table) to honor
2717    // the strided layouts emitted by metadata-only view ops earlier
2718    // in the same realize call.
2719    let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
2720    // `compile_one` for one node + send; returns `false` to stop the walk
2721    // (channel closed or compile error). Shared by both work modes so the
2722    // streamed and frozen-order paths compile identically.
2723    let compile_and_send = |id: NodeId, layout_cache: &mut HashMap<NodeId, Layout>| -> bool {
2724        let item = compile_one(&g, id, layout_cache, &bindings, &sym_env);
2725        let stop_on_err = item.is_err();
2726        if tx.send(item).is_err() {
2727            return false;
2728        }
2729        !stop_on_err
2730    };
2731
2732    match work {
2733        CompilerWork::Order(order) => {
2734            for id in order {
2735                if !compile_and_send(id, &mut layout_cache) {
2736                    return;
2737                }
2738            }
2739        }
2740        CompilerWork::Streaming { roots, pick } => {
2741            // Resolve each branch lazily at its arm-entry. C1 built the
2742            // streaming frontier; C2 made `pick.selector` load-aware (the
2743            // production `ChainedSelector` now reads each arm's live device
2744            // load — `pending_work_count / slot_capacity` via the
2745            // `BackendStreams` seam — as a key leg under the VRAM guard),
2746            // so this resolution reads live device load at THIS moment: the
2747            // executor has been submitting/draining (and updating the B1
2748            // counter) while the compiler ran ahead. Emit only the chosen
2749            // arm's runs, compiling + sending each node as the walk reaches
2750            // it — genuine streaming (resolution interleaved with
2751            // dispatch), not a pre-flattened order.
2752            let mut stopped = false;
2753            fuel_graph::walk_picked_route_streaming(
2754                &g,
2755                &roots,
2756                |branch| resolve_branch(&g, branch, &bindings, pick.selector.as_ref()),
2757                |members| {
2758                    if stopped {
2759                        return;
2760                    }
2761                    for &id in members {
2762                        if !compile_and_send(id, &mut layout_cache) {
2763                            stopped = true;
2764                            return;
2765                        }
2766                    }
2767                },
2768            );
2769        }
2770    }
2771}
2772
2773/// Resolve the [`CompiledNode`] for a kernel-bearing graph node via
2774/// the first-registered [`compile_node`] binding-table lookup.
2775///
2776/// `op_params` always comes from the executor's
2777/// `op_to_op_params(graph, node, id, layout_cache, sym_env)` — the live
2778/// OpParams shape (reduce dims, conv geometry, the per-pass
2779/// `SymEnv`-resolved `WriteSlice` offset, etc.) derives from the graph
2780/// node + its resolved input layouts at execute time.
2781fn resolve_compiled(
2782    op_kind: OpKind,
2783    dtypes: &[DType],
2784    target_backend: BackendId,
2785    op_params: OpParams,
2786    bindings: &KernelBindingTable,
2787) -> Result<CompiledNode> {
2788    compile_node(op_kind, dtypes, target_backend, op_params, bindings)
2789}
2790
2791/// Resolve one node into a `WorkItem` and update `layout_cache`
2792/// with the node's output layout. Three op shapes:
2793///
2794/// - `Op::Const` — adopts the entry from the input cache; layout is
2795///   read from the graph's side-table (or its contiguous fallback).
2796///
2797/// - Metadata-only view op — output layout is read from the graph's
2798///   side-table (populated by `Graph::push` at construction time);
2799///   the executor adopts the input's Storage Arc (no allocation, no
2800///   kernel).
2801///
2802/// - Computational op — output layout is `Layout::contiguous(node.shape)`
2803///   because today's kernels write contiguous output. The compiler
2804///   resolves the kernel ref and emits a Kernel work item.
2805fn compile_one(
2806    graph: &Graph,
2807    id: NodeId,
2808    layout_cache: &mut HashMap<NodeId, Layout>,
2809    bindings: &KernelBindingTable,
2810    sym_env: &SymEnv,
2811) -> Result<WorkItem> {
2812    let node = graph.node(id);
2813    let elem_count = node.shape.elem_count();
2814    let inputs = node.inputs.clone();
2815    // Snapshot destructive-input metadata from the graph at compile
2816    // time so the executor can evict the destroyed input from its
2817    // cache after the op runs (Op::Release / Op::Move semantics).
2818    let destructive_input = node.op.destructive_input();
2819
2820    if matches!(node.op, Op::Const) {
2821        let output_layout = graph.layout(id);
2822        layout_cache.insert(id, output_layout.clone());
2823        return Ok(WorkItem {
2824            node_id: id,
2825            inputs,
2826            elem_count,
2827            dtype: node.dtype,
2828            target_backend: BackendId::Cpu,
2829            kind: WorkItemKind::ConstAdopt,
2830            compiled: None,
2831            output_layout,
2832            destructive_input,
2833            output_bundle: None,
2834        });
2835    }
2836
2837    if node.op.is_view_op() {
2838        if inputs.len() != 1 {
2839            return Err(Error::Msg(format!(
2840                "view op {:?} expects 1 input, got {}",
2841                node.op,
2842                inputs.len(),
2843            ))
2844            .bt());
2845        }
2846        // Layout is read from the graph's side-table — populated by
2847        // `Graph::push` at construction time for view ops, and by
2848        // graph-rewriting opt passes that emit view nodes. The
2849        // compiler does not re-derive: graph.layout(id) is the single
2850        // source of truth.
2851        let output_layout = graph.layout(id);
2852        layout_cache.insert(id, output_layout.clone());
2853        // Inherit the upstream's target_backend (or default CPU) —
2854        // metadata-only adoption doesn't actually run on a backend,
2855        // but downstream consumers look at target_backend so it
2856        // needs to be set sensibly. Any device works.
2857        let target_backend = graph
2858            .target_backend(id)
2859            .or_else(|| graph.target_backend(inputs[0]))
2860            .unwrap_or(BackendId::Cpu);
2861        return Ok(WorkItem {
2862            node_id: id,
2863            inputs,
2864            elem_count,
2865            dtype: node.dtype,
2866            target_backend,
2867            kind: WorkItemKind::ViewOf {
2868                input: node.inputs[0],
2869            },
2870            compiled: None,
2871            output_layout,
2872            destructive_input,
2873            output_bundle: None,
2874        });
2875    }
2876
2877    // Op::View — multi-output projection (Option C, Session 4).
2878    // Structurally identical to a metadata-only view op at realize
2879    // time: clone the producer's Storage Arc into the View's cache
2880    // slot. The graph's layout side-table, populated by
2881    // `Tensor::view`, already carries the slot's effective layout
2882    // (slot.byte_offset baked into start_offset in slot-dtype-element
2883    // units).
2884    if let Op::View { .. } = node.op {
2885        if inputs.len() != 1 {
2886            return Err(Error::Msg(format!(
2887                "Op::View expects 1 input (the producer), got {}",
2888                inputs.len(),
2889            ))
2890            .bt());
2891        }
2892        let output_layout = graph.layout(id);
2893        layout_cache.insert(id, output_layout.clone());
2894        let target_backend = graph
2895            .target_backend(id)
2896            .or_else(|| graph.target_backend(inputs[0]))
2897            .unwrap_or(BackendId::Cpu);
2898        return Ok(WorkItem {
2899            node_id: id,
2900            inputs: inputs.clone(),
2901            elem_count,
2902            dtype: node.dtype,
2903            target_backend,
2904            kind: WorkItemKind::SlotView {
2905                producer: inputs[0],
2906            },
2907            compiled: None,
2908            output_layout,
2909            destructive_input,
2910            output_bundle: None,
2911        });
2912    }
2913
2914    // Op::ViewOwned — copies the slot's bytes into a fresh
2915    // contiguous Storage at realize time. Output layout is
2916    // contiguous starting at offset 0 (the memcpy produced an
2917    // independent buffer).
2918    if let Op::ViewOwned { slot } = node.op {
2919        if inputs.len() != 1 {
2920            return Err(Error::Msg(format!(
2921                "Op::ViewOwned expects 1 input (the producer), got {}",
2922                inputs.len(),
2923            ))
2924            .bt());
2925        }
2926        let output_layout = Layout::contiguous(node.shape.clone());
2927        layout_cache.insert(id, output_layout.clone());
2928        let target_backend = graph
2929            .target_backend(id)
2930            .or_else(|| graph.target_backend(inputs[0]))
2931            .unwrap_or(BackendId::Cpu);
2932        return Ok(WorkItem {
2933            node_id: id,
2934            inputs: inputs.clone(),
2935            elem_count,
2936            dtype: node.dtype,
2937            target_backend,
2938            kind: WorkItemKind::SlotOwn {
2939                producer: inputs[0],
2940                slot,
2941            },
2942            compiled: None,
2943            output_layout,
2944            destructive_input,
2945            output_bundle: None,
2946        });
2947    }
2948
2949    if matches!(node.op, Op::Release) {
2950        // Op::Release produces a zero-element marker output. The
2951        // marker storage is CPU + 0 bytes — nothing reads it; it
2952        // exists so cache lookups on the Release NodeId resolve.
2953        // The actual deallocation of `inputs[0]` happens in the
2954        // realize loop via `destructive_input` cleanup.
2955        if inputs.len() != 1 {
2956            return Err(
2957                Error::Msg(format!("Op::Release expects 1 input, got {}", inputs.len(),)).bt(),
2958            );
2959        }
2960        let output_layout = Layout::contiguous(node.shape.clone());
2961        layout_cache.insert(id, output_layout.clone());
2962        // Inherit the source's target_backend so any downstream
2963        // backend-aware logic (telemetry, scheduling) sees a sensible
2964        // value. The marker doesn't actually run on any backend.
2965        let target_backend = graph
2966            .target_backend(id)
2967            .or_else(|| graph.target_backend(inputs[0]))
2968            .unwrap_or(BackendId::Cpu);
2969        return Ok(WorkItem {
2970            node_id: id,
2971            inputs,
2972            elem_count,
2973            dtype: node.dtype,
2974            target_backend,
2975            kind: WorkItemKind::ReleaseMarker,
2976            compiled: None,
2977            output_layout,
2978            destructive_input,
2979            output_bundle: None,
2980        });
2981    }
2982
2983    // In-place ops (Phase 3 of in-place ops infrastructure): kernel
2984    // lookup goes through the standard binding-table path, but the
2985    // executor adopts the target's Arc as the output instead of
2986    // allocating fresh bytes. The compile-time predicate is exactly
2987    // `op.destructive_input().is_some()` AND NOT one of the
2988    // structural ops (WriteSlice / ZeroFill / Release / Move) which
2989    // have their own dedicated WorkItemKind arms in this function.
2990    if !matches!(
2991        node.op,
2992        Op::WriteSlice { .. }
2993            | Op::WriteSliceRotating { .. }
2994            | Op::WriteSliceDoff { .. }
2995            | Op::ZeroFill
2996            | Op::Release
2997            | Op::Move { .. },
2998    ) && let Some(target_idx) = node.op.destructive_input()
2999    {
3000        if inputs.len() <= target_idx {
3001            return Err(Error::Msg(format!(
3002                "in-place op {:?} declares destructive_input={target_idx} \
3003                     but has only {} input(s)",
3004                node.op,
3005                inputs.len(),
3006            ))
3007            .bt());
3008        }
3009        let target_backend = graph.target_backend(id).ok_or_else(|| {
3010            Error::Msg(format!(
3011                "PipelinedExecutor: in-place op node {id:?} has no target_backend set",
3012            ))
3013            .bt()
3014        })?;
3015        let op_kind = op_to_op_kind(&node.op).ok_or_else(|| {
3016            Error::Msg(format!(
3017                "PipelinedExecutor: in-place op {:?} has no op_to_op_kind mapping",
3018                node.op,
3019            ))
3020            .bt()
3021        })?;
3022        let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3023        let dtypes = build_lookup_dtypes(graph, node);
3024        let compiled = resolve_compiled(op_kind, &dtypes, target_backend, op_params, bindings)?;
3025        // Output adopts target's Layout (same Storage Arc, same shape).
3026        let output_layout = graph.layout(inputs[target_idx]);
3027        layout_cache.insert(id, output_layout.clone());
3028        return Ok(WorkItem {
3029            node_id: id,
3030            inputs: inputs.clone(),
3031            elem_count,
3032            dtype: node.dtype,
3033            target_backend,
3034            kind: WorkItemKind::InplaceKernel { target_idx },
3035            compiled: Some(compiled),
3036            output_layout,
3037            destructive_input,
3038            output_bundle: None,
3039        });
3040    }
3041
3042    if matches!(node.op, Op::WriteSlice { .. }) {
3043        // WriteSlice: kernel lookup happens like a normal kernel, but
3044        // the work item carries a dedicated kind so the executor
3045        // knows to adopt the destination's Arc as the output rather
3046        // than allocating a fresh buffer. The destination's NodeId is
3047        // captured here so the executor doesn't have to re-derive it.
3048        if inputs.len() != 2 {
3049            return Err(Error::Msg(format!(
3050                "Op::WriteSlice expects 2 inputs (destination, source), got {}",
3051                inputs.len(),
3052            ))
3053            .bt());
3054        }
3055        let target_backend = graph.target_backend(id).ok_or_else(|| {
3056            Error::Msg(format!(
3057                "PipelinedExecutor: WriteSlice node {:?} has no target_backend set",
3058                id
3059            ))
3060            .bt()
3061        })?;
3062        let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3063        let dtypes = build_lookup_dtypes(graph, node);
3064        let compiled = resolve_compiled(
3065            OpKind::WriteSlice,
3066            &dtypes,
3067            target_backend,
3068            op_params,
3069            bindings,
3070        )?;
3071        // Output adopts the destination's Layout — same Storage Arc,
3072        // same shape. Downstream consumers that want a post-write
3073        // sub-extent compose an explicit Op::Slice (WriteSlice does
3074        // not encode partial extents).
3075        let output_layout = graph.layout(inputs[0]);
3076        layout_cache.insert(id, output_layout.clone());
3077        return Ok(WorkItem {
3078            node_id: id,
3079            inputs: inputs.clone(),
3080            elem_count,
3081            dtype: node.dtype,
3082            target_backend,
3083            kind: WorkItemKind::WriteSlice {
3084                dest: inputs[0],
3085                source: inputs[1],
3086            },
3087            compiled: Some(compiled),
3088            output_layout,
3089            destructive_input,
3090            output_bundle: None,
3091        });
3092    }
3093
3094    if matches!(node.op, Op::WriteSliceRotating { .. }) {
3095        // WriteSliceRotating: same shape as WriteSlice but with a
3096        // third input (position scalar). Dispatch through the
3097        // binding table at `OpKind::WriteSliceRotating`; the
3098        // executor's arm reads the position from `position`'s
3099        // storage and the kernel splits across the ring boundary.
3100        if inputs.len() != 3 {
3101            return Err(Error::Msg(format!(
3102                "Op::WriteSliceRotating expects 3 inputs (destination, source, position), got {}",
3103                inputs.len(),
3104            ))
3105            .bt());
3106        }
3107        let target_backend = graph.target_backend(id).ok_or_else(|| {
3108            Error::Msg(format!(
3109                "PipelinedExecutor: WriteSliceRotating node {:?} has no target_backend set",
3110                id
3111            ))
3112            .bt()
3113        })?;
3114        let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3115        let dtypes = build_lookup_dtypes(graph, node);
3116        let compiled = resolve_compiled(
3117            OpKind::WriteSliceRotating,
3118            &dtypes,
3119            target_backend,
3120            op_params,
3121            bindings,
3122        )?;
3123        let output_layout = graph.layout(inputs[0]);
3124        layout_cache.insert(id, output_layout.clone());
3125        return Ok(WorkItem {
3126            node_id: id,
3127            inputs: inputs.clone(),
3128            elem_count,
3129            dtype: node.dtype,
3130            target_backend,
3131            kind: WorkItemKind::WriteSliceRotating {
3132                dest: inputs[0],
3133                source: inputs[1],
3134                position: inputs[2],
3135            },
3136            compiled: Some(compiled),
3137            output_layout,
3138            destructive_input,
3139            output_bundle: None,
3140        });
3141    }
3142
3143    if matches!(node.op, Op::WriteSliceDoff { .. }) {
3144        // WriteSliceDoff: same shape as WriteSlice but with a third
3145        // input (device-resident I64 offset). Dispatch through the
3146        // binding table at `OpKind::WriteSliceDoff`; the executor's arm
3147        // threads the offset's device pointer straight to the kernel
3148        // (no D2H, capture-safe).
3149        if inputs.len() != 3 {
3150            return Err(Error::Msg(format!(
3151                "Op::WriteSliceDoff expects 3 inputs (destination, source, offset), got {}",
3152                inputs.len(),
3153            ))
3154            .bt());
3155        }
3156        let target_backend = graph.target_backend(id).ok_or_else(|| {
3157            Error::Msg(format!(
3158                "PipelinedExecutor: WriteSliceDoff node {:?} has no target_backend set",
3159                id
3160            ))
3161            .bt()
3162        })?;
3163        let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3164        let dtypes = build_lookup_dtypes(graph, node);
3165        let compiled = resolve_compiled(
3166            OpKind::WriteSliceDoff,
3167            &dtypes,
3168            target_backend,
3169            op_params,
3170            bindings,
3171        )?;
3172        let output_layout = graph.layout(inputs[0]);
3173        layout_cache.insert(id, output_layout.clone());
3174        return Ok(WorkItem {
3175            node_id: id,
3176            inputs: inputs.clone(),
3177            elem_count,
3178            dtype: node.dtype,
3179            target_backend,
3180            kind: WorkItemKind::WriteSliceDoff {
3181                dest: inputs[0],
3182                source: inputs[1],
3183                offset: inputs[2],
3184            },
3185            compiled: Some(compiled),
3186            output_layout,
3187            destructive_input,
3188            output_bundle: None,
3189        });
3190    }
3191
3192    if let Op::Alloc { target } = node.op {
3193        // Op::Alloc { target }: produce a fresh zero-init Storage on
3194        // `target` with node.shape * node.dtype. Zero inputs.
3195        // Direct executor dispatch via WorkItemKind::Alloc — no
3196        // binding-table lookup (the device handle threading isn't
3197        // expressible through the binding table's current key shape).
3198        if !inputs.is_empty() {
3199            return Err(
3200                Error::Msg(format!("Op::Alloc expects 0 inputs, got {}", inputs.len(),)).bt(),
3201            );
3202        }
3203        let output_layout = Layout::contiguous(node.shape.clone());
3204        layout_cache.insert(id, output_layout.clone());
3205        // target_backend is informational here (the executor's Alloc
3206        // arm consults target_location for allocation routing); set
3207        // it to target's backend for consistency with how downstream
3208        // nodes inherit/read it.
3209        let target_backend = target.backend();
3210        return Ok(WorkItem {
3211            node_id: id,
3212            inputs,
3213            elem_count,
3214            dtype: node.dtype,
3215            target_backend,
3216            kind: WorkItemKind::Alloc {
3217                target_location: target,
3218            },
3219            compiled: None,
3220            output_layout,
3221            destructive_input,
3222            output_bundle: None,
3223        });
3224    }
3225
3226    if let Op::Iota { len } = node.op {
3227        // Op::Iota { len }: 0-input F32 position generator
3228        // [0.0, 1.0, …, (len-1)]. Direct executor dispatch via
3229        // WorkItemKind::Iota — no binding-table lookup (a leaf has no
3230        // inputs[0] to inherit a backend from). Modeled on Op::Alloc.
3231        if !inputs.is_empty() {
3232            return Err(
3233                Error::Msg(format!("Op::Iota expects 0 inputs, got {}", inputs.len(),)).bt(),
3234            );
3235        }
3236        let output_layout = Layout::contiguous(node.shape.clone());
3237        layout_cache.insert(id, output_layout.clone());
3238        // Leaf: the planner may not place a 0-input node, so fall back to
3239        // CPU. Iota is a tiny host-side generator; its only consumer today
3240        // is the CPU flash-attn decomposition's alibi bias.
3241        let target_backend = graph.target_backend(id).unwrap_or(BackendId::Cpu);
3242        return Ok(WorkItem {
3243            node_id: id,
3244            inputs,
3245            elem_count,
3246            dtype: node.dtype,
3247            target_backend,
3248            kind: WorkItemKind::Iota {
3249                len,
3250                target_location: graph.placement(id),
3251            },
3252            compiled: None,
3253            output_layout,
3254            destructive_input,
3255            output_bundle: None,
3256        });
3257    }
3258
3259    if matches!(node.op, Op::ZeroFill) {
3260        // Op::ZeroFill: 1 input (the buffer to zero); output aliases
3261        // input's Storage Arc (destructive in-place). No binding-
3262        // table lookup — per-backend dispatch in execute_work_item.
3263        if inputs.len() != 1 {
3264            return Err(Error::Msg(format!(
3265                "Op::ZeroFill expects 1 input, got {}",
3266                inputs.len(),
3267            ))
3268            .bt());
3269        }
3270        // Output layout: contiguous in the node's shape. We don't
3271        // require the input to be contiguous (auto_contiguize in the
3272        // executor handles strided inputs), but the destructive
3273        // semantic means callers should only ZeroFill an Op::Alloc
3274        // output today.
3275        let output_layout = Layout::contiguous(node.shape.clone());
3276        layout_cache.insert(id, output_layout.clone());
3277        let target_backend = graph
3278            .target_backend(id)
3279            .or_else(|| graph.target_backend(inputs[0]))
3280            .unwrap_or(BackendId::Cpu);
3281        return Ok(WorkItem {
3282            node_id: id,
3283            inputs,
3284            elem_count,
3285            dtype: node.dtype,
3286            target_backend,
3287            kind: WorkItemKind::ZeroFill,
3288            compiled: None,
3289            output_layout,
3290            destructive_input,
3291            output_bundle: None,
3292        });
3293    }
3294
3295    if let Op::Copy { target } = node.op {
3296        // Op::Copy { target }: download bytes from the source residency
3297        // to a fresh Storage allocated on `target`. Kernel lookup uses
3298        // `target_backend` = source backend (set by `prepare()` on the
3299        // realize device the source is on); the wrapper does the actual
3300        // transfer (e.g. Vulkan::download_bytes → memcpy into a CPU
3301        // CpuStorageBytes). The output Storage's variant is determined
3302        // by `target_location` and allocated in `execute_work_item`'s
3303        // WorkItemKind::Copy arm.
3304        if inputs.len() != 1 {
3305            return Err(
3306                Error::Msg(format!("Op::Copy expects 1 input, got {}", inputs.len(),)).bt(),
3307            );
3308        }
3309        let target_backend = graph.target_backend(id).ok_or_else(|| {
3310            Error::Msg(format!(
3311                "PipelinedExecutor: Op::Copy node {:?} has no target_backend \
3312                 set (= source backend, the one whose kernel runs the \
3313                 download)",
3314                id
3315            ))
3316            .bt()
3317        })?;
3318        let op_params = OpParams::None;
3319        let dtypes = build_lookup_dtypes(graph, node);
3320        let compiled =
3321            resolve_compiled(OpKind::Copy, &dtypes, target_backend, op_params, bindings)?;
3322        // Output layout: contiguous in the node's shape (mirrors the
3323        // source's logical shape). Auto-contiguize on the input side
3324        // (in execute_work_item) handles strided source views by
3325        // materializing them into a contiguous source buffer before
3326        // the kernel runs.
3327        let output_layout = Layout::contiguous(node.shape.clone());
3328        layout_cache.insert(id, output_layout.clone());
3329        return Ok(WorkItem {
3330            node_id: id,
3331            inputs,
3332            elem_count,
3333            dtype: node.dtype,
3334            target_backend,
3335            kind: WorkItemKind::Copy {
3336                target_location: target,
3337            },
3338            compiled: Some(compiled),
3339            output_layout,
3340            destructive_input,
3341            output_bundle: None,
3342        });
3343    }
3344
3345    if let Op::Move { target } = node.op {
3346        // Op::Move { target }: identical data-movement half to
3347        // Op::Copy — kernel lookup at (OpKind::Copy, [dt, dt],
3348        // source_backend); output allocated on `target` by the
3349        // executor's Copy/Move arm. The destructive half (release
3350        // the source) rides the realize loop's `destructive_input`
3351        // cleanup via the snapshot taken at the top of this function
3352        // (`Op::Move::destructive_input() == Some(0)`). Ordering
3353        // safety (a Move must not strand a sibling consumer of its
3354        // source) is `execution_plan`/`derive_ordering`'s job — the
3355        // Move is pinned after every non-destructive reader of the
3356        // source's alias set before any work item is emitted.
3357        if inputs.len() != 1 {
3358            return Err(
3359                Error::Msg(format!("Op::Move expects 1 input, got {}", inputs.len(),)).bt(),
3360            );
3361        }
3362        let target_backend = graph.target_backend(id).ok_or_else(|| {
3363            Error::Msg(format!(
3364                "PipelinedExecutor: Op::Move node {:?} has no target_backend \
3365                 set (= source backend, the one whose kernel runs the \
3366                 transfer)",
3367                id
3368            ))
3369            .bt()
3370        })?;
3371        let op_params = OpParams::None;
3372        let dtypes = build_lookup_dtypes(graph, node);
3373        let compiled =
3374            resolve_compiled(OpKind::Copy, &dtypes, target_backend, op_params, bindings)?;
3375        // Output layout: contiguous in the node's shape, same as
3376        // Op::Copy (the transfer materializes strided sources via
3377        // auto-contiguize on the input side).
3378        let output_layout = Layout::contiguous(node.shape.clone());
3379        layout_cache.insert(id, output_layout.clone());
3380        return Ok(WorkItem {
3381            node_id: id,
3382            inputs,
3383            elem_count,
3384            dtype: node.dtype,
3385            target_backend,
3386            kind: WorkItemKind::Move {
3387                target_location: target,
3388            },
3389            compiled: Some(compiled),
3390            output_layout,
3391            destructive_input,
3392            output_bundle: None,
3393        });
3394    }
3395
3396    if matches!(node.op, Op::Reshape(_)) {
3397        if inputs.len() != 1 {
3398            return Err(
3399                Error::Msg(format!("Op::Reshape expects 1 input, got {}", inputs.len(),)).bt(),
3400            );
3401        }
3402        let input_layout = graph.layout(inputs[0]);
3403        // Output is contiguous in the new shape — bytes per element
3404        // are unchanged, so a contiguous input flows through with
3405        // zero copy. A non-contiguous input is auto-contiguized at
3406        // execute time and the result is naturally contiguous.
3407        let output_layout = Layout::contiguous(node.shape.clone());
3408        layout_cache.insert(id, output_layout.clone());
3409        let target_backend = graph
3410            .target_backend(id)
3411            .or_else(|| graph.target_backend(inputs[0]))
3412            .unwrap_or(BackendId::Cpu);
3413        // Sanity: same total element count.
3414        let in_elem_count = input_layout.shape().elem_count();
3415        if in_elem_count != elem_count {
3416            return Err(Error::Msg(format!(
3417                "Op::Reshape changes element count: input {} → output {}",
3418                in_elem_count, elem_count,
3419            ))
3420            .bt());
3421        }
3422        return Ok(WorkItem {
3423            node_id: id,
3424            inputs,
3425            elem_count,
3426            dtype: node.dtype,
3427            target_backend,
3428            kind: WorkItemKind::ContiguizeOf {
3429                input: node.inputs[0],
3430            },
3431            compiled: None,
3432            output_layout,
3433            destructive_input,
3434            output_bundle: None,
3435        });
3436    }
3437
3438    if matches!(node.op, Op::Contiguize) {
3439        // Op::Contiguize: same execute-time path as Reshape, but
3440        // output shape == input shape so there's no element-count
3441        // check. Zero-copy when input is already contiguous +
3442        // zero-offset (the ContiguizeOf arm in execute_work_item
3443        // adopts the input Arc); otherwise auto_contiguize allocates
3444        // a fresh contiguous Storage on the input's backend.
3445        if inputs.len() != 1 {
3446            return Err(Error::Msg(format!(
3447                "Op::Contiguize expects 1 input, got {}",
3448                inputs.len(),
3449            ))
3450            .bt());
3451        }
3452        let output_layout = Layout::contiguous(node.shape.clone());
3453        layout_cache.insert(id, output_layout.clone());
3454        let target_backend = graph
3455            .target_backend(id)
3456            .or_else(|| graph.target_backend(inputs[0]))
3457            .unwrap_or(BackendId::Cpu);
3458        return Ok(WorkItem {
3459            node_id: id,
3460            inputs,
3461            elem_count,
3462            dtype: node.dtype,
3463            target_backend,
3464            kind: WorkItemKind::ContiguizeOf {
3465                input: node.inputs[0],
3466            },
3467            compiled: None,
3468            output_layout,
3469            destructive_input,
3470            output_bundle: None,
3471        });
3472    }
3473
3474    // Runtime fused op — a JIT-adopted (Tier-2) kernel. `Op::Fused(fid, _)`
3475    // with `fid.is_runtime()` has no `OpKind` (the op was synthesized after
3476    // startup): its kernel resolves from the SAME binding table as every
3477    // static kernel, under `BindingKey::RuntimeFused(fid)` — the dtype tuple
3478    // is the key, so an absent kernel AND a dtype mismatch are one honest
3479    // `NoBackendForOp` miss. A deterministic *lookup*, not a decision: the
3480    // optimizer's gate emitted the arm only when this kernel was bound, and
3481    // pinned `target_backend` (`runtime-fused-op-registration.md` §6). The
3482    // guards are invariant checks, never live fallbacks.
3483    if let Op::Fused(fid, _) = &node.op
3484        && fid.is_runtime()
3485    {
3486        let target_backend = graph.target_backend(id).ok_or_else(|| {
3487            Error::Msg(format!(
3488                "PipelinedExecutor: runtime fused op {:?} (node {:?}) has no \
3489                     target_backend — the arm emitter pins it at emission",
3490                fid, id,
3491            ))
3492            .bt()
3493        })?;
3494        // v1: single-output only. Reject a multi-output bundle explicitly
3495        // rather than silently dropping it.
3496        if graph.output_views_arc(id).is_some() {
3497            return Err(Error::Msg(format!(
3498                "PipelinedExecutor: runtime fused op {:?} (node {:?}) carries a \
3499                     multi-output bundle — synthesized kernels are single-output in v1",
3500                fid, id,
3501            ))
3502            .bt());
3503        }
3504        let dtypes = build_lookup_dtypes(graph, node);
3505        let (kernel, caps) = bindings.lookup_with_caps(
3506            crate::kernel::BindingKey::RuntimeFused(*fid),
3507            &dtypes,
3508            target_backend,
3509        )?;
3510        let output_layout = Layout::contiguous(node.shape.clone());
3511        layout_cache.insert(id, output_layout.clone());
3512        // Deliberate, not a fallthrough to `op_to_op_params` (which doesn't
3513        // know runtime ops): the node's `Runtime { scalars }` — the live
3514        // `extract:` values, pattern pre-order — becomes `JitScalars` (the
3515        // launch appends them as the kernel's trailing `p{i}` args); a
3516        // param-free op carries `None` (its launch is layout-driven:
3517        // pointers + element count).
3518        let op_params = match &node.op {
3519            Op::Fused(_, FusedOpParams::Runtime { scalars }) if !scalars.is_empty() => {
3520                OpParams::JitScalars {
3521                    scalars: scalars.clone(),
3522                }
3523            }
3524            _ => OpParams::None,
3525        };
3526        let compiled = CompiledNode {
3527            op: OpKind::RuntimeFused,
3528            dtypes: KernelDTypes::from_slice(&dtypes),
3529            backend: target_backend,
3530            kernel,
3531            caps,
3532            op_params,
3533        };
3534        return Ok(WorkItem {
3535            node_id: id,
3536            inputs,
3537            elem_count,
3538            dtype: node.dtype,
3539            target_backend,
3540            kind: WorkItemKind::Kernel,
3541            compiled: Some(compiled),
3542            output_layout,
3543            destructive_input,
3544            output_bundle: None,
3545        });
3546    }
3547
3548    let target_backend = graph.target_backend(id).ok_or_else(|| {
3549        Error::Msg(format!(
3550            "PipelinedExecutor: node {:?} ({:?}) has no target_backend set",
3551            id, node.op
3552        ))
3553        .bt()
3554    })?;
3555
3556    let op_kind = op_to_op_kind(&node.op).ok_or_else(|| {
3557        Error::Msg(format!(
3558            "PipelinedExecutor: op {:?} not yet mapped to an OpKind \
3559             (Phase C migrates more ops as they're registered)",
3560            node.op,
3561        ))
3562        .bt()
3563    })?;
3564
3565    let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3566    // Build the per-operand dtype list for the binding-table lookup —
3567    // inputs in order, then outputs. Variadic uniform-dtype ops
3568    // (Concat) collapse to the canonical `[T_in, T_out]` shorthand to
3569    // match how registrations index them.
3570    let dtypes = build_lookup_dtypes(graph, node);
3571    let compiled = resolve_compiled(op_kind, &dtypes, target_backend, op_params, bindings)?;
3572    let output_layout = Layout::contiguous(node.shape.clone());
3573    layout_cache.insert(id, output_layout.clone());
3574    // Multi-output: snapshot the producer's bundle metadata. When
3575    // `Some(_)`, the Kernel arm allocates a single Storage sized to
3576    // fit every slot and attaches the bundle via
3577    // `Storage::with_bundle` so downstream Op::View/Op::ViewOwned
3578    // resolve correctly.
3579    let output_bundle = graph.output_views_arc(id);
3580    Ok(WorkItem {
3581        node_id: id,
3582        inputs,
3583        elem_count,
3584        dtype: node.dtype,
3585        target_backend,
3586        kind: WorkItemKind::Kernel,
3587        compiled: Some(compiled),
3588        output_layout,
3589        destructive_input,
3590        output_bundle,
3591    })
3592}
3593
3594/// Build the per-operand dtype list used as the binding-table lookup
3595/// key. Inputs in order, then the output. Variadic-uniform ops
3596/// (Concat) collapse to the canonical `[T_in, T_out]` shorthand to
3597/// match how those wrappers are registered (otherwise an N-way concat
3598/// would need N+1 distinct registrations per dtype).
3599///
3600/// `pub(crate)` — `crate::plan::compile_plan` (step 9b) reuses this
3601/// to key the route picker's binding-table lookup the same way the
3602/// pipelined path does.
3603pub(crate) fn build_lookup_dtypes(graph: &Graph, node: &Node) -> Vec<DType> {
3604    if matches!(node.op, Op::Concat { .. }) {
3605        // Concat: all inputs share node.dtype by construction.
3606        let in_dt = node
3607            .inputs
3608            .first()
3609            .map(|&id| graph.node(id).dtype)
3610            .unwrap_or(node.dtype);
3611        return vec![in_dt, node.dtype];
3612    }
3613    if matches!(node.op, Op::WriteSlice { .. }) {
3614        // WriteSlice: the destination (inputs[0]) is exposed to the
3615        // executor as the OUTPUT slot (in-place adoption), not as an
3616        // input the kernel reads. Canonicalize the binding-table key
3617        // to `[T_source, T_out]` so registrations match the kernel's
3618        // actual surface (one input slab + one output buffer).
3619        let src_dt = node
3620            .inputs
3621            .get(1)
3622            .map(|&id| graph.node(id).dtype)
3623            .unwrap_or(node.dtype);
3624        return vec![src_dt, node.dtype];
3625    }
3626    if matches!(node.op, Op::WriteSliceRotating { .. }) {
3627        // Same canonicalization as WriteSlice: dest = output slot;
3628        // position (inputs[2]) is read by the kernel via the
3629        // position-input parameter, not the binding-table key.
3630        let src_dt = node
3631            .inputs
3632            .get(1)
3633            .map(|&id| graph.node(id).dtype)
3634            .unwrap_or(node.dtype);
3635        return vec![src_dt, node.dtype];
3636    }
3637    if matches!(node.op, Op::WriteSliceDoff { .. }) {
3638        // Same canonicalization as WriteSlice: dest = output slot;
3639        // offset (inputs[2], I64) is a non-key runtime operand read by
3640        // the kernel via its device pointer, not the binding-table key.
3641        let src_dt = node
3642            .inputs
3643            .get(1)
3644            .map(|&id| graph.node(id).dtype)
3645            .unwrap_or(node.dtype);
3646        return vec![src_dt, node.dtype];
3647    }
3648    let mut dts: Vec<DType> = node.inputs.iter().map(|&id| graph.node(id).dtype).collect();
3649    dts.push(node.dtype);
3650    dts
3651}
3652
3653/// SoftmaxLastDim is reachable only through `Op::Fused(FusedOps::
3654/// SOFTMAX_LAST_DIM, _)` post-step-5 (the legacy `Op::SoftmaxLastDim`
3655/// primitive variant was retired). This helper collapses the
3656/// op-to-OpKind/OpParams shapes for callers that want a single-arm
3657/// match.
3658fn op_is_softmax_last_dim(op: &Op) -> bool {
3659    matches!(op, Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM)
3660}
3661
3662/// FusedLinear is reachable only through `Op::Fused(FusedOps::
3663/// FUSED_LINEAR, _)` post-step-5.
3664fn op_is_fused_linear(op: &Op) -> bool {
3665    matches!(op, Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::FUSED_LINEAR)
3666}
3667
3668/// Does the executor have an arm that runs `op` on `backend`? Only for ops it dispatches DIRECTLY
3669/// (no binding-table kernel, so the planner cannot reject them for lack of a binding). `None` means
3670/// the op is not direct-dispatched and this answer does not apply (the binding table decides).
3671///
3672/// Source of truth for [`check_direct_arms_wired`]; keep in step with the `execute_work_item` arms.
3673pub(crate) fn direct_arm_wired(op: &Op, backend: BackendId) -> Option<bool> {
3674    match op {
3675        // CPU generates it; CUDA generates on the host and uploads (GAP-380 a2). The cuda arm is
3676        // compiled only with the `cuda` feature, and a CUDA stamp cannot arise without it.
3677        Op::Iota { .. } => Some(
3678            backend == BackendId::Cpu || (cfg!(feature = "cuda") && backend == BackendId::Cuda),
3679        ),
3680        _ => None,
3681    }
3682}
3683
3684/// Plan-time guard (PM, 2026-11-12): a node stamped for a backend whose executor has no arm for its
3685/// op fails HERE, with the node and op named, instead of as an `Err` inside the executor mid-run.
3686/// Run after the backend stamp. A graph with every arm wired is a no-op.
3687pub(crate) fn check_direct_arms_wired(graph: &Graph, roots: &[NodeId]) -> Result<()> {
3688    for id in fuel_graph::topo_order_multi(graph, roots) {
3689        let node = graph.node(id);
3690        let backend = graph.target_backend(id).unwrap_or(BackendId::Cpu);
3691        if direct_arm_wired(&node.op, backend) == Some(false) {
3692            return Err(Error::Msg(format!(
3693                "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)",
3694                id.0,
3695                node.op,
3696                node.shape,
3697                node.dtype,
3698            ))
3699            .bt());
3700        }
3701    }
3702    Ok(())
3703}
3704
3705/// Map a `fuel_graph::Op` to a `fuel_ir::dispatch::OpKind`.
3706/// Returns `None` for ops that haven't been wired into the new
3707/// dispatch path yet — Phase C extends this as op families migrate.
3708///
3709/// `pub(crate)` — `crate::plan::compile_plan` (step 9b) reuses this
3710/// to skip nodes the binding-table doesn't index (view ops,
3711/// `Op::Const`, not-yet-migrated ops) when building bindings.
3712pub(crate) fn op_to_op_kind(op: &Op) -> Option<OpKind> {
3713    match op {
3714        Op::Add => Some(OpKind::AddElementwise),
3715        Op::Sub => Some(OpKind::SubElementwise),
3716        Op::Mul => Some(OpKind::MulElementwise),
3717        Op::Div => Some(OpKind::DivElementwise),
3718        Op::Relu => Some(OpKind::ReluElementwise),
3719        Op::Neg => Some(OpKind::NegElementwise),
3720        Op::Sqr => Some(OpKind::SqrElementwise),
3721        Op::Sqrt => Some(OpKind::SqrtElementwise),
3722        Op::Tanh => Some(OpKind::TanhElementwise),
3723        Op::Exp => Some(OpKind::ExpElementwise),
3724        Op::Log => Some(OpKind::LogElementwise),
3725        Op::Sin => Some(OpKind::SinElementwise),
3726        Op::Cos => Some(OpKind::CosElementwise),
3727        Op::Sigmoid => Some(OpKind::SigmoidElementwise),
3728        Op::Silu => Some(OpKind::SiluElementwise),
3729        Op::GeluTanh => Some(OpKind::GeluTanhElementwise),
3730        Op::Step => Some(OpKind::StepElementwise),
3731        Op::Recip => Some(OpKind::RecipElementwise),
3732        Op::Abs => Some(OpKind::AbsElementwise),
3733        Op::Equal => Some(OpKind::EqualElementwise),
3734        Op::Ne => Some(OpKind::NotEqualElementwise),
3735        Op::Lt => Some(OpKind::LessElementwise),
3736        Op::Le => Some(OpKind::LessEqualElementwise),
3737        Op::Gt => Some(OpKind::GreaterElementwise),
3738        Op::Ge => Some(OpKind::GreaterEqualElementwise),
3739        Op::Where => Some(OpKind::Where),
3740        Op::Floor => Some(OpKind::FloorElementwise),
3741        Op::Ceil => Some(OpKind::CeilElementwise),
3742        Op::Round => Some(OpKind::RoundElementwise),
3743        Op::Sign => Some(OpKind::SignElementwise),
3744        Op::Erf => Some(OpKind::ErfElementwise),
3745        Op::Gelu => Some(OpKind::GeluElementwise),
3746        Op::Pow => Some(OpKind::PowElementwise),
3747        Op::Rsqrt => Some(OpKind::RsqrtElementwise),
3748        Op::Rem => Some(OpKind::RemElementwise),
3749        Op::Flip { .. } => Some(OpKind::Flip),
3750        Op::Roll { .. } => Some(OpKind::Roll),
3751        Op::CumSum { .. } => Some(OpKind::CumSum),
3752        Op::Triu { .. } => Some(OpKind::Triu),
3753        Op::Tril { .. } => Some(OpKind::Tril),
3754        Op::LogSoftmaxLastDim => Some(OpKind::LogSoftmaxLastDim),
3755        Op::LogSoftmaxLastDimBackward => Some(OpKind::LogSoftmaxLastDimBackward),
3756        Op::MaskedFill { .. } => Some(OpKind::MaskedFill),
3757        Op::Pad { .. } => Some(OpKind::Pad),
3758        Op::PadBackward { .. } => Some(OpKind::PadBackward),
3759        Op::SumDim(_) => Some(OpKind::SumReduce),
3760        Op::MaxDim(_) => Some(OpKind::MaxReduce),
3761        Op::MinDim(_) => Some(OpKind::MinReduce),
3762        Op::MeanDim(_) => Some(OpKind::MeanReduce),
3763        Op::SumAll => Some(OpKind::SumReduce),
3764        Op::MaxAll => Some(OpKind::MaxReduce),
3765        Op::MinAll => Some(OpKind::MinReduce),
3766        Op::MeanAll => Some(OpKind::MeanReduce),
3767        Op::MatMul => Some(OpKind::MatMul),
3768        Op::Cast(_) => Some(OpKind::Cast),
3769        // Phase 7.6 step 5: fused-op dispatch routes through
3770        // `Op::Fused(fid, _)`; the legacy `Op::Conv2D` /
3771        // `Op::FusedLinear` / `Op::SoftmaxLastDim` /
3772        // `Op::RmsNormLastDim` / `Op::LayerNormLastDim` / `Op::Rope`
3773        // arms were dropped together with the variants.
3774        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::CONV2D => Some(OpKind::Conv2D),
3775        // Phase 7.6 step 5 (final): legacy `Op::ConvTranspose2D` /
3776        // `Op::FlashAttn` / `Op::PagedAttn` arms dropped with the
3777        // variants; dispatch flows only through `Op::Fused`.
3778        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D => {
3779            Some(OpKind::ConvTranspose2D)
3780        }
3781        Op::ReduceSumTo(_) => Some(OpKind::ReduceSumTo),
3782        Op::ReduceMaxTo(_) => Some(OpKind::ReduceMaxTo),
3783        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::FLASH_ATTN => {
3784            Some(OpKind::FlashAttn)
3785        }
3786        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::PAGED_ATTN => {
3787            Some(OpKind::PagedAttn)
3788        }
3789        Op::AddScalar(_) => Some(OpKind::Affine),
3790        Op::MulScalar(_) => Some(OpKind::Affine),
3791        Op::Clamp { .. } => Some(OpKind::ClampElementwise),
3792        Op::PowI(_) => Some(OpKind::PowIElementwise),
3793        Op::Maximum => Some(OpKind::MaximumElementwise),
3794        Op::Minimum => Some(OpKind::MinimumElementwise),
3795        Op::Concat { .. } => Some(OpKind::Concat),
3796        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM => {
3797            Some(OpKind::SoftmaxLastDim)
3798        }
3799        // Phase 7.6 step 6 follow-up: backward helpers now route
3800        // through the byte-level binding table too.
3801        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM_BACKWARD => {
3802            Some(OpKind::SoftmaxLastDimBackward)
3803        }
3804        Op::Fused(fid, _)
3805            if *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM_BACKWARD =>
3806        {
3807            Some(OpKind::LayerNormLastDimBackward)
3808        }
3809        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM_BACKWARD => {
3810            Some(OpKind::RmsNormLastDimBackward)
3811        }
3812        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::REDUCE_MAX_TO_BACKWARD => {
3813            Some(OpKind::ReduceMaxToBackward)
3814        }
3815        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::POWI_BACKWARD => {
3816            Some(OpKind::PowIElementwiseBackward)
3817        }
3818        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::FUSED_LINEAR => {
3819            Some(OpKind::FusedLinear)
3820        }
3821        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM => {
3822            Some(OpKind::RmsNormLastDim)
3823        }
3824        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM => {
3825            Some(OpKind::LayerNormLastDim)
3826        }
3827        Op::IndexSelect { .. } => Some(OpKind::IndexSelect),
3828        Op::Gather { .. } => Some(OpKind::Gather),
3829        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::ROPE => Some(OpKind::Rope),
3830        Op::IndexAdd { .. } => Some(OpKind::IndexAdd),
3831        Op::ScatterAdd { .. } => Some(OpKind::ScatterAdd),
3832        Op::NonZeroIndices { .. } => Some(OpKind::NonZeroIndices),
3833        Op::ArgMaxDim(_) => Some(OpKind::ArgMaxDim),
3834        Op::ArgMinDim(_) => Some(OpKind::ArgMinDim),
3835        // Phase 7.6 step 5 (final): legacy `Op::QMatMul` arm dropped.
3836        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::QMATMUL => {
3837            Some(OpKind::QMatMul)
3838        }
3839        Op::WriteSlice { .. } => Some(OpKind::WriteSlice),
3840        Op::WriteSliceRotating { .. } => Some(OpKind::WriteSliceRotating),
3841        Op::WriteSliceDoff { .. } => Some(OpKind::WriteSliceDoff),
3842        // Phase 2 of bridge-retirement (post-9c): Op::Copy dispatches
3843        // through the binding table at OpKind::Copy. The BackendId
3844        // axis encodes the source backend (the kernel runs there —
3845        // download from local memory). The executor handles output
3846        // allocation on the target via a dedicated WorkItemKind::Copy
3847        // arm, since target_location differs from target_backend for
3848        // this op (the only one with that property today).
3849        Op::Copy { .. } => Some(OpKind::Copy),
3850        // Op::Move dispatches the same data-movement kernel as
3851        // Op::Copy — the destructive release of the source is
3852        // realize-loop bookkeeping (`destructive_input` cleanup), not
3853        // a kernel. Same OpKind, same source-backend key convention.
3854        // `compile_plan` skips both (residency-determined, not a
3855        // picker decision).
3856        Op::Move { .. } => Some(OpKind::Copy),
3857        // Phase 3 of the in-place ops infrastructure: each in-place Op
3858        // variant maps to its OpKind so the binding-table dispatch can
3859        // resolve a kernel. The executor's dedicated WorkItemKind
3860        // arms (added alongside) handle the storage-Arc adoption.
3861        Op::ReluInplace => Some(OpKind::ReluInplace),
3862        Op::SiluInplace => Some(OpKind::SiluInplace),
3863        Op::GeluTanhInplace => Some(OpKind::GeluTanhInplace),
3864        Op::TanhInplace => Some(OpKind::TanhInplace),
3865        Op::SigmoidInplace => Some(OpKind::SigmoidInplace),
3866        Op::NegInplace => Some(OpKind::NegInplace),
3867        Op::AbsInplace => Some(OpKind::AbsInplace),
3868        Op::SqrInplace => Some(OpKind::SqrInplace),
3869        Op::SqrtInplace => Some(OpKind::SqrtInplace),
3870        Op::RsqrtInplace => Some(OpKind::RsqrtInplace),
3871        Op::RecipInplace => Some(OpKind::RecipInplace),
3872        Op::ExpInplace => Some(OpKind::ExpInplace),
3873        Op::LogInplace => Some(OpKind::LogInplace),
3874        Op::SinInplace => Some(OpKind::SinInplace),
3875        Op::CosInplace => Some(OpKind::CosInplace),
3876        Op::SignInplace => Some(OpKind::SignInplace),
3877        Op::FloorInplace => Some(OpKind::FloorInplace),
3878        Op::CeilInplace => Some(OpKind::CeilInplace),
3879        Op::RoundInplace => Some(OpKind::RoundInplace),
3880        Op::ErfInplace => Some(OpKind::ErfInplace),
3881        Op::GeluInplace => Some(OpKind::GeluInplace),
3882        Op::ClampInplace { .. } => Some(OpKind::ClampInplace),
3883        Op::PowIInplace(_) => Some(OpKind::PowIInplace),
3884        // In-place binary variants (Add/Sub/Mul/Div/MaskedFill) and
3885        // their OpKind siblings are tracked by a parallel session and
3886        // toggle in and out of the Op enum as that work progresses.
3887        // No multi-output arm references them; nothing to map here in
3888        // the current HEAD.
3889        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::INPLACE_AFFINE => {
3890            Some(OpKind::InplaceAffine)
3891        }
3892        Op::Fused(fid, _)
3893            if *fid == fuel_graph::registry::FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY =>
3894        {
3895            Some(OpKind::FusedSoftmaxCrossEntropy)
3896        }
3897        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::CAUSAL_CONV1D => {
3898            Some(OpKind::CausalConv1d)
3899        }
3900        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SELECTIVE_SCAN => {
3901            Some(OpKind::SelectiveScan)
3902        }
3903        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SSD_CHUNK_SCAN => {
3904            Some(OpKind::SsdChunkScan)
3905        }
3906        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::NF4_MATMUL => {
3907            Some(OpKind::Nf4Matmul)
3908        }
3909        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::AWQ_MATMUL => {
3910            Some(OpKind::AwqMatmul)
3911        }
3912        // Phase 3a (post-9c): Op::Alloc + Op::ZeroFill are structural
3913        // ops dispatched directly via `WorkItemKind::Alloc` /
3914        // `WorkItemKind::ZeroFill` (no binding-table lookup).
3915        // `compile_plan` skips these.
3916        Op::Alloc { .. } | Op::ZeroFill => None,
3917        _ => None,
3918    }
3919}
3920
3921/// Build the [`OpParams`] for `node`'s op. Most ops use
3922/// `OpParams::None`; reductions / matmul / conv / slice carry their
3923/// op-specific extras here. The graph is consulted to read input
3924/// shapes (e.g. reductions need the input shape to walk the
3925/// multi-index — Storage only carries bytes + dtype).
3926///
3927/// Phase C — extends as op families migrate. Returns Err if a
3928/// graph-shape lookup fails (currently can't, but the signature is
3929/// `Result` so future cases needing validation slot in cleanly).
3930/// Encode an `f64` value into the byte pattern of `dtype`. Used by
3931/// `Op::Pad` (Constant mode) to pre-convert the fill value once at
3932/// op_params time, so the kernel itself stays dtype-agnostic.
3933fn encode_value_to_bytes(dtype: DType, value: f64) -> Result<Vec<u8>> {
3934    match dtype {
3935        DType::F32 => Ok((value as f32).to_le_bytes().to_vec()),
3936        DType::F64 => Ok(value.to_le_bytes().to_vec()),
3937        DType::BF16 => Ok(half::bf16::from_f32(value as f32).to_le_bytes().to_vec()),
3938        DType::F16 => Ok(half::f16::from_f32(value as f32).to_le_bytes().to_vec()),
3939        DType::U8 => Ok(vec![value as u8]),
3940        DType::U32 => Ok((value as u32).to_le_bytes().to_vec()),
3941        other => Err(Error::Msg(format!(
3942            "encode_value_to_bytes: dtype {other:?} not yet supported for Pad fill",
3943        ))
3944        .bt()),
3945    }
3946}
3947
3948/// Encode a typed `Scalar` to its little-endian byte representation.
3949/// Used by Op::MaskedFill so the kernel only sees bytes — never has
3950/// to know the value's dtype.
3951fn scalar_to_bytes(s: fuel_ir::Scalar) -> Vec<u8> {
3952    use fuel_ir::Scalar;
3953    match s {
3954        Scalar::U8(v) => vec![v],
3955        Scalar::I8(v) => vec![v as u8],
3956        Scalar::U32(v) => v.to_le_bytes().to_vec(),
3957        Scalar::I16(v) => v.to_le_bytes().to_vec(),
3958        Scalar::I32(v) => v.to_le_bytes().to_vec(),
3959        Scalar::I64(v) => v.to_le_bytes().to_vec(),
3960        Scalar::BF16(v) => v.to_le_bytes().to_vec(),
3961        Scalar::F16(v) => v.to_le_bytes().to_vec(),
3962        Scalar::F32(v) => v.to_le_bytes().to_vec(),
3963        Scalar::F64(v) => v.to_le_bytes().to_vec(),
3964        Scalar::Bool(b) => vec![b as u8],
3965        Scalar::F8E4M3(v) => vec![v.to_bits()],
3966        Scalar::F8E5M2(v) => vec![v.to_bits()],
3967        // OCP-MX E8M0 block scale is a raw byte on the wire (`2^(X-127)`,
3968        // decoded kernel-side); a single byte is its own LE encoding.
3969        Scalar::F8E8M0(v) => vec![v],
3970    }
3971}
3972
3973fn op_to_op_params(
3974    graph: &Graph,
3975    node: &Node,
3976    node_id: NodeId,
3977    layout_cache: &HashMap<NodeId, Layout>,
3978    sym_env: &SymEnv,
3979) -> Result<OpParams> {
3980    // Helper: read an input's layout from the compiler-thread-local
3981    // cache (which is current within the realize call), falling back
3982    // to the graph's side-table if the input wasn't visited (which
3983    // shouldn't happen in topo order, but the fallback keeps the
3984    // path safe).
3985    let input_layout = |input_id: NodeId| -> Layout {
3986        layout_cache
3987            .get(&input_id)
3988            .cloned()
3989            .unwrap_or_else(|| graph.layout(input_id))
3990    };
3991    Ok(match &node.op {
3992        // Phase 7.6 step 5 (final): legacy `Op::QMatMul` arm dropped.
3993        Op::Fused(_, fuel_graph::registry::FusedOpParams::QMatMul { quant_type, k, n }) => {
3994            // Inputs: (activations f32 [..., m, k], weight_bytes
3995            // u32-typed). Output shape (this Node's shape) is
3996            // [..., m, n]. Flatten leading dims into batch_count.
3997            if node.inputs.len() != 2 {
3998                return Err(Error::Msg(format!(
3999                    "Op::QMatMul expects 2 inputs (activations, weight_bytes), got {}",
4000                    node.inputs.len(),
4001                ))
4002                .bt());
4003            }
4004            let act_layout = input_layout(node.inputs[0]);
4005            let act_dims = act_layout.shape().dims();
4006            if act_dims.len() < 2 {
4007                return Err(Error::Msg(format!(
4008                    "Op::QMatMul: activations must be rank ≥ 2, got {act_dims:?}",
4009                ))
4010                .bt());
4011            }
4012            let m = act_dims[act_dims.len() - 2];
4013            let k_act = act_dims[act_dims.len() - 1];
4014            if k_act != *k {
4015                return Err(Error::Msg(format!(
4016                    "Op::QMatMul: activation last dim ({k_act}) must equal Op's k ({k})",
4017                ))
4018                .bt());
4019            }
4020            let batch_count: usize = act_dims[..act_dims.len() - 2].iter().product();
4021            OpParams::QMatMul {
4022                quant_type: *quant_type,
4023                batch_count,
4024                m,
4025                n: *n,
4026                k: *k,
4027            }
4028        }
4029        Op::ArgMaxDim(d) | Op::ArgMinDim(d) => {
4030            // Reuse OpParams::Reduce — same shape contract; the
4031            // single reduce dim is the argmax/argmin axis. Input
4032            // layout flows through KernelRef's `layouts[0]`.
4033            OpParams::Reduce {
4034                dims: vec![*d],
4035                keepdim: false,
4036            }
4037        }
4038        Op::SumDim(d) | Op::MaxDim(d) | Op::MinDim(d) | Op::MeanDim(d) => OpParams::Reduce {
4039            dims: vec![*d],
4040            keepdim: false,
4041        },
4042        Op::SumAll | Op::MaxAll | Op::MinAll | Op::MeanAll => {
4043            let il = input_layout(node.inputs[0]);
4044            let rank = il.shape().rank();
4045            OpParams::Reduce {
4046                dims: (0..rank).collect(),
4047                keepdim: false,
4048            }
4049        }
4050        Op::MatMul => {
4051            // Batched matmul: lhs `[..lhs_batch.., m, k]` @
4052            // rhs `[..rhs_batch.., k, n]` → out `[..lhs_batch.., m, n]`.
4053            // Per-axis the batch dims either match or follow GQA-style
4054            // divisibility (lhs_dim > rhs_dim && lhs_dim % rhs_dim == 0);
4055            // the kernel honors the latter via `rhs_idx = lhs_idx / n_rep`.
4056            if node.inputs.len() != 2 {
4057                return Err(Error::Msg(format!(
4058                    "Op::MatMul expects 2 inputs, got {}",
4059                    node.inputs.len(),
4060                ))
4061                .bt());
4062            }
4063            let lhs = input_layout(node.inputs[0]);
4064            let rhs = input_layout(node.inputs[1]);
4065            let lhs_dims = lhs.shape().dims();
4066            let rhs_dims = rhs.shape().dims();
4067            if lhs_dims.len() < 2 || rhs_dims.len() < 2 {
4068                return Err(Error::Msg(format!(
4069                    "Op::MatMul requires both inputs rank ≥ 2; got lhs={:?} rhs={:?}",
4070                    lhs_dims, rhs_dims,
4071                ))
4072                .bt());
4073            }
4074            if lhs_dims.len() != rhs_dims.len() {
4075                return Err(Error::Msg(format!(
4076                    "Op::MatMul: ranks must match (auto-broadcast happens at \
4077                     graph construction time); got lhs rank {} vs rhs rank {}",
4078                    lhs_dims.len(),
4079                    rhs_dims.len(),
4080                ))
4081                .bt());
4082            }
4083            let rank = lhs_dims.len();
4084            let batch_rank = rank - 2;
4085            // Per-axis validation: equal or GQA-divisible.
4086            for i in 0..batch_rank {
4087                let la = lhs_dims[i];
4088                let ra = rhs_dims[i];
4089                let ok = la == ra || (ra > 0 && la > ra && la % ra == 0);
4090                if !ok {
4091                    return Err(Error::Msg(format!(
4092                        "Op::MatMul: batch dim {i} disallowed combination \
4093                         (lhs={la}, rhs={ra}); must be equal or \
4094                         GQA-divisible (lhs > rhs && lhs % rhs == 0)",
4095                    ))
4096                    .bt());
4097                }
4098            }
4099            let lhs_batch_dims: Vec<usize> = lhs_dims[..batch_rank].to_vec();
4100            let rhs_batch_dims: Vec<usize> = rhs_dims[..batch_rank].to_vec();
4101            let (m, k_lhs) = (lhs_dims[rank - 2], lhs_dims[rank - 1]);
4102            let (k_rhs, n) = (rhs_dims[rank - 2], rhs_dims[rank - 1]);
4103            if k_lhs != k_rhs {
4104                return Err(Error::Msg(format!(
4105                    "Op::MatMul: contracting dims disagree — lhs trailing is \
4106                     [{m}, {k_lhs}], rhs trailing is [{k_rhs}, {n}]",
4107                ))
4108                .bt());
4109            }
4110            // Data-determined-M (sparse-MoE): a side-table row count makes
4111            // `m` the capacity and this the compute count. Dual-path,
4112            // mirroring WriteSlice: resolve in the compile-time SymEnv
4113            // (static / input-determined) now; else DEFER a producer-bound
4114            // sym to execute; else it is a genuine caller error.
4115            let m_compute = match graph.matmul_row_count(node_id) {
4116                None => MatmulM::All,
4117                Some(dyn_m) => match dyn_m.resolve(sym_env) {
4118                    Some(c) => {
4119                        if c > m {
4120                            return Err(Error::Msg(format!(
4121                                "Op::MatMul: resolved row count {c} exceeds capacity {m}",
4122                            ))
4123                            .bt());
4124                        }
4125                        MatmulM::Rows(c)
4126                    }
4127                    None => match dyn_m {
4128                        fuel_ir::DynScalar::Sym(s) if graph.binds_data_determined_sym(s) => {
4129                            MatmulM::Deferred(dyn_m)
4130                        }
4131                        _ => {
4132                            return Err(Error::Msg(format!(
4133                                "Op::MatMul: dynamic row count {dyn_m:?} is unbound in the \
4134                                 SymEnv at compile and no producer binds it (not \
4135                                 data-determined)",
4136                            ))
4137                            .bt());
4138                        }
4139                    },
4140                },
4141            };
4142            OpParams::Matmul {
4143                lhs_batch_dims,
4144                rhs_batch_dims,
4145                m,
4146                n,
4147                k: k_lhs,
4148                m_compute,
4149            }
4150        }
4151        // Phase 7.6 step 4: legacy `Op::FusedLinear` and registry-extended
4152        // `Op::Fused(FUSED_LINEAR, _)` share the same shape contract and
4153        // params encoding (reuses OpParams::Matmul). One body covers both.
4154        op if op_is_fused_linear(op) => {
4155            // Inputs: [a, b, bias]. Same shape semantics as MatMul on
4156            // a/b; bias is rank-1 [N] and broadcasts along all leading
4157            // dims. We reuse OpParams::Matmul (kernel reads bias from
4158            // inputs[2] directly).
4159            if node.inputs.len() != 3 {
4160                return Err(Error::Msg(format!(
4161                    "Op::FusedLinear expects 3 inputs (a, b, bias), got {}",
4162                    node.inputs.len(),
4163                ))
4164                .bt());
4165            }
4166            let lhs = input_layout(node.inputs[0]);
4167            let rhs = input_layout(node.inputs[1]);
4168            let bias = input_layout(node.inputs[2]);
4169            let lhs_dims = lhs.shape().dims();
4170            let rhs_dims = rhs.shape().dims();
4171            let bias_dims = bias.shape().dims();
4172            if lhs_dims.len() < 2 || rhs_dims.len() < 2 {
4173                return Err(Error::Msg(format!(
4174                    "Op::FusedLinear requires both a, b rank ≥ 2; got a={:?} b={:?}",
4175                    lhs_dims, rhs_dims,
4176                ))
4177                .bt());
4178            }
4179            if lhs_dims.len() != rhs_dims.len() {
4180                return Err(Error::Msg(format!(
4181                    "Op::FusedLinear: ranks must match (auto-broadcast happens at \
4182                     graph construction time); got a rank {} vs b rank {}",
4183                    lhs_dims.len(),
4184                    rhs_dims.len(),
4185                ))
4186                .bt());
4187            }
4188            let rank = lhs_dims.len();
4189            let batch_rank = rank - 2;
4190            for i in 0..batch_rank {
4191                let la = lhs_dims[i];
4192                let ra = rhs_dims[i];
4193                let ok = la == ra || (ra > 0 && la > ra && la % ra == 0);
4194                if !ok {
4195                    return Err(Error::Msg(format!(
4196                        "Op::FusedLinear: batch dim {i} disallowed (a={la}, b={ra})",
4197                    ))
4198                    .bt());
4199                }
4200            }
4201            let lhs_batch_dims: Vec<usize> = lhs_dims[..batch_rank].to_vec();
4202            let rhs_batch_dims: Vec<usize> = rhs_dims[..batch_rank].to_vec();
4203            let (m, k_lhs) = (lhs_dims[rank - 2], lhs_dims[rank - 1]);
4204            let (k_rhs, n) = (rhs_dims[rank - 2], rhs_dims[rank - 1]);
4205            if k_lhs != k_rhs {
4206                return Err(Error::Msg(format!(
4207                    "Op::FusedLinear: contracting dims disagree — a trailing is \
4208                     [{m}, {k_lhs}], b trailing is [{k_rhs}, {n}]",
4209                ))
4210                .bt());
4211            }
4212            if bias_dims.len() != 1 || bias_dims[0] != n {
4213                return Err(Error::Msg(format!(
4214                    "Op::FusedLinear: bias must be rank-1 [{n}], got {bias_dims:?}",
4215                ))
4216                .bt());
4217            }
4218            OpParams::Matmul {
4219                lhs_batch_dims,
4220                rhs_batch_dims,
4221                m,
4222                n,
4223                k: k_lhs,
4224                // FusedLinear is always static-M (dense linear layer).
4225                m_compute: MatmulM::All,
4226            }
4227        }
4228        // FusedSoftmaxCrossEntropy: flatten logits `[..., V]` to
4229        // `[n_rows, V]` for the kernel. n_rows is the product of all
4230        // leading dims (≥1 even for rank-1 logits, where targets are
4231        // a scalar). The kernel walks rows internally.
4232        Op::Fused(
4233            _,
4234            fuel_graph::registry::FusedOpParams::FusedSoftmaxCrossEntropy {
4235                reduction,
4236                ignore_index,
4237            },
4238        ) => {
4239            if node.inputs.len() != 2 {
4240                return Err(Error::Msg(format!(
4241                    "FusedSoftmaxCrossEntropy expects 2 inputs (logits, targets), got {}",
4242                    node.inputs.len(),
4243                ))
4244                .bt());
4245            }
4246            let logits_layout = input_layout(node.inputs[0]);
4247            let logits_dims = logits_layout.shape().dims();
4248            if logits_dims.is_empty() {
4249                return Err(Error::Msg(
4250                    "FusedSoftmaxCrossEntropy: logits must have rank ≥ 1".to_string(),
4251                )
4252                .bt());
4253            }
4254            let vocab = *logits_dims.last().unwrap();
4255            let n_rows: usize = logits_dims[..logits_dims.len() - 1]
4256                .iter()
4257                .product::<usize>()
4258                .max(1);
4259            let targets_layout = input_layout(node.inputs[1]);
4260            let target_count: usize = targets_layout
4261                .shape()
4262                .dims()
4263                .iter()
4264                .product::<usize>()
4265                .max(1);
4266            if target_count != n_rows {
4267                return Err(Error::Msg(format!(
4268                    "FusedSoftmaxCrossEntropy: targets element count {target_count} must \
4269                     equal logits row count {n_rows} (logits {logits_dims:?}, targets {:?})",
4270                    targets_layout.shape().dims(),
4271                ))
4272                .bt());
4273            }
4274            OpParams::FusedSoftmaxCrossEntropy {
4275                n_rows,
4276                vocab,
4277                reduction: *reduction,
4278                ignore_index: *ignore_index,
4279            }
4280        }
4281        // CausalConv1d: derive (batch, channels, seq_in, seq_out, kernel)
4282        // from the input layouts. x is `[batch, channels, seq_in]`
4283        // (caller pre-pads with kernel-1 zeros), weight is
4284        // `[channels, 1, kernel]`. seq_out = seq_in - (kernel - 1).
4285        Op::Fused(_, fuel_graph::registry::FusedOpParams::CausalConv1d { use_silu }) => {
4286            if node.inputs.len() != 3 {
4287                return Err(Error::Msg(format!(
4288                    "CausalConv1d expects 3 inputs (x, weight, bias), got {}",
4289                    node.inputs.len(),
4290                ))
4291                .bt());
4292            }
4293            let x_layout = input_layout(node.inputs[0]);
4294            let w_layout = input_layout(node.inputs[1]);
4295            let x_dims = x_layout.shape().dims();
4296            let w_dims = w_layout.shape().dims();
4297            if x_dims.len() != 3 {
4298                return Err(Error::Msg(format!(
4299                    "CausalConv1d: x must be rank 3 [batch, channels, seq+pad], got {x_dims:?}",
4300                ))
4301                .bt());
4302            }
4303            if w_dims.len() != 3 {
4304                return Err(Error::Msg(format!(
4305                    "CausalConv1d: weight must be rank 3 [channels, 1, kernel], got {w_dims:?}",
4306                ))
4307                .bt());
4308            }
4309            let batch = x_dims[0];
4310            let channels = x_dims[1];
4311            let seq_in = x_dims[2];
4312            let kernel = w_dims[2];
4313            if seq_in < kernel - 1 {
4314                return Err(Error::Msg(format!(
4315                    "CausalConv1d: x time dim {seq_in} must be ≥ kernel-1 = {} \
4316                     (caller must pre-pad with kernel-1 zeros)",
4317                    kernel - 1,
4318                ))
4319                .bt());
4320            }
4321            let seq_out = seq_in - (kernel - 1);
4322            OpParams::CausalConv1d {
4323                batch,
4324                channels,
4325                seq_in,
4326                seq_out,
4327                kernel,
4328                use_silu: *use_silu,
4329            }
4330        }
4331        // SelectiveScan: derive (batch, seqlen, dim, dstate) from the
4332        // input layouts. u: [batch, seqlen, dim]; a: [dim, dstate].
4333        Op::Fused(_, fuel_graph::registry::FusedOpParams::SelectiveScan { delta_softplus }) => {
4334            if node.inputs.len() != 5 {
4335                return Err(Error::Msg(format!(
4336                    "SelectiveScan expects 5 inputs (u, delta, a, b, c), got {}",
4337                    node.inputs.len(),
4338                ))
4339                .bt());
4340            }
4341            let u_layout = input_layout(node.inputs[0]);
4342            let a_layout = input_layout(node.inputs[2]);
4343            let u_dims = u_layout.shape().dims();
4344            let a_dims = a_layout.shape().dims();
4345            if u_dims.len() != 3 {
4346                return Err(Error::Msg(format!(
4347                    "SelectiveScan: u must be rank 3 [batch, seqlen, dim], got {u_dims:?}",
4348                ))
4349                .bt());
4350            }
4351            if a_dims.len() != 2 {
4352                return Err(Error::Msg(format!(
4353                    "SelectiveScan: a must be rank 2 [dim, dstate], got {a_dims:?}",
4354                ))
4355                .bt());
4356            }
4357            let batch = u_dims[0];
4358            let seqlen = u_dims[1];
4359            let dim = u_dims[2];
4360            let dstate = a_dims[1];
4361            if a_dims[0] != dim {
4362                return Err(Error::Msg(format!(
4363                    "SelectiveScan: a's first dim {} must equal dim {dim}",
4364                    a_dims[0],
4365                ))
4366                .bt());
4367            }
4368            OpParams::SelectiveScan {
4369                batch,
4370                seqlen,
4371                dim,
4372                dstate,
4373                delta_softplus: *delta_softplus,
4374            }
4375        }
4376        // SsdChunkScan: derive (batch, seqlen, heads, head_dim,
4377        // state_dim) from x and b layouts. x: [batch, seqlen, heads,
4378        // head_dim]; b: [batch, seqlen, heads, state_dim].
4379        Op::Fused(_, fuel_graph::registry::FusedOpParams::SsdChunkScan { chunk_size }) => {
4380            if node.inputs.len() != 5 {
4381                return Err(Error::Msg(format!(
4382                    "SsdChunkScan expects 5 inputs (x, dt, a, b, c), got {}",
4383                    node.inputs.len(),
4384                ))
4385                .bt());
4386            }
4387            let x_layout = input_layout(node.inputs[0]);
4388            let b_layout = input_layout(node.inputs[3]);
4389            let x_dims = x_layout.shape().dims();
4390            let b_dims = b_layout.shape().dims();
4391            if x_dims.len() != 4 {
4392                return Err(Error::Msg(format!(
4393                    "SsdChunkScan: x must be rank 4 [batch, seqlen, heads, head_dim], got {x_dims:?}",
4394                ))
4395                .bt());
4396            }
4397            if b_dims.len() != 4 {
4398                return Err(Error::Msg(format!(
4399                    "SsdChunkScan: b must be rank 4 [batch, seqlen, heads, state_dim], got {b_dims:?}",
4400                ))
4401                .bt());
4402            }
4403            let batch = x_dims[0];
4404            let seqlen = x_dims[1];
4405            let heads = x_dims[2];
4406            let head_dim = x_dims[3];
4407            let state_dim = b_dims[3];
4408            OpParams::SsdChunkScan {
4409                batch,
4410                seqlen,
4411                heads,
4412                head_dim,
4413                state_dim,
4414                chunk_size: *chunk_size,
4415            }
4416        }
4417        // Nf4Matmul: derive (batch, m, n, k) from activations + w_packed
4418        // layouts. activations: [..., m, k] (leading dims flatten into
4419        // batch); w_packed: [n, k/2] U8.
4420        Op::Fused(_, fuel_graph::registry::FusedOpParams::Nf4Matmul { block_size }) => {
4421            if node.inputs.len() != 3 {
4422                return Err(Error::Msg(format!(
4423                    "Nf4Matmul expects 3 inputs (activations, w_packed, absmax), got {}",
4424                    node.inputs.len(),
4425                ))
4426                .bt());
4427            }
4428            let a_layout = input_layout(node.inputs[0]);
4429            let w_layout = input_layout(node.inputs[1]);
4430            let a_dims = a_layout.shape().dims();
4431            let w_dims = w_layout.shape().dims();
4432            if a_dims.len() < 2 {
4433                return Err(Error::Msg(format!(
4434                    "Nf4Matmul: activations must be rank ≥ 2, got {a_dims:?}",
4435                ))
4436                .bt());
4437            }
4438            if w_dims.len() != 2 {
4439                return Err(Error::Msg(format!(
4440                    "Nf4Matmul: w_packed must be rank 2 [n, k/2], got {w_dims:?}",
4441                ))
4442                .bt());
4443            }
4444            let m = a_dims[a_dims.len() - 2];
4445            let k = a_dims[a_dims.len() - 1];
4446            let n = w_dims[0];
4447            let batch: usize = a_dims[..a_dims.len() - 2].iter().product::<usize>().max(1);
4448            if k % 2 != 0 {
4449                return Err(Error::Msg(format!(
4450                    "Nf4Matmul: k={k} must be even (w_packed holds 2 nibbles per byte along k)",
4451                ))
4452                .bt());
4453            }
4454            if k % *block_size != 0 {
4455                return Err(Error::Msg(format!(
4456                    "Nf4Matmul: k={k} must be a multiple of block_size={block_size}",
4457                ))
4458                .bt());
4459            }
4460            if w_dims[1] != k / 2 {
4461                return Err(Error::Msg(format!(
4462                    "Nf4Matmul: w_packed second dim {} must equal k/2 = {}",
4463                    w_dims[1],
4464                    k / 2,
4465                ))
4466                .bt());
4467            }
4468            OpParams::Nf4Matmul {
4469                batch,
4470                m,
4471                n,
4472                k,
4473                block_size: *block_size,
4474            }
4475        }
4476        // AwqMatmul: (batch, m, n, k) from activations [..., m, k] and the
4477        // kernel-layout weight [n, k/8]; the padded zeros/scales widths are the
4478        // op's own build-time invariant (checked by `awq_matmul`).
4479        Op::Fused(
4480            _,
4481            fuel_graph::registry::FusedOpParams::AwqMatmul {
4482                group_size,
4483                split_k_iters,
4484            },
4485        ) => {
4486            if node.inputs.len() != 4 {
4487                return Err(Error::Msg(format!(
4488                    "AwqMatmul expects 4 inputs (activations, weight, zeros, scales), got {}",
4489                    node.inputs.len(),
4490                ))
4491                .bt());
4492            }
4493            let a_layout = input_layout(node.inputs[0]);
4494            let w_layout = input_layout(node.inputs[1]);
4495            let a_dims = a_layout.shape().dims();
4496            let w_dims = w_layout.shape().dims();
4497            if a_dims.len() < 2 {
4498                return Err(Error::Msg(format!(
4499                    "AwqMatmul: activations must be rank ≥ 2, got {a_dims:?}",
4500                ))
4501                .bt());
4502            }
4503            if w_dims.len() != 2 {
4504                return Err(Error::Msg(format!(
4505                    "AwqMatmul: weight must be rank 2 [n, k/8], got {w_dims:?}",
4506                ))
4507                .bt());
4508            }
4509            let m = a_dims[a_dims.len() - 2];
4510            let k = a_dims[a_dims.len() - 1];
4511            let n = w_dims[0];
4512            let batch: usize = a_dims[..a_dims.len() - 2].iter().product::<usize>().max(1);
4513            if k % 8 != 0 || w_dims[1] != k / 8 {
4514                return Err(Error::Msg(format!(
4515                    "AwqMatmul: weight second dim {} must equal k/8 for k={k} (a multiple of 8)",
4516                    w_dims[1],
4517                ))
4518                .bt());
4519            }
4520            OpParams::AwqMatmul {
4521                batch,
4522                m,
4523                n,
4524                k,
4525                group_size: *group_size,
4526                split_k_iters: *split_k_iters,
4527            }
4528        }
4529        // Phase 7.6 step 3: SoftmaxLastDim flows through
4530        // `Op::Fused(FusedOps::SOFTMAX_LAST_DIM, _)`. The
4531        // SOFTMAX_LAST_DIM_BACKWARD variant added in step 6
4532        // follow-up shares the same `outer × last_dim` shape
4533        // contract (input 0 is `y` for forward / forward-output
4534        // for backward; both rank-≥1 with last-dim as the
4535        // reduction axis).
4536        op if op_is_softmax_last_dim(op)
4537            || matches!(op, Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM_BACKWARD) =>
4538        {
4539            let il = input_layout(node.inputs[0]);
4540            let dims = il.shape().dims();
4541            if dims.is_empty() {
4542                return Err(Error::Msg("Op::SoftmaxLastDim requires rank ≥ 1".to_string()).bt());
4543            }
4544            let last_dim = *dims.last().unwrap();
4545            let outer_count: usize = dims[..dims.len() - 1].iter().product();
4546            OpParams::SoftmaxLastDim {
4547                outer_count,
4548                last_dim,
4549            }
4550        }
4551        Op::Flip { dim } => {
4552            // Single input. Precompute the flat-3-axis split
4553            // (outer × dim × inner) from the input shape.
4554            if node.inputs.len() != 1 {
4555                return Err(Error::Msg(format!(
4556                    "Op::Flip expects 1 input, got {}",
4557                    node.inputs.len(),
4558                ))
4559                .bt());
4560            }
4561            let in_layout = input_layout(node.inputs[0]);
4562            let in_dims = in_layout.shape().dims();
4563            if *dim >= in_dims.len() {
4564                return Err(Error::Msg(format!(
4565                    "Op::Flip: dim {dim} out of range for rank {}",
4566                    in_dims.len(),
4567                ))
4568                .bt());
4569            }
4570            let outer_count: usize = in_dims[..*dim].iter().product();
4571            let dim_size = in_dims[*dim];
4572            let inner_count: usize = in_dims[*dim + 1..].iter().product();
4573            OpParams::Flip {
4574                outer_count,
4575                dim_size,
4576                inner_count,
4577                axis: *dim,
4578            }
4579        }
4580        Op::Roll { dim, shift } => {
4581            if node.inputs.len() != 1 {
4582                return Err(Error::Msg(format!(
4583                    "Op::Roll expects 1 input, got {}",
4584                    node.inputs.len(),
4585                ))
4586                .bt());
4587            }
4588            let in_layout = input_layout(node.inputs[0]);
4589            let in_dims = in_layout.shape().dims();
4590            if *dim >= in_dims.len() {
4591                return Err(Error::Msg(format!(
4592                    "Op::Roll: dim {dim} out of range for rank {}",
4593                    in_dims.len(),
4594                ))
4595                .bt());
4596            }
4597            let outer_count: usize = in_dims[..*dim].iter().product();
4598            let dim_size = in_dims[*dim];
4599            let inner_count: usize = in_dims[*dim + 1..].iter().product();
4600            OpParams::Roll {
4601                outer_count,
4602                dim_size,
4603                inner_count,
4604                shift: *shift,
4605                axis: *dim,
4606            }
4607        }
4608        Op::CumSum { dim } => {
4609            if node.inputs.len() != 1 {
4610                return Err(Error::Msg(format!(
4611                    "Op::CumSum expects 1 input, got {}",
4612                    node.inputs.len(),
4613                ))
4614                .bt());
4615            }
4616            let in_layout = input_layout(node.inputs[0]);
4617            let in_dims = in_layout.shape().dims();
4618            if *dim >= in_dims.len() {
4619                return Err(Error::Msg(format!(
4620                    "Op::CumSum: dim {dim} out of range for rank {}",
4621                    in_dims.len(),
4622                ))
4623                .bt());
4624            }
4625            let outer_count: usize = in_dims[..*dim].iter().product();
4626            let dim_size = in_dims[*dim];
4627            let inner_count: usize = in_dims[*dim + 1..].iter().product();
4628            OpParams::CumSum {
4629                outer_count,
4630                dim_size,
4631                inner_count,
4632                axis: *dim,
4633            }
4634        }
4635        Op::Triu { diagonal } | Op::Tril { diagonal } => {
4636            if node.inputs.len() != 1 {
4637                return Err(Error::Msg(format!(
4638                    "Op::Triu/Tril expects 1 input, got {}",
4639                    node.inputs.len(),
4640                ))
4641                .bt());
4642            }
4643            let in_layout = input_layout(node.inputs[0]);
4644            let in_dims = in_layout.shape().dims();
4645            if in_dims.len() < 2 {
4646                return Err(Error::Msg(format!(
4647                    "Op::Triu/Tril requires rank >= 2, got {}",
4648                    in_dims.len(),
4649                ))
4650                .bt());
4651            }
4652            let rows = in_dims[in_dims.len() - 2];
4653            let cols = in_dims[in_dims.len() - 1];
4654            let batch_count: usize = in_dims[..in_dims.len() - 2]
4655                .iter()
4656                .product::<usize>()
4657                .max(1);
4658            OpParams::Triangular {
4659                batch_count,
4660                rows,
4661                cols,
4662                diagonal: *diagonal,
4663            }
4664        }
4665        Op::LogSoftmaxLastDim => {
4666            if node.inputs.len() != 1 {
4667                return Err(Error::Msg(format!(
4668                    "Op::LogSoftmaxLastDim expects 1 input, got {}",
4669                    node.inputs.len(),
4670                ))
4671                .bt());
4672            }
4673            let in_layout = input_layout(node.inputs[0]);
4674            let in_dims = in_layout.shape().dims();
4675            if in_dims.is_empty() {
4676                return Err(Error::Msg("Op::LogSoftmaxLastDim requires rank ≥ 1".to_string()).bt());
4677            }
4678            let last_dim = *in_dims.last().unwrap();
4679            let outer_count: usize = in_dims[..in_dims.len() - 1].iter().product();
4680            OpParams::LogSoftmaxLastDim {
4681                outer_count,
4682                last_dim,
4683            }
4684        }
4685        Op::LogSoftmaxLastDimBackward => {
4686            // Inputs: (forward_output_y, upstream_grad). Same shape contract
4687            // as SoftmaxLastDimBackward — last-dim row-wise dispatch.
4688            if node.inputs.len() != 2 {
4689                return Err(Error::Msg(format!(
4690                    "Op::LogSoftmaxLastDimBackward expects 2 inputs, got {}",
4691                    node.inputs.len(),
4692                ))
4693                .bt());
4694            }
4695            let in_layout = input_layout(node.inputs[0]);
4696            let in_dims = in_layout.shape().dims();
4697            if in_dims.is_empty() {
4698                return Err(Error::Msg(
4699                    "Op::LogSoftmaxLastDimBackward requires rank ≥ 1".to_string(),
4700                )
4701                .bt());
4702            }
4703            let last_dim = *in_dims.last().unwrap();
4704            let outer_count: usize = in_dims[..in_dims.len() - 1].iter().product();
4705            OpParams::LogSoftmaxLastDim {
4706                outer_count,
4707                last_dim,
4708            }
4709        }
4710        Op::MaskedFill { value } => {
4711            if node.inputs.len() != 2 {
4712                return Err(Error::Msg(format!(
4713                    "Op::MaskedFill expects 2 inputs (x, mask), got {}",
4714                    node.inputs.len(),
4715                ))
4716                .bt());
4717            }
4718            let fill_bytes = scalar_to_bytes(*value);
4719            OpParams::MaskedFill { fill_bytes }
4720        }
4721        // Op::MaskedFillInplace tracked by the parallel in-place
4722        // binary family session — not in HEAD's Op enum right now.
4723        Op::PadBackward {
4724            in_shape,
4725            padding,
4726            mode,
4727        } => {
4728            // Single input is the upstream gradient; output is the
4729            // input gradient (shape == `in_shape`).
4730            if node.inputs.len() != 1 {
4731                return Err(Error::Msg(format!(
4732                    "Op::PadBackward expects 1 input, got {}",
4733                    node.inputs.len(),
4734                ))
4735                .bt());
4736            }
4737            let in_dims: Vec<usize> = in_shape.dims().to_vec();
4738            // Output of the original forward Pad is the input shape
4739            // of the backward (== upstream's shape).
4740            let out_dims: Vec<usize> = in_dims
4741                .iter()
4742                .zip(padding.iter())
4743                .map(|(&d, &(b, a))| d + b + a)
4744                .collect();
4745            let mode_tag: u8 = match mode {
4746                fuel_graph::PadMode::Constant => 0,
4747                fuel_graph::PadMode::Reflect => 1,
4748                fuel_graph::PadMode::Replicate => 2,
4749            };
4750            OpParams::PadBackward {
4751                in_shape: in_dims,
4752                out_shape: out_dims,
4753                padding: padding.clone(),
4754                mode_tag,
4755            }
4756        }
4757        Op::Pad {
4758            padding,
4759            mode,
4760            value,
4761        } => {
4762            if node.inputs.len() != 1 {
4763                return Err(Error::Msg(format!(
4764                    "Op::Pad expects 1 input, got {}",
4765                    node.inputs.len(),
4766                ))
4767                .bt());
4768            }
4769            let in_layout = input_layout(node.inputs[0]);
4770            let in_dims: Vec<usize> = in_layout.shape().dims().to_vec();
4771            if padding.len() != in_dims.len() {
4772                return Err(Error::Msg(format!(
4773                    "Op::Pad: padding.len() ({}) != input rank ({})",
4774                    padding.len(),
4775                    in_dims.len(),
4776                ))
4777                .bt());
4778            }
4779            let out_dims: Vec<usize> = in_dims
4780                .iter()
4781                .zip(padding.iter())
4782                .map(|(&d, &(b, a))| d + b + a)
4783                .collect();
4784            let mode_tag: u8 = match mode {
4785                fuel_graph::PadMode::Constant => 0,
4786                fuel_graph::PadMode::Reflect => 1,
4787                fuel_graph::PadMode::Replicate => 2,
4788            };
4789            // Encode fill value as bytes for the output dtype. The
4790            // kernel is dtype-agnostic — it just memcopies the
4791            // pattern. Conversion happens once here per node, not
4792            // per element in the kernel.
4793            let fill_bytes = encode_value_to_bytes(node.dtype, *value)?;
4794            OpParams::Pad {
4795                in_shape: in_dims,
4796                out_shape: out_dims,
4797                padding: padding.clone(),
4798                mode_tag,
4799                fill_bytes,
4800            }
4801        }
4802        Op::IndexAdd { dim } => {
4803            // Inputs: (base, indices, src). All same dtype except
4804            // indices is U32. Output shape == base shape.
4805            if node.inputs.len() != 3 {
4806                return Err(Error::Msg(format!(
4807                    "Op::IndexAdd expects 3 inputs (base, indices, src), got {}",
4808                    node.inputs.len(),
4809                ))
4810                .bt());
4811            }
4812            let base_layout = input_layout(node.inputs[0]);
4813            let idx_layout = input_layout(node.inputs[1]);
4814            let src_layout = input_layout(node.inputs[2]);
4815            let base_dims = base_layout.shape().dims();
4816            let idx_dims = idx_layout.shape().dims();
4817            let src_dims = src_layout.shape().dims();
4818            if *dim >= base_dims.len() {
4819                return Err(Error::Msg(format!(
4820                    "Op::IndexAdd: dim {dim} out of range for base rank {}",
4821                    base_dims.len(),
4822                ))
4823                .bt());
4824            }
4825            if idx_dims.len() != 1 {
4826                return Err(Error::Msg(format!(
4827                    "Op::IndexAdd: indices must be rank 1, got {idx_dims:?}",
4828                ))
4829                .bt());
4830            }
4831            if base_dims.len() != src_dims.len() {
4832                return Err(Error::Msg(format!(
4833                    "Op::IndexAdd: base rank ({}) != src rank ({})",
4834                    base_dims.len(),
4835                    src_dims.len(),
4836                ))
4837                .bt());
4838            }
4839            let outer_count: usize = base_dims[..*dim].iter().product();
4840            let base_dim_size = base_dims[*dim];
4841            let inner_count: usize = base_dims[*dim + 1..].iter().product();
4842            let n_indices = idx_dims[0];
4843            OpParams::IndexAdd {
4844                outer_count,
4845                base_dim_size,
4846                n_indices,
4847                inner_count,
4848            }
4849        }
4850        Op::ScatterAdd { dim } => {
4851            if node.inputs.len() != 3 {
4852                return Err(Error::Msg(format!(
4853                    "Op::ScatterAdd expects 3 inputs (base, indices, src), got {}",
4854                    node.inputs.len(),
4855                ))
4856                .bt());
4857            }
4858            let base_layout = input_layout(node.inputs[0]);
4859            let src_layout = input_layout(node.inputs[2]);
4860            let base_shape: Vec<usize> = base_layout.shape().dims().to_vec();
4861            let src_shape: Vec<usize> = src_layout.shape().dims().to_vec();
4862            if base_shape.len() != src_shape.len() {
4863                return Err(Error::Msg(format!(
4864                    "Op::ScatterAdd: base rank ({}) != src rank ({})",
4865                    base_shape.len(),
4866                    src_shape.len(),
4867                ))
4868                .bt());
4869            }
4870            if *dim >= base_shape.len() {
4871                return Err(Error::Msg(format!(
4872                    "Op::ScatterAdd: dim {dim} out of range for rank {}",
4873                    base_shape.len(),
4874                ))
4875                .bt());
4876            }
4877            OpParams::ScatterAdd {
4878                base_shape,
4879                src_shape,
4880                dim: *dim,
4881            }
4882        }
4883        // Phase 7.6 step 5: Rope routes through the registry; the
4884        // legacy `Op::Rope` arm was retired with the variant.
4885        Op::Fused(_, fuel_graph::registry::FusedOpParams::Rope) => {
4886            // Inputs: (x, cos, sin). x is [..., seq, head_dim];
4887            // cos/sin are [seq, head_dim] (validated at graph build).
4888            if node.inputs.len() != 3 {
4889                return Err(Error::Msg(format!(
4890                    "Op::Rope expects 3 inputs (x, cos, sin), got {}",
4891                    node.inputs.len(),
4892                ))
4893                .bt());
4894            }
4895            let x_layout = input_layout(node.inputs[0]);
4896            let x_dims = x_layout.shape().dims();
4897            if x_dims.len() < 2 {
4898                return Err(
4899                    Error::Msg(format!("Op::Rope: x must have rank ≥ 2, got {x_dims:?}",)).bt(),
4900                );
4901            }
4902            let head_dim = *x_dims.last().unwrap();
4903            let seq = x_dims[x_dims.len() - 2];
4904            let outer_count: usize = x_dims[..x_dims.len() - 2].iter().product();
4905            OpParams::Rope {
4906                outer_count,
4907                seq,
4908                head_dim,
4909            }
4910        }
4911        Op::Gather { dim } => {
4912            // inputs[0] = source, inputs[1] = U32 indices (same rank).
4913            if node.inputs.len() != 2 {
4914                return Err(Error::Msg(format!(
4915                    "Op::Gather expects 2 inputs (source, indices), got {}",
4916                    node.inputs.len(),
4917                ))
4918                .bt());
4919            }
4920            let src_layout = input_layout(node.inputs[0]);
4921            let idx_layout = input_layout(node.inputs[1]);
4922            let source_shape: Vec<usize> = src_layout.shape().dims().to_vec();
4923            let output_shape: Vec<usize> = idx_layout.shape().dims().to_vec();
4924            if source_shape.len() != output_shape.len() {
4925                return Err(Error::Msg(format!(
4926                    "Op::Gather: source rank ({}) != indices rank ({})",
4927                    source_shape.len(),
4928                    output_shape.len(),
4929                ))
4930                .bt());
4931            }
4932            if *dim >= source_shape.len() {
4933                return Err(Error::Msg(format!(
4934                    "Op::Gather: dim {dim} out of range for rank {}",
4935                    source_shape.len(),
4936                ))
4937                .bt());
4938            }
4939            OpParams::Gather {
4940                source_shape,
4941                output_shape,
4942                dim: *dim,
4943            }
4944        }
4945        Op::NonZeroIndices { count_sym } => {
4946            // inputs[0] = x (the value tensor). capacity == x.elem_count();
4947            // the bundled output is [indices [capacity] U32 ; count [1] U32].
4948            if node.inputs.len() != 1 {
4949                return Err(Error::Msg(format!(
4950                    "Op::NonZeroIndices expects 1 input, got {}",
4951                    node.inputs.len(),
4952                ))
4953                .bt());
4954            }
4955            let x_layout = input_layout(node.inputs[0]);
4956            let capacity = x_layout.shape().elem_count();
4957            OpParams::NonZeroIndices {
4958                capacity,
4959                count_sym: *count_sym,
4960            }
4961        }
4962        Op::IndexSelect { dim } => {
4963            // inputs[0] = source, inputs[1] = U32 indices (rank 1).
4964            if node.inputs.len() != 2 {
4965                return Err(Error::Msg(format!(
4966                    "Op::IndexSelect expects 2 inputs (source, indices), got {}",
4967                    node.inputs.len(),
4968                ))
4969                .bt());
4970            }
4971            let src_layout = input_layout(node.inputs[0]);
4972            let idx_layout = input_layout(node.inputs[1]);
4973            let src_dims = src_layout.shape().dims();
4974            let idx_dims = idx_layout.shape().dims();
4975            if *dim >= src_dims.len() {
4976                return Err(Error::Msg(format!(
4977                    "Op::IndexSelect: dim {dim} out of range for source rank {}",
4978                    src_dims.len(),
4979                ))
4980                .bt());
4981            }
4982            if idx_dims.len() != 1 {
4983                return Err(Error::Msg(format!(
4984                    "Op::IndexSelect: indices must be rank 1, got shape {idx_dims:?}",
4985                ))
4986                .bt());
4987            }
4988            let outer_count: usize = src_dims[..*dim].iter().product();
4989            let source_dim_size = src_dims[*dim];
4990            let inner_count: usize = src_dims[*dim + 1..].iter().product();
4991            let n_indices = idx_dims[0];
4992            OpParams::IndexSelect {
4993                outer_count,
4994                source_dim_size,
4995                n_indices,
4996                inner_count,
4997            }
4998        }
4999        // Phase 7.6 step 5: legacy `Op::RmsNormLastDim` /
5000        // `Op::LayerNormLastDim` arms retired with the variants;
5001        // both now route through `Op::Fused(NORM_LAST_DIM, _)`.
5002        // Step 6 follow-up extends this arm to also cover the
5003        // backward variants (same outer × last_dim + eps geometry).
5004        Op::Fused(fid, params)
5005            if *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM
5006                || *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM
5007                || *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM_BACKWARD
5008                || *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM_BACKWARD =>
5009        {
5010            let eps = match params {
5011                fuel_graph::registry::FusedOpParams::RmsNormLastDim { eps } => *eps,
5012                fuel_graph::registry::FusedOpParams::LayerNormLastDim { eps } => *eps,
5013                fuel_graph::registry::FusedOpParams::RmsNormLastDimBackward { eps } => *eps,
5014                fuel_graph::registry::FusedOpParams::LayerNormLastDimBackward { eps } => *eps,
5015                _ => {
5016                    return Err(Error::Msg(format!(
5017                        "Op::Fused(NORM_LAST_DIM[_BACKWARD], _) expected \
5018                     RmsNormLastDim[Backward] or LayerNormLastDim[Backward] params, got {params:?}",
5019                    ))
5020                    .bt());
5021                }
5022            };
5023            let il = input_layout(node.inputs[0]);
5024            let dims = il.shape().dims();
5025            if dims.is_empty() {
5026                return Err(Error::Msg(
5027                    "Op::Fused(NORM_LAST_DIM[_BACKWARD], _) requires rank ≥ 1".to_string(),
5028                )
5029                .bt());
5030            }
5031            let last_dim = *dims.last().unwrap();
5032            let outer_count: usize = dims[..dims.len() - 1].iter().product();
5033            OpParams::NormLastDim {
5034                outer_count,
5035                last_dim,
5036                eps,
5037            }
5038        }
5039        // ReduceMaxToBackward: shape pair via the new
5040        // OpParams::ReduceMaxToBackward variant. x's shape is
5041        // `input_shape`; upstream's shape is `output_shape`.
5042        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::REDUCE_MAX_TO_BACKWARD => {
5043            if node.inputs.len() != 2 {
5044                return Err(Error::Msg(format!(
5045                    "Op::Fused(REDUCE_MAX_TO_BACKWARD) expects 2 inputs, got {}",
5046                    node.inputs.len(),
5047                ))
5048                .bt());
5049            }
5050            let x_layout = input_layout(node.inputs[0]);
5051            let up_layout = input_layout(node.inputs[1]);
5052            let input_shape: Vec<usize> = x_layout.shape().dims().to_vec();
5053            let output_shape: Vec<usize> = up_layout.shape().dims().to_vec();
5054            OpParams::ReduceMaxToBackward {
5055                input_shape,
5056                output_shape,
5057            }
5058        }
5059        Op::Concat { dim } => {
5060            // Output's shape: [..., total_dim, ...]. Compute outer
5061            // and inner counts from output_shape[..dim] and
5062            // [dim+1..]; per-input dim sizes from each input's
5063            // layout shape at index `dim`.
5064            if node.inputs.is_empty() {
5065                return Err(Error::Msg("Op::Concat requires at least 1 input".to_string()).bt());
5066            }
5067            let out_dims = node.shape.dims();
5068            if *dim >= out_dims.len() {
5069                return Err(Error::Msg(format!(
5070                    "Op::Concat: dim {dim} out of range for output rank {}",
5071                    out_dims.len(),
5072                ))
5073                .bt());
5074            }
5075            let outer_count: usize = out_dims[..*dim].iter().product();
5076            let inner_count: usize = out_dims[*dim + 1..].iter().product();
5077            let mut input_dim_sizes: Vec<usize> = Vec::with_capacity(node.inputs.len());
5078            for in_id in &node.inputs {
5079                let il = input_layout(*in_id);
5080                let il_dims = il.shape().dims();
5081                if *dim >= il_dims.len() {
5082                    return Err(Error::Msg(format!(
5083                        "Op::Concat: input {in_id:?} has rank {} but concat dim is {dim}",
5084                        il_dims.len(),
5085                    ))
5086                    .bt());
5087                }
5088                input_dim_sizes.push(il_dims[*dim]);
5089            }
5090            OpParams::Concat {
5091                outer_count,
5092                input_dim_sizes,
5093                inner_count,
5094                axis: *dim,
5095            }
5096        }
5097        Op::AddScalar(c) => OpParams::Affine { mul: 1.0, add: *c },
5098        Op::MulScalar(c) => OpParams::Affine { mul: *c, add: 0.0 },
5099        Op::Clamp { min, max } => OpParams::Clamp {
5100            min: *min,
5101            max: *max,
5102        },
5103        Op::PowI(exp) => OpParams::PowI { exp: *exp },
5104        Op::ClampInplace { min, max } => OpParams::Clamp {
5105            min: *min,
5106            max: *max,
5107        },
5108        Op::PowIInplace(exp) => OpParams::PowI { exp: *exp },
5109        // PowI backward — `(x, upstream) → grad_x = exp · x^(exp-1) ·
5110        // upstream`. Pulls the same `exp` as the forward through
5111        // FusedOpParams::PowIBackward (autograd carries it across).
5112        Op::Fused(_, fuel_graph::registry::FusedOpParams::PowIBackward { exp }) => {
5113            OpParams::PowI { exp: *exp }
5114        }
5115        // In-place affine (Phase 3 of the in-place ops infrastructure):
5116        // reuse the existing `OpParams::Affine` payload — the kernel
5117        // side doesn't care whether the destination is fresh or aliases
5118        // the input; the structural decision lives in the executor's
5119        // dedicated `WorkItemKind::InplaceKernel` arm.
5120        Op::Fused(_, fuel_graph::registry::FusedOpParams::InplaceAffine { mul, add }) => {
5121            OpParams::Affine {
5122                mul: *mul,
5123                add: *add,
5124            }
5125        }
5126        // Phase 7.6 step 5: legacy `Op::Conv2D` arm retired with the
5127        // variant; Conv2D routes through `Op::Fused(CONV2D, _)`.
5128        Op::Fused(
5129            _,
5130            fuel_graph::registry::FusedOpParams::Conv2D {
5131                stride,
5132                padding,
5133                groups,
5134            },
5135        ) => {
5136            // Inputs[0] = x [N, Cin, Hin, Win]; inputs[1] = weight
5137            // [Cout, Cin/groups, Kh, Kw]; inputs[2] (optional) = bias [Cout].
5138            // Output (this Node's shape) = [N, Cout, Hout, Wout].
5139            if node.inputs.len() != 2 && node.inputs.len() != 3 {
5140                return Err(Error::Msg(format!(
5141                    "Op::Conv2D expects 2 or 3 inputs, got {}",
5142                    node.inputs.len(),
5143                ))
5144                .bt());
5145            }
5146            let x_layout = input_layout(node.inputs[0]);
5147            let w_layout = input_layout(node.inputs[1]);
5148            let x_dims = x_layout.shape().dims();
5149            let w_dims = w_layout.shape().dims();
5150            if x_dims.len() != 4 || w_dims.len() != 4 {
5151                return Err(Error::Msg(format!(
5152                    "Op::Conv2D requires rank-4 x and weight; got x={x_dims:?} w={w_dims:?}",
5153                ))
5154                .bt());
5155            }
5156            let out_dims = node.shape.dims();
5157            if out_dims.len() != 4 {
5158                return Err(Error::Msg(format!(
5159                    "Op::Conv2D output must be rank 4, got {out_dims:?}",
5160                ))
5161                .bt());
5162            }
5163            let x_shape = [x_dims[0], x_dims[1], x_dims[2], x_dims[3]];
5164            let w_shape = [w_dims[0], w_dims[1], w_dims[2], w_dims[3]];
5165            let out_shape = [out_dims[0], out_dims[1], out_dims[2], out_dims[3]];
5166            OpParams::Conv2D {
5167                x_shape,
5168                w_shape,
5169                out_shape,
5170                stride: *stride,
5171                padding: *padding,
5172                dilation: (1, 1),
5173                groups: *groups,
5174            }
5175        }
5176        // Phase 7.6 step 5 (final): legacy `Op::PagedAttn` arm dropped.
5177        Op::Fused(
5178            _,
5179            fuel_graph::registry::FusedOpParams::PagedAttn {
5180                softmax_scale,
5181                block_size,
5182                softcap,
5183            },
5184        ) => {
5185            // Inputs[0]=q [B,Hq,Sq,D], inputs[1]=k_cache [num_blocks,
5186            // block_size, Hkv, D], inputs[2]=v_cache same shape,
5187            // inputs[3]=block_table [B, max_blocks_per_seq] U32,
5188            // inputs[4]=context_lens [B] U32, inputs[5]=alibi [Hq] (optional).
5189            if node.inputs.len() != 5 && node.inputs.len() != 6 {
5190                return Err(Error::Msg(format!(
5191                    "Op::PagedAttn expects 5 or 6 inputs, got {}",
5192                    node.inputs.len(),
5193                ))
5194                .bt());
5195            }
5196            let q_layout = input_layout(node.inputs[0]);
5197            let kc_layout = input_layout(node.inputs[1]);
5198            let vc_layout = input_layout(node.inputs[2]);
5199            let bt_layout = input_layout(node.inputs[3]);
5200            let q_dims = q_layout.shape().dims();
5201            let kc_dims = kc_layout.shape().dims();
5202            let vc_dims = vc_layout.shape().dims();
5203            let bt_dims = bt_layout.shape().dims();
5204            if q_dims.len() != 4 || kc_dims.len() != 4 || vc_dims.len() != 4 {
5205                return Err(Error::Msg(format!(
5206                    "Op::PagedAttn requires rank-4 q/k_cache/v_cache; \
5207                     got q={q_dims:?} k_cache={kc_dims:?} v_cache={vc_dims:?}",
5208                ))
5209                .bt());
5210            }
5211            if kc_dims != vc_dims {
5212                return Err(Error::Msg(format!(
5213                    "Op::PagedAttn: k_cache {kc_dims:?} and v_cache {vc_dims:?} must match",
5214                ))
5215                .bt());
5216            }
5217            if bt_dims.len() != 2 {
5218                return Err(Error::Msg(format!(
5219                    "Op::PagedAttn: block_table must be rank 2 [B, max_blocks_per_seq], got {bt_dims:?}",
5220                ))
5221                .bt());
5222            }
5223            if kc_dims[1] != *block_size {
5224                return Err(Error::Msg(format!(
5225                    "Op::PagedAttn: k_cache block_size dim ({}) must equal Op's block_size ({})",
5226                    kc_dims[1], block_size,
5227                ))
5228                .bt());
5229            }
5230            OpParams::PagedAttn {
5231                b: q_dims[0],
5232                hq: q_dims[1],
5233                hkv: kc_dims[2],
5234                sq: q_dims[2],
5235                d: q_dims[3],
5236                block_size: *block_size,
5237                max_blocks_per_seq: bt_dims[1],
5238                num_blocks: kc_dims[0],
5239                softmax_scale: *softmax_scale,
5240                softcap: *softcap,
5241            }
5242        }
5243        // Phase 7.6 step 5 (final): legacy `Op::FlashAttn` arm dropped.
5244        Op::Fused(
5245            _,
5246            fuel_graph::registry::FusedOpParams::FlashAttn {
5247                softmax_scale,
5248                causal,
5249                window_size_left,
5250                window_size_right,
5251                softcap,
5252                k_len,
5253            },
5254        ) => {
5255            // Inputs[0]=q [B,Hq,Sq,D], inputs[1]=k [B,Hkv,Sk,D],
5256            // inputs[2]=v [B,Hkv,Sk,D], inputs[3]=alibi_slopes [Hq] (optional).
5257            // `sk` is the PHYSICAL K extent (capacity, for strides/bytes);
5258            // `k_len` (resolved below) is the LOGICAL attended length.
5259            if node.inputs.len() != 3 && node.inputs.len() != 4 {
5260                return Err(Error::Msg(format!(
5261                    "Op::FlashAttn expects 3 or 4 inputs, got {}",
5262                    node.inputs.len(),
5263                ))
5264                .bt());
5265            }
5266            let q_layout = input_layout(node.inputs[0]);
5267            let k_layout = input_layout(node.inputs[1]);
5268            let v_layout = input_layout(node.inputs[2]);
5269            let q_dims = q_layout.shape().dims();
5270            let k_dims = k_layout.shape().dims();
5271            let v_dims = v_layout.shape().dims();
5272            if q_dims.len() != 4 || k_dims.len() != 4 || v_dims.len() != 4 {
5273                return Err(Error::Msg(format!(
5274                    "Op::FlashAttn requires rank-4 q/k/v; got q={q_dims:?} k={k_dims:?} v={v_dims:?}",
5275                ))
5276                .bt());
5277            }
5278            if k_dims != v_dims {
5279                return Err(Error::Msg(format!(
5280                    "Op::FlashAttn: k {k_dims:?} and v {v_dims:?} must share shape",
5281                ))
5282                .bt());
5283            }
5284            if q_dims[0] != k_dims[0] || q_dims[3] != k_dims[3] {
5285                return Err(Error::Msg(format!(
5286                    "Op::FlashAttn: q {q_dims:?} and k {k_dims:?} must share B and D",
5287                ))
5288                .bt());
5289            }
5290            let sk = k_dims[2];
5291            // Resolve the logical attended length. `None` ⇒ attend the
5292            // full K extent (today's behavior). `Some(dyn)` ⇒ resolve
5293            // against the per-pass SymEnv; the resolved length must fit
5294            // the capacity and cover Sq (a valid causal prefix).
5295            let attended_k_len = match k_len {
5296                None => sk,
5297                Some(dyn_k) => {
5298                    let kl = dyn_k.resolve(sym_env).ok_or_else(|| {
5299                        Error::Msg(format!(
5300                            "Op::FlashAttn: dynamic k_len {dyn_k:?} is unbound in the SymEnv at realize",
5301                        ))
5302                        .bt()
5303                    })?;
5304                    if kl > sk {
5305                        return Err(Error::Msg(format!(
5306                            "Op::FlashAttn: resolved k_len ({kl}) exceeds K capacity ({sk})",
5307                        ))
5308                        .bt());
5309                    }
5310                    if kl < q_dims[2] {
5311                        return Err(Error::Msg(format!(
5312                            "Op::FlashAttn: resolved k_len ({kl}) < Sq ({}) — not a valid causal prefix",
5313                            q_dims[2],
5314                        ))
5315                        .bt());
5316                    }
5317                    kl
5318                }
5319            };
5320            OpParams::FlashAttn {
5321                b: q_dims[0],
5322                hq: q_dims[1],
5323                hkv: k_dims[1],
5324                sq: q_dims[2],
5325                sk,
5326                d: q_dims[3],
5327                k_len: attended_k_len,
5328                softmax_scale: *softmax_scale,
5329                causal: *causal,
5330                window_size_left: *window_size_left,
5331                window_size_right: *window_size_right,
5332                softcap: *softcap,
5333            }
5334        }
5335        Op::ReduceSumTo(target_shape) => {
5336            if node.inputs.len() != 1 {
5337                return Err(Error::Msg(format!(
5338                    "Op::ReduceSumTo expects 1 input, got {}",
5339                    node.inputs.len(),
5340                ))
5341                .bt());
5342            }
5343            let in_layout = input_layout(node.inputs[0]);
5344            let input_shape: Vec<usize> = in_layout.shape().dims().to_vec();
5345            let output_shape: Vec<usize> = target_shape.dims().to_vec();
5346            OpParams::ReduceSumTo {
5347                input_shape,
5348                output_shape,
5349            }
5350        }
5351        Op::ReduceMaxTo(target_shape) => {
5352            if node.inputs.len() != 1 {
5353                return Err(Error::Msg(format!(
5354                    "Op::ReduceMaxTo expects 1 input, got {}",
5355                    node.inputs.len(),
5356                ))
5357                .bt());
5358            }
5359            let in_layout = input_layout(node.inputs[0]);
5360            let input_shape: Vec<usize> = in_layout.shape().dims().to_vec();
5361            let output_shape: Vec<usize> = target_shape.dims().to_vec();
5362            OpParams::ReduceMaxTo {
5363                input_shape,
5364                output_shape,
5365            }
5366        }
5367        // Phase 7.6 step 5 (final): legacy `Op::ConvTranspose2D` arm dropped.
5368        Op::Fused(
5369            _,
5370            fuel_graph::registry::FusedOpParams::ConvTranspose2D {
5371                stride,
5372                padding,
5373                output_padding,
5374                dilation,
5375                groups,
5376            },
5377        ) => {
5378            // Inputs[0] = x [N, Cin, Hin, Win]; inputs[1] = weight
5379            // [Cin, Cout/groups, Kh, Kw]; inputs[2] (optional) = bias [Cout].
5380            // Output (this Node's shape) = [N, Cout, Hout, Wout].
5381            if node.inputs.len() != 2 && node.inputs.len() != 3 {
5382                return Err(Error::Msg(format!(
5383                    "Op::ConvTranspose2D expects 2 or 3 inputs, got {}",
5384                    node.inputs.len(),
5385                ))
5386                .bt());
5387            }
5388            let x_layout = input_layout(node.inputs[0]);
5389            let w_layout = input_layout(node.inputs[1]);
5390            let x_dims = x_layout.shape().dims();
5391            let w_dims = w_layout.shape().dims();
5392            if x_dims.len() != 4 || w_dims.len() != 4 {
5393                return Err(Error::Msg(format!(
5394                    "Op::ConvTranspose2D requires rank-4 x and weight; got x={x_dims:?} w={w_dims:?}",
5395                ))
5396                .bt());
5397            }
5398            let out_dims = node.shape.dims();
5399            if out_dims.len() != 4 {
5400                return Err(Error::Msg(format!(
5401                    "Op::ConvTranspose2D output must be rank 4, got {out_dims:?}",
5402                ))
5403                .bt());
5404            }
5405            let x_shape = [x_dims[0], x_dims[1], x_dims[2], x_dims[3]];
5406            let w_shape = [w_dims[0], w_dims[1], w_dims[2], w_dims[3]];
5407            let out_shape = [out_dims[0], out_dims[1], out_dims[2], out_dims[3]];
5408            OpParams::ConvTranspose2D {
5409                x_shape,
5410                w_shape,
5411                out_shape,
5412                stride: *stride,
5413                padding: *padding,
5414                output_padding: *output_padding,
5415                dilation: *dilation,
5416                groups: *groups,
5417            }
5418        }
5419        Op::WriteSlice { ranges, dyn_offset } => {
5420            // inputs[0] = destination (its shape == this node's shape
5421            // since WriteSlice's output adopts the destination's
5422            // Layout). inputs[1] = source slab; its shape is implied
5423            // by `ranges`. The kernel needs the destination shape to
5424            // compute strides for the slab walk.
5425            if node.inputs.len() != 2 {
5426                return Err(Error::Msg(format!(
5427                    "Op::WriteSlice expects 2 inputs (destination, source), got {}",
5428                    node.inputs.len(),
5429                ))
5430                .bt());
5431            }
5432            let dest_dims = node.shape.dims().to_vec();
5433            if ranges.len() != dest_dims.len() {
5434                return Err(Error::Msg(format!(
5435                    "Op::WriteSlice: ranges.len() ({}) must equal destination rank ({})",
5436                    ranges.len(),
5437                    dest_dims.len(),
5438                ))
5439                .bt());
5440            }
5441            // Phase D symbolic extents: when present, resolve the runtime
5442            // start offset against the per-pass SymEnv, overriding
5443            // `ranges[axis].0`. The slab WIDTH on that axis stays
5444            // `ranges[axis].1 - ranges[axis].0`, so the effective range
5445            // becomes `(base, base + width)`. `None` ⇒ fully static, and
5446            // the SymEnv is never consulted (empty-env realize unchanged).
5447            //
5448            // DUAL-PATH (increment 2b — data-determined dynamic shapes):
5449            //  - The offset resolves in the compile-time `sym_env` (static,
5450            //    or an INPUT-determined `cached_len`): bake it into `ranges`
5451            //    now, exactly as before.
5452            //  - It is UNBOUND at compile AND a producer in this graph binds
5453            //    it (`Op::NonZeroIndices`'s count, etc.): it is
5454            //    DATA-DETERMINED — leave `ranges[axis]` as the static
5455            //    placeholder and DEFER, carrying the `DynScalar` in
5456            //    `deferred_dyn_offset`. The `WorkItemKind::WriteSlice`
5457            //    executor arm resolves it from `produced_syms` (after the
5458            //    producer runs) and bounds-checks the resolved range there.
5459            //  - It is unbound AND no producer binds it: a genuine caller
5460            //    error → surface it here (preserves the unbound-error path).
5461            let mut ranges = ranges.clone();
5462            let mut deferred_dyn_offset: Option<(usize, fuel_ir::DynScalar)> = None;
5463            if let Some((axis, off)) = dyn_offset {
5464                if *axis >= ranges.len() {
5465                    return Err(Error::Msg(format!(
5466                        "Op::WriteSlice: dyn_offset axis ({axis}) out of bounds for rank {}",
5467                        ranges.len(),
5468                    ))
5469                    .bt());
5470                }
5471                match off.resolve(sym_env) {
5472                    Some(base) => {
5473                        let (start, end) = ranges[*axis];
5474                        let width = end - start;
5475                        ranges[*axis] = (base, base + width);
5476                    }
5477                    None => {
5478                        let is_data_determined = matches!(off, fuel_ir::DynScalar::Sym(s)
5479                            if graph.binds_data_determined_sym(*s));
5480                        if is_data_determined {
5481                            deferred_dyn_offset = Some((*axis, *off));
5482                        } else {
5483                            return Err(Error::Msg(format!(
5484                                "Op::WriteSlice: dynamic offset {off:?} on axis {axis} is \
5485                                 unbound in the SymEnv at realize (and no producer in the \
5486                                 graph binds it, so it is not data-determined)",
5487                            ))
5488                            .bt());
5489                        }
5490                    }
5491                }
5492            }
5493            for (i, &(start, end)) in ranges.iter().enumerate() {
5494                // The deferred axis still holds its static placeholder; the
5495                // executor bounds-checks the resolved range after producing
5496                // the count. Every other axis is fully known now.
5497                if deferred_dyn_offset.is_some_and(|(a, _)| a == i) {
5498                    continue;
5499                }
5500                if end < start || end > dest_dims[i] {
5501                    return Err(Error::Msg(format!(
5502                        "Op::WriteSlice: ranges[{i}] = ({start}, {end}) invalid \
5503                         for destination dim {i} = {}",
5504                        dest_dims[i],
5505                    ))
5506                    .bt());
5507                }
5508            }
5509            OpParams::WriteSlice {
5510                dest_shape: dest_dims,
5511                ranges,
5512                deferred_dyn_offset,
5513            }
5514        }
5515        Op::WriteSliceRotating {
5516            axis,
5517            modulus,
5518            ranges,
5519        } => {
5520            // inputs[0] = destination, inputs[1] = source slab,
5521            // inputs[2] = dynamic position scalar (U32). The builder
5522            // already validated rank / dtype / shape parity; the
5523            // exec-time check below mirrors WriteSlice for the
5524            // structural invariants the executor depends on.
5525            if node.inputs.len() != 3 {
5526                return Err(Error::Msg(format!(
5527                    "Op::WriteSliceRotating expects 3 inputs (destination, source, position), got {}",
5528                    node.inputs.len(),
5529                ))
5530                .bt());
5531            }
5532            let dest_dims = node.shape.dims().to_vec();
5533            if ranges.len() != dest_dims.len() {
5534                return Err(Error::Msg(format!(
5535                    "Op::WriteSliceRotating: ranges.len() ({}) must equal destination rank ({})",
5536                    ranges.len(),
5537                    dest_dims.len(),
5538                ))
5539                .bt());
5540            }
5541            if *axis >= dest_dims.len() {
5542                return Err(Error::Msg(format!(
5543                    "Op::WriteSliceRotating: axis {axis} out of bounds for rank {}",
5544                    dest_dims.len(),
5545                ))
5546                .bt());
5547            }
5548            if *modulus == 0 || *modulus > dest_dims[*axis] {
5549                return Err(Error::Msg(format!(
5550                    "Op::WriteSliceRotating: modulus {modulus} invalid for dest_shape[{axis}] = {}",
5551                    dest_dims[*axis],
5552                ))
5553                .bt());
5554            }
5555            OpParams::WriteSliceRotating {
5556                dest_shape: dest_dims,
5557                axis: *axis,
5558                modulus: *modulus,
5559                ranges: ranges.clone(),
5560            }
5561        }
5562        Op::WriteSliceDoff { axis, ranges } => {
5563            // inputs[0] = destination, inputs[1] = source slab,
5564            // inputs[2] = device-resident I64 offset scalar. The
5565            // builder validated rank / dtype / static-width parity; the
5566            // exec-time check below mirrors WriteSliceRotating minus the
5567            // modulus (no wrap). Bounds on the *dynamic* offset are the
5568            // caller's contract (device-only, un-checkable here).
5569            if node.inputs.len() != 3 {
5570                return Err(Error::Msg(format!(
5571                    "Op::WriteSliceDoff expects 3 inputs (destination, source, offset), got {}",
5572                    node.inputs.len(),
5573                ))
5574                .bt());
5575            }
5576            let dest_dims = node.shape.dims().to_vec();
5577            if ranges.len() != dest_dims.len() {
5578                return Err(Error::Msg(format!(
5579                    "Op::WriteSliceDoff: ranges.len() ({}) must equal destination rank ({})",
5580                    ranges.len(),
5581                    dest_dims.len(),
5582                ))
5583                .bt());
5584            }
5585            if *axis >= dest_dims.len() {
5586                return Err(Error::Msg(format!(
5587                    "Op::WriteSliceDoff: axis {axis} out of bounds for rank {}",
5588                    dest_dims.len(),
5589                ))
5590                .bt());
5591            }
5592            OpParams::WriteSliceDoff {
5593                dest_shape: dest_dims,
5594                axis: *axis,
5595                ranges: ranges.clone(),
5596            }
5597        }
5598        _ => OpParams::None,
5599    })
5600}
5601
5602/// Execute one work item. Three branches by `WorkItemKind`:
5603///
5604/// - `ConstAdopt` — verify cache has an entry pre-seeded by the
5605///   caller; record the layout from the WorkItem.
5606/// - `ViewOf { input }` — clone the input's Storage Arc into the
5607///   output slot (bytes are shared); record the strided layout
5608///   from the WorkItem.
5609/// - `Kernel` — gather input Arcs, allocate the output, run the
5610///   compiled kernel, store the result; record the contiguous
5611///   layout from the WorkItem.
5612///
5613/// Best-effort: prefix a realize-time node error with the failing node's graph
5614/// location — `Graph::describe_node` renders `Node#N (op, out shape, dtype,
5615/// inputs=[...])`, enough to grep-locate the offending op in a large graph. The
5616/// legacy per-node executors (`fuel-graph-executor`, the retired
5617/// `fuel-reference-backend`) wrapped panics this way; the PipelinedExecutor
5618/// surfaces the raw kernel error, so a dtype/shape/OOB failure deep in a model
5619/// arrived with no graph coordinate. On a graph read-lock failure the original
5620/// error passes through unchanged — the location is a navigation aid, never
5621/// worth masking the real error with a lock issue. Zero happy-path cost: only
5622/// the error branch touches the graph.
5623fn with_node_location(graph: &Arc<RwLock<Graph>>, node_id: NodeId, err: Error) -> Error {
5624    match graph.read() {
5625        Ok(g) => err.context(g.describe_node(node_id)),
5626        Err(_) => err,
5627    }
5628}
5629
5630/// Execute one [`WorkItem`] against the cache, returning the node's
5631/// [`CompletionHandle`].
5632///
5633/// Step E A4b-1: the producing arms (Kernel / WriteSlice / WriteSliceRotating /
5634/// in-place / cross-device Copy alloc) return the handle from `execute_compiled`
5635/// *without* waiting it inline — the realize loop stores it in its per-node
5636/// handle map and drains at realize-end. Non-producing arms (const adopt, view,
5637/// slot projection, release marker, contiguize) are pure Arc-clones / host
5638/// allocs whose work is already complete → [`CompletionHandle::Ready`].
5639/// Read a data-determined runtime count from bundle slot 1 of a
5640/// just-realized producer and bind it into the per-pass `SymEnv` under
5641/// `count_sym` — the data-dependent dynamic-shapes seam (increment 2a).
5642/// The producer's bundle is `[indices [capacity] U32 ; count [1] U32]`;
5643/// slot 1's single U32 starts at byte `capacity * 4` (after the
5644/// `capacity`-element U32 primary slot). CPU only for now — device
5645/// backends need a D2H after the completion handle is waited (a documented
5646/// follow-up; the whole data-dependent path is CPU-first). Called AFTER
5647/// `execute_compiled`, whose CPU path returns a `Ready` handle, so the
5648/// bytes are already valid.
5649fn bind_data_determined_count(
5650    arc: &Arc<RwLock<Storage>>,
5651    capacity: usize,
5652    count_sym: fuel_ir::SymId,
5653    produced_syms: &mut SymEnv,
5654) -> Result<()> {
5655    let guard = arc
5656        .read()
5657        .map_err(|_| poisoned("NonZeroIndices output storage"))?;
5658    let count_byte_off = capacity * std::mem::size_of::<u32>();
5659    let end = count_byte_off + std::mem::size_of::<u32>();
5660    // The non-CPU `BackendStorage` variants are cfg-gated; with GPU
5661    // features off, `Cpu` is the only variant and the fallback arm is
5662    // unreachable (a documented CPU-first limitation, not dead logic).
5663    #[allow(unreachable_patterns)]
5664    let count = match &guard.inner {
5665        fuel_memory::BackendStorage::Cpu(cpu_bytes) => {
5666            let bytes = cpu_bytes.bytes();
5667            if end > bytes.len() {
5668                return Err(Error::Msg(format!(
5669                    "NonZeroIndices: count slot byte range [{count_byte_off}..{end}) \
5670                     exceeds bundle byte length {}",
5671                    bytes.len(),
5672                ))
5673                .bt());
5674            }
5675            u32::from_le_bytes(
5676                bytes[count_byte_off..end]
5677                    .try_into()
5678                    .expect("4 bytes → u32"),
5679            )
5680        }
5681        other => {
5682            return Err(Error::Msg(format!(
5683                "NonZeroIndices: data-determined count read is CPU-only today; got \
5684                 BackendStorage::{:?} (device backends need a D2H after the completion \
5685                 handle is waited — a documented follow-up)",
5686                other.backend_id(),
5687            ))
5688            .bt());
5689        }
5690    };
5691    produced_syms.bind(count_sym, count as usize)?;
5692    Ok(())
5693}
5694
5695/// Increment 2b — the consumer half of data-dependent dynamic shapes. When
5696/// a `WriteSlice`'s offset is DATA-DETERMINED (its `SymId` is produced
5697/// mid-pass, so `op_to_op_params` deferred it into
5698/// `OpParams::WriteSlice::deferred_dyn_offset` instead of baking it at
5699/// compile), resolve it HERE from `produced_syms` — populated by the
5700/// producer's execute step (single-threaded topological order guarantees
5701/// the producer already ran). Returns a patched clone of the `CompiledNode`
5702/// with the resolved `ranges` (and `deferred_dyn_offset` cleared) for the
5703/// kernel; `None` when there is nothing to defer (the common path — no
5704/// clone). Bounds-checks the resolved range (deferred past compile).
5705fn resolve_deferred_write_slice(
5706    compiled: &CompiledNode,
5707    produced_syms: &SymEnv,
5708    node_id: NodeId,
5709) -> Result<Option<CompiledNode>> {
5710    let OpParams::WriteSlice {
5711        dest_shape,
5712        ranges,
5713        deferred_dyn_offset,
5714    } = &compiled.op_params
5715    else {
5716        return Ok(None);
5717    };
5718    let Some((axis, off)) = deferred_dyn_offset else {
5719        return Ok(None);
5720    };
5721    let base = off.resolve(produced_syms).ok_or_else(|| {
5722        Error::Msg(format!(
5723            "Op::WriteSlice {node_id:?}: data-determined offset {off:?} on axis {axis} is \
5724             unbound in produced_syms at execute (its producer did not run / bind it)",
5725        ))
5726        .bt()
5727    })?;
5728    let mut ranges = ranges.clone();
5729    let (start, end) = ranges[*axis];
5730    let width = end - start;
5731    let resolved = (base, base + width);
5732    if resolved.1 > dest_shape[*axis] {
5733        return Err(Error::Msg(format!(
5734            "Op::WriteSlice {node_id:?}: resolved data-determined range {resolved:?} on axis \
5735             {axis} exceeds destination dim = {}",
5736            dest_shape[*axis],
5737        ))
5738        .bt());
5739    }
5740    ranges[*axis] = resolved;
5741    let mut patched = compiled.clone();
5742    patched.op_params = OpParams::WriteSlice {
5743        dest_shape: dest_shape.clone(),
5744        ranges,
5745        deferred_dyn_offset: None,
5746    };
5747    Ok(Some(patched))
5748}
5749
5750/// Dynamic-M matmul: when a matmul's row count is DATA-DETERMINED
5751/// (`MatmulM::Deferred`, deferred by `op_to_op_params` because a producer
5752/// binds its `SymId` mid-pass), resolve it HERE from `produced_syms` and
5753/// run the kernel against a patched clone whose `m_compute` is
5754/// `MatmulM::Rows(count)`. Mirrors `resolve_deferred_write_slice`. `None`
5755/// when nothing is deferred (the common path — no clone). The kernel then
5756/// computes exactly `count` rows of the `m`-row capacity buffer.
5757fn resolve_deferred_matmul(
5758    compiled: &CompiledNode,
5759    produced_syms: &SymEnv,
5760    node_id: NodeId,
5761) -> Result<Option<CompiledNode>> {
5762    let OpParams::Matmul {
5763        lhs_batch_dims,
5764        rhs_batch_dims,
5765        m,
5766        n,
5767        k,
5768        m_compute,
5769    } = &compiled.op_params
5770    else {
5771        return Ok(None);
5772    };
5773    let MatmulM::Deferred(dyn_m) = m_compute else {
5774        return Ok(None);
5775    };
5776    let rows = dyn_m.resolve(produced_syms).ok_or_else(|| {
5777        Error::Msg(format!(
5778            "Op::MatMul {node_id:?}: data-determined row count {dyn_m:?} is unbound in \
5779             produced_syms at execute (its producer did not run / bind it)",
5780        ))
5781        .bt()
5782    })?;
5783    if rows > *m {
5784        return Err(Error::Msg(format!(
5785            "Op::MatMul {node_id:?}: resolved row count {rows} exceeds capacity {m}",
5786        ))
5787        .bt());
5788    }
5789    let mut patched = compiled.clone();
5790    patched.op_params = OpParams::Matmul {
5791        lhs_batch_dims: lhs_batch_dims.clone(),
5792        rhs_batch_dims: rhs_batch_dims.clone(),
5793        m: *m,
5794        n: *n,
5795        k: *k,
5796        m_compute: MatmulM::Rows(rows),
5797    };
5798    Ok(Some(patched))
5799}
5800
5801fn execute_work_item(
5802    item: &WorkItem,
5803    cache: &mut StorageCache,
5804    #[cfg_attr(
5805        not(any(feature = "cuda", feature = "vulkan")),
5806        allow(unused_variables)
5807    )]
5808    devices: &mut DeviceRegistry,
5809    layout_cache: &mut HashMap<NodeId, Layout>,
5810    produced_syms: &mut SymEnv,
5811    // Step E A4b open question #4 — "event only where waited": whether
5812    // THIS item's node id is in the realize's `WaitSet` (`will_be_waited`
5813    // in `pipelined.rs`, computed once per item by the caller). Forwarded
5814    // to every `execute_compiled_with_wait_hint` call below so a CUDA
5815    // kernel with no mid-walk reader skips its `Event` entirely.
5816    will_be_waited: bool,
5817    // CapturedRun executor build-out: persistent-output mode. `None` on
5818    // every existing realize path ⇒ byte-identical (fresh alloc, nothing
5819    // recorded). `Some(Record)` records each Kernel output's fixed Arc;
5820    // `Some(Reuse)` reuses the recorded buffer (no alloc — capture-safe)
5821    // and the write-into kernel path writes into it in place. Only the
5822    // `Kernel` arm consults it; every other arm ignores it.
5823    mut persistent: Option<&mut PersistentOutputs>,
5824) -> Result<CompletionHandle> {
5825    match &item.kind {
5826        WorkItemKind::ConstAdopt => {
5827            if !cache.contains_key(&item.node_id) {
5828                return Err(Error::Msg(format!(
5829                    "PipelinedExecutor: Const node {:?} not in input cache",
5830                    item.node_id
5831                ))
5832                .bt());
5833            }
5834            // Layout for input cache entries was seeded at realize
5835            // start; refresh from the WorkItem in case the side-table
5836            // was set after seeding.
5837            layout_cache.insert(item.node_id, item.output_layout.clone());
5838            Ok(CompletionHandle::Ready)
5839        }
5840        WorkItemKind::ViewOf { input } => {
5841            let input_arc = cache.get(input).cloned().ok_or_else(|| {
5842                Error::Msg(format!(
5843                    "PipelinedExecutor: view-op input {:?} of {:?} not realized",
5844                    input, item.node_id,
5845                ))
5846                .bt()
5847            })?;
5848            cache.insert(item.node_id, input_arc);
5849            layout_cache.insert(item.node_id, item.output_layout.clone());
5850            Ok(CompletionHandle::Ready)
5851        }
5852        WorkItemKind::SlotView { producer } => {
5853            // Op::View — multi-output projection. Same realization
5854            // shape as ViewOf: clone the producer's Storage Arc into
5855            // the View's cache slot. The WorkItem's output_layout was
5856            // computed at graph-build time by `Tensor::view`, with
5857            // the slot's byte_offset baked into start_offset (in
5858            // slot-dtype-element units). Downstream kernels reading
5859            // the producer's bytes as the slot's dtype starting at
5860            // that offset see the slot's typed window.
5861            let producer_arc = cache.get(producer).cloned().ok_or_else(|| {
5862                Error::Msg(format!(
5863                    "PipelinedExecutor: Op::View producer {:?} of {:?} not realized",
5864                    producer, item.node_id,
5865                ))
5866                .bt()
5867            })?;
5868            cache.insert(item.node_id, producer_arc);
5869            layout_cache.insert(item.node_id, item.output_layout.clone());
5870            Ok(CompletionHandle::Ready)
5871        }
5872        WorkItemKind::SlotOwn { producer, slot } => {
5873            // Op::ViewOwned — allocate a fresh Storage of the slot's
5874            // (shape, dtype) on the producer's device and copy the
5875            // slot's bytes in. Per-backend fast paths:
5876            //   - CPU:    direct &[u8]→&mut[u8] memcpy via CpuStorageBytes
5877            //   - CUDA:   D2D via CudaStorageBytes::slot_copy_to_new
5878            //             (cuMemcpyDtoDAsync with offset src pointer)
5879            //   - Vulkan: vkCmdCopyBuffer via
5880            //             VulkanBackend::slot_copy_to_new_handle
5881            //             (srcOffset/dstOffset/size)
5882            // For backends without a copy-with-offset hook we fall
5883            // back to a host round-trip (`to_host_buffer_dyn` →
5884            // slice → `storage_from_host_buffer_owned_dyn`), which
5885            // works but is wasteful.
5886            let producer_arc = cache.get(producer).cloned().ok_or_else(|| {
5887                Error::Msg(format!(
5888                    "PipelinedExecutor: Op::ViewOwned producer {:?} of {:?} not realized",
5889                    producer, item.node_id,
5890                ))
5891                .bt()
5892            })?;
5893            let new_storage = {
5894                let guard = producer_arc
5895                    .read()
5896                    .map_err(|_| poisoned("ViewOwned producer storage"))?;
5897                let bundle = guard.bundle().ok_or_else(|| {
5898                    Error::Msg(format!(
5899                        "Op::ViewOwned: producer {:?} has no bundle side-table \
5900                         — the multi-output authoring contract requires \
5901                         Storage::with_bundle / new_bundled at allocation \
5902                         time. Node {:?} slot {} cannot resolve its source.",
5903                        producer, item.node_id, slot,
5904                    ))
5905                    .bt()
5906                })?;
5907                let sv = bundle.get(*slot as usize).cloned().ok_or_else(|| {
5908                    Error::Msg(format!(
5909                        "Op::ViewOwned: slot {} out of range for producer {:?} \
5910                         (bundle has {} slots)",
5911                        slot,
5912                        producer,
5913                        bundle.len(),
5914                    ))
5915                    .bt()
5916                })?;
5917                use fuel_memory::BackendStorage;
5918                match &guard.inner {
5919                    BackendStorage::Cpu(cpu_bytes) => {
5920                        let src_bytes = cpu_bytes.bytes();
5921                        let end = sv.byte_offset + sv.len_bytes();
5922                        if end > src_bytes.len() {
5923                            return Err(Error::Msg(format!(
5924                                "Op::ViewOwned: slot {} byte range [{}..{}) \
5925                                 exceeds producer's CPU byte length {}",
5926                                slot,
5927                                sv.byte_offset,
5928                                end,
5929                                src_bytes.len(),
5930                            ))
5931                            .bt());
5932                        }
5933                        let owned = fuel_cpu_backend::CpuStorageBytes::from_bytes(
5934                            &src_bytes[sv.byte_offset..end],
5935                        );
5936                        fuel_memory::Storage::new(BackendStorage::Cpu(owned), sv.dtype)
5937                    }
5938                    #[cfg(feature = "cuda")]
5939                    BackendStorage::Cuda(cuda_bytes) => {
5940                        let dst = cuda_bytes.slot_copy_to_new(sv.byte_offset, sv.len_bytes())?;
5941                        fuel_memory::Storage::new(BackendStorage::Cuda(dst), sv.dtype)
5942                    }
5943                    #[cfg(feature = "vulkan")]
5944                    BackendStorage::Vulkan(vk_bytes) => {
5945                        let backend = vk_bytes.backend().ok_or_else(|| {
5946                            Error::Msg(format!(
5947                                "Op::ViewOwned: producer {:?} is on Vulkan but \
5948                                 its storage has no VulkanBackend handle. \
5949                                 Storages flowing through the pipelined executor \
5950                                 must be constructed via alloc_bytes_handle / \
5951                                 upload_bytes_handle so the bundle's slot extraction \
5952                                 path can reach the backend.",
5953                                producer,
5954                            ))
5955                            .bt()
5956                        })?;
5957                        let dst = backend.slot_copy_to_new_handle(
5958                            vk_bytes,
5959                            sv.byte_offset,
5960                            sv.len_bytes(),
5961                        )?;
5962                        fuel_memory::Storage::new(BackendStorage::Vulkan(dst), sv.dtype)
5963                    }
5964                    #[allow(unreachable_patterns)]
5965                    _ => {
5966                        return Err(Error::Msg(format!(
5967                            "Op::ViewOwned: producer {:?} is on a backend \
5968                             without a slot-copy-with-offset hook \
5969                             (CPU + CUDA + Vulkan wired). Add a per-backend \
5970                             `slot_copy_to_new`-equivalent and extend the \
5971                             match arm.",
5972                            producer,
5973                        ))
5974                        .bt());
5975                    }
5976                }
5977            };
5978            cache.insert(item.node_id, Arc::new(RwLock::new(new_storage)));
5979            layout_cache.insert(item.node_id, item.output_layout.clone());
5980            // A4b-1: Op::ViewOwned's slot copy (CUDA D2D) is same-stream; its
5981            // completion is carried by the realize-end full-stream sync in
5982            // `to_cpu_bytes` (unchanged) — `Ready` here is behavior-preserving.
5983            Ok(CompletionHandle::Ready)
5984        }
5985        WorkItemKind::WriteSlice { dest, source } => {
5986            let compiled = item.compiled.as_ref().ok_or_else(|| {
5987                Error::Msg(format!(
5988                    "PipelinedExecutor: WriteSlice work item {:?} has no compiled node",
5989                    item.node_id,
5990                ))
5991                .bt()
5992            })?;
5993            // Increment 2b: if the offset is DATA-DETERMINED, resolve it from
5994            // the producer-bound `produced_syms` and run the kernel against
5995            // the patched (resolved-range) node. `None` on the common path.
5996            let patched_ws = resolve_deferred_write_slice(compiled, produced_syms, item.node_id)?;
5997            let compiled = patched_ws.as_ref().unwrap_or(compiled);
5998            let dest_arc = cache.get(dest).cloned().ok_or_else(|| {
5999                Error::Msg(format!(
6000                    "PipelinedExecutor: WriteSlice destination {:?} of {:?} not realized",
6001                    dest, item.node_id,
6002                ))
6003                .bt()
6004            })?;
6005            let source_arc = cache.get(source).cloned().ok_or_else(|| {
6006                Error::Msg(format!(
6007                    "PipelinedExecutor: WriteSlice source {:?} of {:?} not realized",
6008                    source, item.node_id,
6009                ))
6010                .bt()
6011            })?;
6012            let dest_layout = layout_cache.get(dest).cloned().ok_or_else(|| {
6013                Error::Msg(format!(
6014                    "PipelinedExecutor: WriteSlice destination {:?} of {:?} has no cached layout",
6015                    dest, item.node_id,
6016                ))
6017                .bt()
6018            })?;
6019            let source_layout = layout_cache.get(source).cloned().ok_or_else(|| {
6020                Error::Msg(format!(
6021                    "PipelinedExecutor: WriteSlice source {:?} of {:?} has no cached layout",
6022                    source, item.node_id,
6023                ))
6024                .bt()
6025            })?;
6026            // v1 contract: destination must be contiguous + zero
6027            // offset. Strided dests would force the kernel to walk
6028            // both source and dest strides; defer until KV cache
6029            // exposes a non-contig dest. Source CAN be non-contig —
6030            // we auto-contiguize it here so the kernel sees a flat
6031            // slab.
6032            if !dest_layout.is_contiguous() || dest_layout.start_offset() != 0 {
6033                return Err(Error::Msg(format!(
6034                    "Op::WriteSlice (Phase E.3.2 v1): destination {:?} must be \
6035                     contiguous + zero-offset; got Layout {:?}",
6036                    dest, dest_layout,
6037                ))
6038                .bt());
6039            }
6040            let source_arc_contig = {
6041                let s_dtype = source_arc
6042                    .read()
6043                    .map_err(|_| poisoned("WriteSlice source storage"))?
6044                    .dtype;
6045                let s_len_bytes = source_arc
6046                    .read()
6047                    .map_err(|_| poisoned("WriteSlice source storage"))?
6048                    .inner
6049                    .len_bytes();
6050                let layout_bytes = source_layout.shape().elem_count() * s_dtype.size_in_bytes();
6051                let bytes_match_shape = s_len_bytes == layout_bytes;
6052                let already_contig = source_layout.is_contiguous()
6053                    && source_layout.start_offset() == 0
6054                    && bytes_match_shape;
6055                if already_contig {
6056                    source_arc
6057                } else {
6058                    auto_contiguize(&source_arc, &source_layout)?
6059                }
6060            };
6061            let source_layout_kernel = fuel_ir::Layout::contiguous(source_layout.shape().clone());
6062            // The kernel sees inputs=[source] and outputs=[dest_arc].
6063            // The dest input slot is intentionally absent — the kernel
6064            // doesn't read from dest; it only writes to its bytes
6065            // through the output slot's write lock.
6066            let input_arcs = vec![source_arc_contig];
6067            let mut output_arcs = vec![dest_arc.clone()];
6068            let kernel_layouts = vec![source_layout_kernel, dest_layout.clone()];
6069            // A4b-1: defer the wait — return the handle to the realize loop.
6070            let handle = execute_compiled_with_wait_hint(
6071                compiled,
6072                &input_arcs,
6073                &mut output_arcs,
6074                &kernel_layouts,
6075                will_be_waited,
6076            )?;
6077            // Adopt the dest Arc at this WriteSlice node's slot. The
6078            // realize loop's destructive_input cleanup evicts the
6079            // dest's own NodeId from the cache afterward — downstream
6080            // readers go through this node's NodeId.
6081            cache.insert(item.node_id, dest_arc);
6082            layout_cache.insert(item.node_id, item.output_layout.clone());
6083            Ok(handle)
6084        }
6085        WorkItemKind::WriteSliceRotating {
6086            dest,
6087            source,
6088            position,
6089        } => {
6090            // Same shape as WriteSlice but with a position input.
6091            // Kernel sees `[source, position]` as inputs; `dest` is the
6092            // pre-allocated output buffer (in-place adoption).
6093            let compiled = item.compiled.as_ref().ok_or_else(|| {
6094                Error::Msg(format!(
6095                    "PipelinedExecutor: WriteSliceRotating work item {:?} has no compiled node",
6096                    item.node_id,
6097                ))
6098                .bt()
6099            })?;
6100            let dest_arc = cache.get(dest).cloned().ok_or_else(|| {
6101                Error::Msg(format!(
6102                    "PipelinedExecutor: WriteSliceRotating destination {:?} of {:?} not realized",
6103                    dest, item.node_id,
6104                ))
6105                .bt()
6106            })?;
6107            let source_arc = cache.get(source).cloned().ok_or_else(|| {
6108                Error::Msg(format!(
6109                    "PipelinedExecutor: WriteSliceRotating source {:?} of {:?} not realized",
6110                    source, item.node_id,
6111                ))
6112                .bt()
6113            })?;
6114            let position_arc = cache.get(position).cloned().ok_or_else(|| {
6115                Error::Msg(format!(
6116                    "PipelinedExecutor: WriteSliceRotating position {:?} of {:?} not realized",
6117                    position, item.node_id,
6118                ))
6119                .bt()
6120            })?;
6121            let dest_layout = layout_cache.get(dest).cloned().ok_or_else(|| {
6122                Error::Msg(format!(
6123                    "PipelinedExecutor: WriteSliceRotating destination {:?} of {:?} has no cached layout",
6124                    dest, item.node_id,
6125                ))
6126                .bt()
6127            })?;
6128            let source_layout = layout_cache.get(source).cloned().ok_or_else(|| {
6129                Error::Msg(format!(
6130                    "PipelinedExecutor: WriteSliceRotating source {:?} of {:?} has no cached layout",
6131                    source, item.node_id,
6132                ))
6133                .bt()
6134            })?;
6135            // v1: destination contiguous + zero offset (same as WriteSlice).
6136            if !dest_layout.is_contiguous() || dest_layout.start_offset() != 0 {
6137                return Err(Error::Msg(format!(
6138                    "Op::WriteSliceRotating (v1): destination {:?} must be \
6139                     contiguous + zero-offset; got Layout {:?}",
6140                    dest, dest_layout,
6141                ))
6142                .bt());
6143            }
6144            let source_arc_contig = {
6145                let s_dtype = source_arc
6146                    .read()
6147                    .map_err(|_| poisoned("WriteSliceRotating source storage"))?
6148                    .dtype;
6149                let s_len_bytes = source_arc
6150                    .read()
6151                    .map_err(|_| poisoned("WriteSliceRotating source storage"))?
6152                    .inner
6153                    .len_bytes();
6154                let layout_bytes = source_layout.shape().elem_count() * s_dtype.size_in_bytes();
6155                let bytes_match_shape = s_len_bytes == layout_bytes;
6156                let already_contig = source_layout.is_contiguous()
6157                    && source_layout.start_offset() == 0
6158                    && bytes_match_shape;
6159                if already_contig {
6160                    source_arc
6161                } else {
6162                    auto_contiguize(&source_arc, &source_layout)?
6163                }
6164            };
6165            let source_layout_kernel = fuel_ir::Layout::contiguous(source_layout.shape().clone());
6166            let position_layout = fuel_ir::Layout::contiguous(fuel_ir::Shape::from_dims(&[]));
6167            let input_arcs = vec![source_arc_contig, position_arc];
6168            let mut output_arcs = vec![dest_arc.clone()];
6169            let kernel_layouts = vec![source_layout_kernel, position_layout, dest_layout.clone()];
6170            // A4b-1: defer the wait — return the handle to the realize loop.
6171            let handle = execute_compiled_with_wait_hint(
6172                compiled,
6173                &input_arcs,
6174                &mut output_arcs,
6175                &kernel_layouts,
6176                will_be_waited,
6177            )?;
6178            cache.insert(item.node_id, dest_arc);
6179            layout_cache.insert(item.node_id, item.output_layout.clone());
6180            Ok(handle)
6181        }
6182        WorkItemKind::WriteSliceDoff {
6183            dest,
6184            source,
6185            offset,
6186        } => {
6187            // Same shape as WriteSliceRotating: kernel sees
6188            // `[source, offset]` as inputs; `dest` is the pre-allocated
6189            // output buffer (in-place adoption). The offset (rank-0
6190            // I64) is passed through as a kernel input — the CUDA
6191            // wrapper threads its device pointer straight to the kernel
6192            // (no D2H), which is what makes a captured graph replay at
6193            // the host-updated position.
6194            let compiled = item.compiled.as_ref().ok_or_else(|| {
6195                Error::Msg(format!(
6196                    "PipelinedExecutor: WriteSliceDoff work item {:?} has no compiled node",
6197                    item.node_id,
6198                ))
6199                .bt()
6200            })?;
6201            let dest_arc = cache.get(dest).cloned().ok_or_else(|| {
6202                Error::Msg(format!(
6203                    "PipelinedExecutor: WriteSliceDoff destination {:?} of {:?} not realized",
6204                    dest, item.node_id,
6205                ))
6206                .bt()
6207            })?;
6208            let source_arc = cache.get(source).cloned().ok_or_else(|| {
6209                Error::Msg(format!(
6210                    "PipelinedExecutor: WriteSliceDoff source {:?} of {:?} not realized",
6211                    source, item.node_id,
6212                ))
6213                .bt()
6214            })?;
6215            let offset_arc = cache.get(offset).cloned().ok_or_else(|| {
6216                Error::Msg(format!(
6217                    "PipelinedExecutor: WriteSliceDoff offset {:?} of {:?} not realized",
6218                    offset, item.node_id,
6219                ))
6220                .bt()
6221            })?;
6222            let dest_layout = layout_cache.get(dest).cloned().ok_or_else(|| {
6223                Error::Msg(format!(
6224                    "PipelinedExecutor: WriteSliceDoff destination {:?} of {:?} has no cached layout",
6225                    dest, item.node_id,
6226                ))
6227                .bt()
6228            })?;
6229            let source_layout = layout_cache.get(source).cloned().ok_or_else(|| {
6230                Error::Msg(format!(
6231                    "PipelinedExecutor: WriteSliceDoff source {:?} of {:?} has no cached layout",
6232                    source, item.node_id,
6233                ))
6234                .bt()
6235            })?;
6236            // v1: destination contiguous + zero offset (same as WriteSlice).
6237            if !dest_layout.is_contiguous() || dest_layout.start_offset() != 0 {
6238                return Err(Error::Msg(format!(
6239                    "Op::WriteSliceDoff (v1): destination {:?} must be \
6240                     contiguous + zero-offset; got Layout {:?}",
6241                    dest, dest_layout,
6242                ))
6243                .bt());
6244            }
6245            let source_arc_contig = {
6246                let s_dtype = source_arc
6247                    .read()
6248                    .map_err(|_| poisoned("WriteSliceDoff source storage"))?
6249                    .dtype;
6250                let s_len_bytes = source_arc
6251                    .read()
6252                    .map_err(|_| poisoned("WriteSliceDoff source storage"))?
6253                    .inner
6254                    .len_bytes();
6255                let layout_bytes = source_layout.shape().elem_count() * s_dtype.size_in_bytes();
6256                let bytes_match_shape = s_len_bytes == layout_bytes;
6257                let already_contig = source_layout.is_contiguous()
6258                    && source_layout.start_offset() == 0
6259                    && bytes_match_shape;
6260                if already_contig {
6261                    source_arc
6262                } else {
6263                    auto_contiguize(&source_arc, &source_layout)?
6264                }
6265            };
6266            let source_layout_kernel = fuel_ir::Layout::contiguous(source_layout.shape().clone());
6267            let offset_layout = fuel_ir::Layout::contiguous(fuel_ir::Shape::from_dims(&[]));
6268            let input_arcs = vec![source_arc_contig, offset_arc];
6269            let mut output_arcs = vec![dest_arc.clone()];
6270            let kernel_layouts = vec![source_layout_kernel, offset_layout, dest_layout.clone()];
6271            // A4b-1: defer the wait — return the handle to the realize loop.
6272            let handle = execute_compiled_with_wait_hint(
6273                compiled,
6274                &input_arcs,
6275                &mut output_arcs,
6276                &kernel_layouts,
6277                will_be_waited,
6278            )?;
6279            cache.insert(item.node_id, dest_arc);
6280            layout_cache.insert(item.node_id, item.output_layout.clone());
6281            Ok(handle)
6282        }
6283        WorkItemKind::Alloc { target_location } => {
6284            // Op::Alloc { target }: allocate a fresh, zero-init storage
6285            // on target_location. No inputs, no kernel call — direct
6286            // executor dispatch. For non-CPU targets the per-backend
6287            // device handle comes from the `DeviceRegistry` the caller
6288            // handed the realize (a `*_with_devices` entry point).
6289            // Used only by the Vulkan arm below (alloc_bytes_handle); a
6290            // default-feature build sees it unused. GAP-229: 68161981's
6291            // unused_variables --fix renamed it `_n_bytes` at default
6292            // features and broke `--features vulkan` (E0425). Guard the
6293            // decline instead of the name so the binding stays usable.
6294            #[cfg_attr(not(feature = "vulkan"), allow(unused_variables))]
6295            let n_bytes = item.elem_count * item.dtype.size_in_bytes();
6296            let alloced: Storage = match target_location {
6297                // CPU has no separate uninit alloc primitive in safe
6298                // Rust (`vec![0; n]` is the canonical path). Op::Alloc
6299                // on CPU returns zero-init storage; the following
6300                // Op::ZeroFill is a redundant memset the optimizer
6301                // can elide and LLVM folds away regardless.
6302                DeviceLocation::Cpu => fuel_memory::alloc_cpu_zeroed(item.dtype, item.elem_count)?,
6303                #[cfg(feature = "cuda")]
6304                DeviceLocation::Cuda { gpu_id } => {
6305                    let cuda_dev = devices.cuda(*gpu_id).ok_or_else(|| {
6306                        Error::Msg(format!(
6307                            "Op::Alloc on Cuda {{ gpu_id: {} }}: no CUDA \
6308                             device registered for this place. Hand the device to \
6309                             the realize in a `DeviceRegistry` (a `*_with_devices` \
6310                             entry point).",
6311                            gpu_id,
6312                        ))
6313                        .bt()
6314                    })?;
6315                    // Phase 3a follow-up: true uninit alloc via
6316                    // baracuda alpha.30's unsafe alloc. The bytes are
6317                    // uninit until a subsequent Op::ZeroFill or full-
6318                    // overwrite op runs. The byte-storage Arc has no
6319                    // typed-slice accessor that would dereference
6320                    // uninit bytes.
6321                    let cuda_bytes =
6322                        fuel_cuda_backend::CudaStorageBytes::alloc_uninit(&cuda_dev, n_bytes)?;
6323                    Storage::new(fuel_memory::BackendStorage::Cuda(cuda_bytes), item.dtype)
6324                }
6325                #[cfg(not(feature = "cuda"))]
6326                DeviceLocation::Cuda { .. } => {
6327                    return Err(Error::Msg(
6328                        "Op::Alloc on Cuda but fuel-storage wasn't built \
6329                         with --features cuda"
6330                            .to_string(),
6331                    )
6332                    .bt());
6333                }
6334                #[cfg(feature = "vulkan")]
6335                DeviceLocation::Vulkan { gpu_id } => {
6336                    let backend = devices.vulkan(*gpu_id).ok_or_else(|| {
6337                        Error::Msg(format!(
6338                            "Op::Alloc on Vulkan {{ gpu_id: {} }}: no Vulkan \
6339                             device registered for this place. Hand the device to \
6340                             the realize in a `DeviceRegistry` (a `*_with_devices` \
6341                             entry point).",
6342                            gpu_id,
6343                        ))
6344                        .bt()
6345                    })?;
6346                    // Phase 3a follow-up: true uninit alloc. The old
6347                    // `upload_bytes_handle(vec![0u8; n])` host-staged
6348                    // zeros (~2× the bandwidth of a device-side fill);
6349                    // we now allocate uninit and rely on a paired
6350                    // Op::ZeroFill (vkCmdFillBuffer) for the
6351                    // initialization. Faster KV-cache init on Vulkan.
6352                    let vk_bytes = backend.alloc_bytes_handle(n_bytes)?;
6353                    Storage::new(fuel_memory::BackendStorage::Vulkan(vk_bytes), item.dtype)
6354                }
6355                #[cfg(not(feature = "vulkan"))]
6356                DeviceLocation::Vulkan { .. } => {
6357                    return Err(Error::Msg(
6358                        "Op::Alloc on Vulkan but fuel-storage wasn't built \
6359                         with --features vulkan"
6360                            .to_string(),
6361                    )
6362                    .bt());
6363                }
6364                other => {
6365                    return Err(Error::Msg(format!(
6366                        "Op::Alloc on {:?}: target not yet wired (CPU + \
6367                         CUDA + Vulkan land in Phase 3a of bridge-retirement; \
6368                         Metal extends when its byte-storage substrate is \
6369                         ready).",
6370                        other,
6371                    ))
6372                    .bt());
6373                }
6374            };
6375            cache.insert(item.node_id, Arc::new(RwLock::new(alloced)));
6376            layout_cache.insert(item.node_id, item.output_layout.clone());
6377            Ok(CompletionHandle::Ready)
6378        }
6379        WorkItemKind::Iota {
6380            len,
6381            target_location,
6382        } => {
6383            // Op::Iota { len }: 0-input F32 position generator
6384            // [0.0, 1.0, …, (len-1)]. Direct executor dispatch (no kernel /
6385            // binding-table lookup), like WorkItemKind::Alloc. Generated on the host, then, for a
6386            // CUDA target, uploaded (an Iota is a tiny index constant: a device kernel would cost a
6387            // launch to save a few hundred bytes of transfer). The decomposed PAGED_ATTN recipe
6388            // (GAP-380) is the CUDA consumer; a build without the `cuda` feature, or any other
6389            // non-CPU backend, still errors rather than guessing.
6390            #[cfg(feature = "cuda")]
6391            if item.target_backend == BackendId::Cuda {
6392                let gpu_id = match target_location {
6393                    Some(DeviceLocation::Cuda { gpu_id }) => *gpu_id,
6394                    _ => 0,
6395                };
6396                let cuda_dev = devices.cuda(gpu_id).ok_or_else(|| {
6397                    Error::Msg(format!(
6398                        "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."
6399                    ))
6400                    .bt()
6401                })?;
6402                let bytes: Vec<u8> = (0..*len).flat_map(|i| (i as f32).to_le_bytes()).collect();
6403                let cuda_bytes =
6404                    fuel_cuda_backend::CudaStorageBytes::from_cpu_bytes(&cuda_dev, &bytes)?;
6405                let st = Storage::new(fuel_memory::BackendStorage::Cuda(cuda_bytes), item.dtype);
6406                cache.insert(item.node_id, Arc::new(RwLock::new(st)));
6407                layout_cache.insert(item.node_id, item.output_layout.clone());
6408                return Ok(CompletionHandle::Ready);
6409            }
6410            #[cfg(not(feature = "cuda"))]
6411            let _ = target_location;
6412            if item.target_backend != BackendId::Cpu {
6413                return Err(Error::Msg(format!(
6414                    "WorkItemKind::Iota: only CPU is wired today, got {:?}",
6415                    item.target_backend,
6416                ))
6417                .bt());
6418            }
6419            let v: Vec<f32> = (0..*len).map(|i| i as f32).collect();
6420            let iota = fuel_memory::from_slice_cpu(&v);
6421            cache.insert(item.node_id, Arc::new(RwLock::new(iota)));
6422            layout_cache.insert(item.node_id, item.output_layout.clone());
6423            Ok(CompletionHandle::Ready)
6424        }
6425        WorkItemKind::ZeroFill => {
6426            // Op::ZeroFill: in-place zero the input's bytes. Output
6427            // adopts the input's Storage Arc (same Storage; bytes
6428            // are mutated). Direct per-backend dispatch — no kernel
6429            // call, no binding-table lookup.
6430            if item.inputs.len() != 1 {
6431                return Err(Error::Msg(format!(
6432                    "PipelinedExecutor: ZeroFill work item {:?} expects \
6433                     1 input, got {}",
6434                    item.node_id,
6435                    item.inputs.len(),
6436                ))
6437                .bt());
6438            }
6439            let src_id = item.inputs[0];
6440            let src_arc = cache.get(&src_id).cloned().ok_or_else(|| {
6441                Error::Msg(format!(
6442                    "PipelinedExecutor: ZeroFill input {:?} of {:?} \
6443                     not realized",
6444                    src_id, item.node_id,
6445                ))
6446                .bt()
6447            })?;
6448            // Per-backend in-place fill. Acquired the write lock once
6449            // for the duration of the fill — kernels on async backends
6450            // (CUDA / Vulkan) issue the memset and return; the fence
6451            // happens when downstream readers acquire the read lock
6452            // through the executor's standard synchronization path.
6453            {
6454                let mut guard = src_arc
6455                    .write()
6456                    .map_err(|_| poisoned("ZeroFill destination storage"))?;
6457                match &mut guard.inner {
6458                    fuel_memory::BackendStorage::Cpu(c) => {
6459                        let bytes = c.bytes_mut();
6460                        bytes.fill(0);
6461                    }
6462                    #[cfg(feature = "cuda")]
6463                    fuel_memory::BackendStorage::Cuda(c) => {
6464                        c.zero_async()?;
6465                    }
6466                    #[cfg(feature = "vulkan")]
6467                    fuel_memory::BackendStorage::Vulkan(v) => {
6468                        let backend = v
6469                            .backend()
6470                            .ok_or_else(|| {
6471                                Error::Msg(
6472                                    "Op::ZeroFill on Vulkan: input has no \
6473                                 attached backend handle. Storage must \
6474                                 come from VulkanBackend::alloc_bytes_handle \
6475                                 / upload_bytes_handle."
6476                                        .to_string(),
6477                                )
6478                                .bt()
6479                            })?
6480                            .clone();
6481                        backend.fill_bytes_zero(v)?;
6482                    }
6483                    #[allow(unreachable_patterns)]
6484                    other => {
6485                        return Err(Error::Msg(format!(
6486                            "Op::ZeroFill: backend not wired ({other:?}); \
6487                             CPU + CUDA + Vulkan covered, Metal extends \
6488                             when its byte-storage substrate is ready.",
6489                        ))
6490                        .bt());
6491                    }
6492                }
6493            }
6494            // Adopt the (now-zero) Storage Arc at this node's slot.
6495            // Downstream readers go through `node_id`; the original
6496            // input's NodeId is evicted from the cache by the
6497            // realize loop's destructive_input cleanup.
6498            cache.insert(item.node_id, src_arc);
6499            layout_cache.insert(item.node_id, item.output_layout.clone());
6500            // A4b-1: ZeroFill's CUDA memset is same-stream (and Op::Alloc
6501            // typically zero-inits, so this is usually elided). Its completion
6502            // is carried by the realize-end full-stream sync in `to_cpu_bytes`
6503            // (unchanged) and same-stream ordering — `Ready` is behavior-preserving.
6504            Ok(CompletionHandle::Ready)
6505        }
6506        WorkItemKind::Copy { target_location } | WorkItemKind::Move { target_location } => {
6507            // Op::Copy / Op::Move { target }: kernel lookup at
6508            // (OpKind::Copy, [dt, dt], source_backend) — the wrapper
6509            // downloads from its own residency into a freshly-
6510            // allocated output on `target_location`. We auto-
6511            // contiguize the input first so the kernel always sees
6512            // the logical view's bytes (a transpose-view source
6513            // materializes into a contiguous buffer before download).
6514            //
6515            // Move shares this entire data-movement half; its
6516            // destructive half (release the source) is driven by the
6517            // realize loop's `destructive_input` cleanup after this
6518            // arm returns — see `WorkItemKind::Move`.
6519            let op_label = if matches!(item.kind, WorkItemKind::Move { .. }) {
6520                "Move"
6521            } else {
6522                "Copy"
6523            };
6524            let compiled = item.compiled.as_ref().ok_or_else(|| {
6525                Error::Msg(format!(
6526                    "PipelinedExecutor: {op_label} work item {:?} has no compiled node",
6527                    item.node_id,
6528                ))
6529                .bt()
6530            })?;
6531            if item.inputs.len() != 1 {
6532                return Err(Error::Msg(format!(
6533                    "PipelinedExecutor: {op_label} work item {:?} expects 1 input, got {}",
6534                    item.node_id,
6535                    item.inputs.len(),
6536                ))
6537                .bt());
6538            }
6539            let src_id = item.inputs[0];
6540            let src_arc = cache.get(&src_id).cloned().ok_or_else(|| {
6541                Error::Msg(format!(
6542                    "PipelinedExecutor: {op_label} input {:?} of {:?} not realized",
6543                    src_id, item.node_id,
6544                ))
6545                .bt()
6546            })?;
6547            // Multi-output Option C guard: Op::Copy on a bundled
6548            // producer would silently drop the bundle metadata on
6549            // the destination, and the auto-contiguize step below
6550            // would treat the bundle as a flat slot-0-shaped buffer
6551            // and corrupt non-primary slots. Until the per-backend
6552            // whole-bundle-Copy hook lands, point callers at the
6553            // supported per-slot path:
6554            // Op::View → Op::Copy → Op::ViewOwned.
6555            //
6556            // Exception: when the immediate input is an Op::View
6557            // projection (its layout's byte extent is strictly less
6558            // than the bundle's total bytes), the View has already
6559            // narrowed the slab. auto-contiguize walks the View's
6560            // layout and produces a flat slot-shaped buffer that's
6561            // correctly sized — no data loss, no slot corruption.
6562            // The guard only fires when the Copy targets the bundle
6563            // root directly.
6564            {
6565                let guard = src_arc
6566                    .read()
6567                    .map_err(|_| poisoned("Copy source storage"))?;
6568                if guard.is_bundled() {
6569                    let layout_bytes_for_guard = layout_cache
6570                        .get(&src_id)
6571                        .map(|l| l.shape().elem_count() * guard.dtype.size_in_bytes())
6572                        .unwrap_or(usize::MAX);
6573                    let bundle_bytes = guard.inner.len_bytes();
6574                    let is_whole_bundle = layout_bytes_for_guard >= bundle_bytes;
6575                    if is_whole_bundle {
6576                        return Err(Error::Msg(format!(
6577                            "PipelinedExecutor: Op::{op_label} on a bundled producer \
6578                             ({:?}) is not yet supported (Option C followup). \
6579                             Use Op::View → Op::Copy → Op::ViewOwned for \
6580                             per-slot cross-device moves, or wait for the \
6581                             per-backend whole-bundle-Copy hook.",
6582                            src_id,
6583                        ))
6584                        .bt());
6585                    }
6586                }
6587            }
6588            let src_layout = layout_cache.get(&src_id).cloned().ok_or_else(|| {
6589                Error::Msg(format!(
6590                    "PipelinedExecutor: {op_label} input {:?} of {:?} has no cached layout",
6591                    src_id, item.node_id,
6592                ))
6593                .bt()
6594            })?;
6595            let src_dtype = src_arc
6596                .read()
6597                .map_err(|_| poisoned("Copy source storage"))?
6598                .dtype;
6599            let src_len_bytes = src_arc
6600                .read()
6601                .map_err(|_| poisoned("Copy source storage"))?
6602                .inner
6603                .len_bytes();
6604            let layout_bytes = src_layout.shape().elem_count() * src_dtype.size_in_bytes();
6605            let bytes_match_shape = src_len_bytes == layout_bytes;
6606            let already_contig =
6607                src_layout.is_contiguous() && src_layout.start_offset() == 0 && bytes_match_shape;
6608            let src_input = if already_contig {
6609                src_arc
6610            } else {
6611                auto_contiguize(&src_arc, &src_layout)?
6612            };
6613            let kernel_input_layout = fuel_ir::Layout::contiguous(src_layout.shape().clone());
6614            // CapturedRun build-out (4b-ζ): in Reuse (capture/replay) mode,
6615            // reuse the fixed-address buffer recorded during the warm run
6616            // instead of allocating — device allocation is illegal inside a
6617            // capture scope. Only a same-device CUDA target_location ever
6618            // reaches Reuse mode for a Copy node in practice: capture_decode's
6619            // validation loop rejects every Cpu/Vulkan target_location before
6620            // a capture scope is ever entered (Move is rejected unconditionally
6621            // there too), so this arm trusts that invariant rather than
6622            // re-deriving it — the `DeviceLocation::Cuda` guard below is just
6623            // belt-and-suspenders for any other Reuse-mode caller.
6624            let reuse_arc = match &persistent {
6625                Some(p) if p.mode == PersistentMode::Reuse => match target_location {
6626                    DeviceLocation::Cuda { .. } => p.map.get(&item.node_id).cloned(),
6627                    _ => None,
6628                },
6629                _ => None,
6630            };
6631            // Allocate the output on `target_location`. Phase 2
6632            // covered D2H (target=Cpu); Phase 3b extends to H2D
6633            // (target=Cuda / Vulkan from a CPU source). For non-CPU
6634            // targets the device handle comes from the caller's
6635            // `DeviceRegistry` (a `*_with_devices` entry point), as for
6636            // Op::Alloc.
6637            // Used only by the Vulkan arm below (alloc_bytes_handle); a
6638            // default-feature build sees it unused. GAP-229: 68161981's
6639            // unused_variables --fix renamed it `_n_bytes` at default
6640            // features and broke `--features vulkan` (E0425). Guard the
6641            // decline instead of the name so the binding stays usable.
6642            #[cfg_attr(not(feature = "vulkan"), allow(unused_variables))]
6643            let n_bytes = item.elem_count * item.dtype.size_in_bytes();
6644            let input_arcs = vec![src_input];
6645            let mut output_arcs = if let Some(arc) = reuse_arc {
6646                vec![arc]
6647            } else {
6648                let output = match target_location {
6649                    DeviceLocation::Cpu => {
6650                        fuel_memory::alloc_cpu_zeroed(item.dtype, item.elem_count)?
6651                    }
6652                    #[cfg(feature = "cuda")]
6653                    DeviceLocation::Cuda { gpu_id } => {
6654                        let cuda_dev = devices.cuda(*gpu_id).ok_or_else(|| {
6655                            Error::Msg(format!(
6656                                "Op::{op_label} on Cuda {{ gpu_id: {} }}: no CUDA \
6657                                 device registered for this place. Hand the device to \
6658                                 the realize in a `DeviceRegistry` (a `*_with_devices` \
6659                                 entry point) before an H2D Op::{op_label}.",
6660                                gpu_id,
6661                            ))
6662                            .bt()
6663                        })?;
6664                        let cuda_bytes =
6665                            fuel_cuda_backend::CudaStorageBytes::alloc_uninit(&cuda_dev, n_bytes)?;
6666                        Storage::new(fuel_memory::BackendStorage::Cuda(cuda_bytes), item.dtype)
6667                    }
6668                    #[cfg(not(feature = "cuda"))]
6669                    DeviceLocation::Cuda { .. } => {
6670                        return Err(Error::Msg(format!(
6671                            "Op::{op_label} target Cuda but fuel-storage wasn't built \
6672                             with --features cuda",
6673                        ))
6674                        .bt());
6675                    }
6676                    #[cfg(feature = "vulkan")]
6677                    DeviceLocation::Vulkan { gpu_id } => {
6678                        let backend = devices.vulkan(*gpu_id).ok_or_else(|| {
6679                            Error::Msg(format!(
6680                                "Op::{op_label} on Vulkan {{ gpu_id: {} }}: no Vulkan \
6681                                 device registered for this place. Hand the device to \
6682                                 the realize in a `DeviceRegistry` (a `*_with_devices` \
6683                                 entry point) before an H2D Op::{op_label}.",
6684                                gpu_id,
6685                            ))
6686                            .bt()
6687                        })?;
6688                        let vk_bytes = backend.alloc_bytes_handle(n_bytes)?;
6689                        Storage::new(fuel_memory::BackendStorage::Vulkan(vk_bytes), item.dtype)
6690                    }
6691                    #[cfg(not(feature = "vulkan"))]
6692                    DeviceLocation::Vulkan { .. } => {
6693                        return Err(Error::Msg(format!(
6694                            "Op::{op_label} target Vulkan but fuel-storage wasn't built \
6695                             with --features vulkan",
6696                        ))
6697                        .bt());
6698                    }
6699                    other => {
6700                        return Err(Error::Msg(format!(
6701                            "PipelinedExecutor: Op::{op_label} target_location {:?} not yet \
6702                             wired (CPU + CUDA + Vulkan covered; Metal extends when \
6703                             its byte-storage substrate is ready).",
6704                            other
6705                        ))
6706                        .bt());
6707                    }
6708                };
6709                vec![Arc::new(RwLock::new(output))]
6710            };
6711            let kernel_layouts = vec![kernel_input_layout, item.output_layout.clone()];
6712            // A4b-1: defer the wait — return the handle to the realize loop.
6713            let handle = execute_compiled_with_wait_hint(
6714                compiled,
6715                &input_arcs,
6716                &mut output_arcs,
6717                &kernel_layouts,
6718                will_be_waited,
6719            )?;
6720            let arc = output_arcs.into_iter().next().expect("one output");
6721            // CapturedRun build-out (4b-ζ): Record (warm) mode remembers this
6722            // node's fixed output buffer so the capture run reuses the
6723            // identical device address. No-op in Reuse mode (the buffer came
6724            // FROM the map) and in None mode. Mirrors the Kernel arm's
6725            // Record-mode snapshot (above) exactly.
6726            if let Some(p) = persistent.as_deref_mut()
6727                && p.mode == PersistentMode::Record
6728            {
6729                p.map.insert(item.node_id, Arc::clone(&arc));
6730            }
6731            cache.insert(item.node_id, arc);
6732            layout_cache.insert(item.node_id, item.output_layout.clone());
6733            Ok(handle)
6734        }
6735        WorkItemKind::ReleaseMarker => {
6736            // Emit a zero-byte CPU storage at the Release node's
6737            // slot. Per Op::Release's contract the marker is never
6738            // read — this exists so any downstream cache lookup of
6739            // `release_id` resolves rather than failing. The actual
6740            // deallocation of `inputs[0]` is driven by the realize
6741            // loop's `destructive_input` cleanup (Phase B).
6742            let marker = fuel_memory::alloc_cpu_zeroed(item.dtype, 0)?;
6743            cache.insert(item.node_id, Arc::new(RwLock::new(marker)));
6744            layout_cache.insert(item.node_id, item.output_layout.clone());
6745            Ok(CompletionHandle::Ready)
6746        }
6747        WorkItemKind::ContiguizeOf { input } => {
6748            let input_arc = cache.get(input).cloned().ok_or_else(|| {
6749                Error::Msg(format!(
6750                    "PipelinedExecutor: reshape input {:?} of {:?} not realized",
6751                    input, item.node_id,
6752                ))
6753                .bt()
6754            })?;
6755            let input_layout = layout_cache.get(input).cloned().ok_or_else(|| {
6756                Error::Msg(format!(
6757                    "PipelinedExecutor: reshape input {:?} of {:?} has no cached layout",
6758                    input, item.node_id,
6759                ))
6760                .bt()
6761            })?;
6762            // CapturedRun build-out (4b-γ): in Reuse (capture/replay) mode,
6763            // reuse the fixed-address buffer recorded during the warm run —
6764            // device allocation is illegal inside a capture scope. Always
6765            // write-into when reusing (skip the zero-copy-vs-allocate
6766            // branch entirely): a given ContiguizeOf node's zero-copy-ness
6767            // is a static layout/stride property, identical across the warm
6768            // and capture passes (both replay the same compiled item list
6769            // with the same static layouts per capture_decode's own
6770            // design), so if this node ever needed the map entry it
6771            // allocated on warm too and the entry is guaranteed present.
6772            let reuse_arc = match &persistent {
6773                Some(p) if p.mode == PersistentMode::Reuse => p.map.get(&item.node_id).cloned(),
6774                _ => None,
6775            };
6776            let out_arc = if let Some(dest_arc) = reuse_arc {
6777                contiguize_into(&dest_arc, &input_arc, &input_layout)?;
6778                dest_arc
6779            } else if input_layout.is_contiguous() && input_layout.start_offset() == 0 {
6780                // Zero-copy when the input is already contiguous + zero
6781                // offset — never allocates, so Record mode has nothing to
6782                // record for this node (no fixed address to reuse).
6783                input_arc
6784            } else {
6785                // Allocate + copy via the contiguize kernel.
6786                let arc = auto_contiguize(&input_arc, &input_layout)?;
6787                if let Some(p) = persistent.as_deref_mut()
6788                    && p.mode == PersistentMode::Record
6789                {
6790                    p.map.insert(item.node_id, Arc::clone(&arc));
6791                }
6792                arc
6793            };
6794            cache.insert(item.node_id, out_arc);
6795            layout_cache.insert(item.node_id, item.output_layout.clone());
6796            // A4b-1: a materializing contiguize (CUDA) is same-stream; its
6797            // completion is carried by the realize-end full-stream sync in
6798            // `to_cpu_bytes` (unchanged) — `Ready` here is behavior-preserving.
6799            Ok(CompletionHandle::Ready)
6800        }
6801        WorkItemKind::Kernel => {
6802            let compiled = item.compiled.as_ref().ok_or_else(|| {
6803                Error::Msg(format!(
6804                    "PipelinedExecutor: Kernel work item {:?} has no compiled node",
6805                    item.node_id,
6806                ))
6807                .bt()
6808            })?;
6809            // Dynamic-M matmul (sparse MoE): resolve a DATA-DETERMINED row
6810            // count from the producer-bound `produced_syms` and run against
6811            // the patched (resolved-M) node. `None` on the common path.
6812            let patched_mm = resolve_deferred_matmul(compiled, produced_syms, item.node_id)?;
6813            let compiled = patched_mm.as_ref().unwrap_or(compiled);
6814            // Gather input Arcs from the cache, auto-contiguizing
6815            // any input whose layout is non-contiguous (typically
6816            // produced by an upstream metadata-only view op).
6817            // Today's kernels assume contiguous; this pass keeps
6818            // that invariant true at every kernel call site.
6819            //
6820            // We assemble a parallel `kernel_layouts` vec — the layout
6821            // of the bytes the kernel actually receives. After
6822            // auto-contiguize, that's `Layout::contiguous(shape)` for
6823            // the input's shape; for inputs already contiguous we use
6824            // the cached layout directly. Output layout comes last.
6825            let mut input_arcs: Vec<Arc<RwLock<Storage>>> = Vec::with_capacity(item.inputs.len());
6826            let mut kernel_layouts: Vec<fuel_ir::Layout> =
6827                Vec::with_capacity(item.inputs.len() + 1);
6828            // The kernel's `strided_input` cap lets non-contiguous
6829            // inputs (broadcast, transpose, etc.) flow through without
6830            // materialization — the kernel walks strides itself. Inputs
6831            // with non-zero `start_offset` still go through auto-
6832            // Contiguize today; offset honoring on the byte buffer is
6833            // a separate concern from stride support.
6834            let kernel_handles_strided = compiled.caps.strided_input;
6835            let t_gather = crate::compiled::op_profile::PhaseTimer::start("kernel.gather_inputs");
6836            for in_id in &item.inputs {
6837                let in_arc = cache.get(in_id).cloned().ok_or_else(|| {
6838                    Error::Msg(format!(
6839                        "PipelinedExecutor: input {:?} of {:?} not realized",
6840                        in_id, item.node_id,
6841                    ))
6842                    .bt()
6843                })?;
6844                let in_layout = layout_cache.get(in_id).cloned().ok_or_else(|| {
6845                    Error::Msg(format!(
6846                        "PipelinedExecutor: input {:?} of {:?} has no cached layout",
6847                        in_id, item.node_id,
6848                    ))
6849                    .bt()
6850                })?;
6851                // "Already contig" means more than `is_contiguous()`:
6852                // the LAYOUT's element count must also match the
6853                // STORAGE's byte count for shape-validating kernels
6854                // (concat_cpu, etc.) that read `storage.len_bytes()`.
6855                // A first-N slice view has `is_contiguous() == true`
6856                // (strides match canonical [1] for shape [N]) but its
6857                // storage is the parent's full bytes — too big. In
6858                // that case we auto-contiguize to materialize only
6859                // the view's portion as a fresh storage.
6860                //
6861                // Same constraint applies to strided_ok: kernels that
6862                // declare strided support can walk strided inputs, but
6863                // the byte count check at the kernel surface still
6864                // assumes storage.len_bytes() == layout.elem_count() *
6865                // dtype.size_bytes(). Until kernels universally trust
6866                // layout over storage, we conservatively materialize.
6867                let in_dtype = in_arc.read().map_err(|_| poisoned("input storage"))?.dtype;
6868                let in_len_bytes = in_arc
6869                    .read()
6870                    .map_err(|_| poisoned("input storage"))?
6871                    .inner
6872                    .len_bytes();
6873                let layout_bytes = in_layout.shape().elem_count() * in_dtype.size_in_bytes();
6874                let bytes_match_shape = in_len_bytes == layout_bytes;
6875                let already_contig =
6876                    in_layout.is_contiguous() && in_layout.start_offset() == 0 && bytes_match_shape;
6877                let strided_ok =
6878                    kernel_handles_strided && in_layout.start_offset() == 0 && bytes_match_shape;
6879                if already_contig || strided_ok {
6880                    input_arcs.push(in_arc);
6881                    kernel_layouts.push(in_layout);
6882                } else {
6883                    let contig_arc = auto_contiguize(&in_arc, &in_layout)?;
6884                    input_arcs.push(contig_arc);
6885                    kernel_layouts.push(fuel_ir::Layout::contiguous(in_layout.shape().clone()));
6886                }
6887            }
6888            drop(t_gather);
6889            kernel_layouts.push(item.output_layout.clone());
6890
6891            // Allocate output on the target backend. For GPU backends
6892            // we derive the device handle from the first input —
6893            // every kernel has ≥1 input (Op::Const is handled via
6894            // ConstAdopt, never via Kernel), and an input on the
6895            // target backend carries its own device. This avoids
6896            // threading a device handle through `realize`.
6897            //
6898            // Multi-output (Option C, item 3): when the WorkItem
6899            // carries an `output_bundle`, size the allocation to
6900            // span every slot's bytes (primary-dtype-element count
6901            // rounded up from the bundle's total byte span) and
6902            // attach the bundle metadata after allocation.
6903            let (alloc_elem_count, bundle_to_attach) = match &item.output_bundle {
6904                Some(bundle) => {
6905                    let dtype_bytes = item.dtype.size_in_bytes().max(1);
6906                    let total_bytes = bundle.iter().fold(0usize, |acc, s| {
6907                        let end = s.byte_offset.saturating_add(s.len_bytes());
6908                        acc.max(end)
6909                    });
6910                    let elems = total_bytes.div_ceil(dtype_bytes);
6911                    (elems, Some(Arc::clone(bundle)))
6912                }
6913                None => (item.elem_count, None),
6914            };
6915            // CapturedRun build-out: in Reuse (capture/replay) mode, reuse the
6916            // FIXED-ADDRESS buffer recorded during the warm run instead of
6917            // allocating — device allocation is illegal inside a capture scope,
6918            // and reusing the same address is what makes the captured graph's
6919            // baked kernel arguments valid on replay. In Record (warm) or None
6920            // mode, allocate as usual (below).
6921            let reuse_arc = match &persistent {
6922                Some(p) if p.mode == PersistentMode::Reuse => {
6923                    Some(p.map.get(&item.node_id).cloned().ok_or_else(|| {
6924                        Error::Msg(format!(
6925                            "PipelinedExecutor: capture (reuse) mode has no persistent \
6926                             output buffer for kernel node {:?}; the warm (record) run \
6927                             must realize every kernel node before capture",
6928                            item.node_id,
6929                        ))
6930                        .bt()
6931                    })?)
6932                }
6933                _ => None,
6934            };
6935            let t_alloc = crate::compiled::op_profile::PhaseTimer::start("kernel.alloc_output");
6936            let mut output_arcs = if let Some(arc) = reuse_arc {
6937                vec![arc]
6938            } else {
6939                let output = match item.target_backend {
6940                    BackendId::Cpu => fuel_memory::alloc_cpu_zeroed(item.dtype, alloc_elem_count)?,
6941                    #[cfg(feature = "cuda")]
6942                    BackendId::Cuda => {
6943                        let first_in = input_arcs.first().ok_or_else(|| {
6944                            Error::Msg(format!(
6945                                "PipelinedExecutor: kernel {:?} on Cuda has no inputs; \
6946                             cannot derive device for output allocation",
6947                                item.node_id,
6948                            ))
6949                            .bt()
6950                        })?;
6951                        let guard = first_in.read().map_err(|_| poisoned("input storage"))?;
6952                        let cuda_in = match &guard.inner {
6953                            fuel_memory::BackendStorage::Cuda(c) => c,
6954                            other => {
6955                                return Err(Error::Msg(format!(
6956                                    "PipelinedExecutor: kernel {:?} target_backend=Cuda but \
6957                                 input has BackendStorage::{:?}; mixed-backend kernels \
6958                                 require an explicit Op::Copy first",
6959                                    item.node_id,
6960                                    other.backend_id(),
6961                                ))
6962                                .bt());
6963                            }
6964                        };
6965                        let n_bytes = alloc_elem_count * item.dtype.size_in_bytes();
6966                        let cuda_bytes =
6967                            fuel_cuda_backend::CudaStorageBytes::alloc(cuda_in.device(), n_bytes)?;
6968                        fuel_memory::Storage::new(
6969                            fuel_memory::BackendStorage::Cuda(cuda_bytes),
6970                            item.dtype,
6971                        )
6972                    }
6973                    #[cfg(feature = "vulkan")]
6974                    BackendId::Vulkan => {
6975                        // Mirror the CUDA path: derive the backend handle
6976                        // from the first input's `VulkanStorageBytes::backend()`.
6977                        // Vulkan catch-up V.1.B (2026-05-21) — requires
6978                        // inputs constructed via `alloc_bytes_handle` /
6979                        // `upload_bytes_handle` so they carry the
6980                        // `Arc<VulkanBackend>` (mirroring CUDA's
6981                        // `Arc<CudaDevice>`).
6982                        let first_in = input_arcs.first().ok_or_else(|| {
6983                            Error::Msg(format!(
6984                                "PipelinedExecutor: kernel {:?} on Vulkan has no inputs; \
6985                             cannot derive backend handle for output allocation",
6986                                item.node_id,
6987                            ))
6988                            .bt()
6989                        })?;
6990                        let guard = first_in.read().map_err(|_| poisoned("input storage"))?;
6991                        let vk_in = match &guard.inner {
6992                            fuel_memory::BackendStorage::Vulkan(v) => v,
6993                            other => {
6994                                return Err(Error::Msg(format!(
6995                                    "PipelinedExecutor: kernel {:?} target_backend=Vulkan but \
6996                                 input has BackendStorage::{:?}; mixed-backend kernels \
6997                                 require an explicit Op::Copy first",
6998                                    item.node_id,
6999                                    other.backend_id(),
7000                                ))
7001                                .bt());
7002                            }
7003                        };
7004                        let backend = vk_in.backend().ok_or_else(|| {
7005                            Error::Msg(format!(
7006                                "PipelinedExecutor: Vulkan kernel {:?} input has no backend \
7007                             handle. Storages flowing through the pipelined executor's \
7008                             Vulkan path must be constructed via \
7009                             VulkanBackend::alloc_bytes_handle / upload_bytes_handle \
7010                             (not the legacy alloc_bytes / upload_bytes which leave \
7011                             VulkanStorageBytes::backend = None).",
7012                                item.node_id,
7013                            ))
7014                            .bt()
7015                        })?;
7016                        let n_bytes = alloc_elem_count * item.dtype.size_in_bytes();
7017                        let vk_bytes = backend.alloc_bytes_handle(n_bytes)?;
7018                        fuel_memory::Storage::new(
7019                            fuel_memory::BackendStorage::Vulkan(vk_bytes),
7020                            item.dtype,
7021                        )
7022                    }
7023                    other => {
7024                        return Err(Error::Msg(format!(
7025                            "PipelinedExecutor: target_backend {:?} output allocation \
7026                         not yet implemented (CPU + CUDA + Vulkan wired; Metal extends later)",
7027                            other
7028                        ))
7029                        .bt());
7030                    }
7031                };
7032                // Attach bundle metadata when this is a multi-output op.
7033                // The kernel sees the allocated bytes; the bundle lives
7034                // at the Storage wrapper level so downstream Op::View /
7035                // Op::ViewOwned can resolve their slot windows.
7036                let output = match bundle_to_attach {
7037                    Some(bundle) => output.with_bundle(bundle)?,
7038                    None => output,
7039                };
7040                vec![Arc::new(RwLock::new(output))]
7041            };
7042            drop(t_alloc);
7043
7044            // A4b-1: defer the wait — return the handle to the realize loop.
7045            let t_launch =
7046                crate::compiled::op_profile::PhaseTimer::start("kernel.execute_compiled");
7047            let handle = execute_compiled_with_wait_hint(
7048                compiled,
7049                &input_arcs,
7050                &mut output_arcs,
7051                &kernel_layouts,
7052                will_be_waited,
7053            )?;
7054            drop(t_launch);
7055
7056            let arc = output_arcs.into_iter().next().expect("one output");
7057
7058            // CapturedRun build-out: Record (warm) mode remembers this node's
7059            // fixed output buffer so the capture run reuses the identical
7060            // device address. No-op in Reuse mode (the buffer came FROM the
7061            // map) and in None mode.
7062            if let Some(p) = persistent
7063                && p.mode == PersistentMode::Record
7064            {
7065                p.map.insert(item.node_id, Arc::clone(&arc));
7066            }
7067
7068            // Data-determined dynamic-shapes seam (increment 2a): a
7069            // producer that computes a runtime count publishes it into the
7070            // per-pass `SymEnv` so downstream ops can consume it as a
7071            // dynamic extent. `Op::NonZeroIndices` writes its count into
7072            // bundle slot 1; read it back and bind `count_sym`. This is the
7073            // FIRST op to bind a *data-determined* symbol mid-realize (all
7074            // prior binds are host-known before realize). Single-threaded:
7075            // the executor runs items topologically, so this bind precedes
7076            // any consumer's execute-time resolution.
7077            if let OpParams::NonZeroIndices {
7078                capacity,
7079                count_sym,
7080            } = &compiled.op_params
7081            {
7082                bind_data_determined_count(&arc, *capacity, *count_sym, produced_syms)?;
7083            }
7084
7085            cache.insert(item.node_id, arc);
7086            layout_cache.insert(item.node_id, item.output_layout.clone());
7087            Ok(handle)
7088        }
7089        WorkItemKind::InplaceKernel { target_idx } => {
7090            let compiled = item.compiled.as_ref().ok_or_else(|| {
7091                Error::Msg(format!(
7092                    "PipelinedExecutor: InplaceKernel work item {:?} has no compiled node",
7093                    item.node_id,
7094                ))
7095                .bt()
7096            })?;
7097            let target_id = *item.inputs.get(*target_idx).ok_or_else(|| {
7098                Error::Msg(format!(
7099                    "PipelinedExecutor: InplaceKernel work item {:?} target_idx={} \
7100                     out of bounds (inputs.len()={})",
7101                    item.node_id,
7102                    target_idx,
7103                    item.inputs.len(),
7104                ))
7105                .bt()
7106            })?;
7107            let target_arc = cache.get(&target_id).cloned().ok_or_else(|| {
7108                Error::Msg(format!(
7109                    "PipelinedExecutor: InplaceKernel target {:?} of {:?} not realized",
7110                    target_id, item.node_id,
7111                ))
7112                .bt()
7113            })?;
7114            let target_layout = layout_cache.get(&target_id).cloned().ok_or_else(|| {
7115                Error::Msg(format!(
7116                    "PipelinedExecutor: InplaceKernel target {:?} of {:?} has no cached layout",
7117                    target_id, item.node_id,
7118                ))
7119                .bt()
7120            })?;
7121            // v1 contract: target must be contiguous + zero offset.
7122            // Strided in-place targets would force the kernel to walk
7123            // strides for writes too; defer until a concrete consumer
7124            // needs it (mirrors `Op::WriteSlice`'s v1 dest contract).
7125            if !target_layout.is_contiguous() || target_layout.start_offset() != 0 {
7126                return Err(Error::Msg(format!(
7127                    "InplaceKernel (Phase 3 v1): target {:?} must be contiguous + \
7128                     zero-offset; got Layout {:?}",
7129                    target_id, target_layout,
7130                ))
7131                .bt());
7132            }
7133            // Kernel sees inputs=[non-target IR inputs in order] and
7134            // outputs=[target_arc]. For unary in-place (1 IR input at
7135            // target_idx=0) the input vec is empty, matching the
7136            // original Phase 3e contract. For binary in-place
7137            // (target_idx=0, 2 IR inputs) the wrapper sees the
7138            // non-destructive RHS as `inputs[0]`. The wrapper acquires
7139            // outputs[0]'s write lock and mutates through its
7140            // bytes_mut(). Layout vector contains the kernel's
7141            // inputs+outputs layouts in that order.
7142            let mut input_arcs: Vec<Arc<RwLock<Storage>>> = Vec::new();
7143            let mut kernel_layouts: Vec<Layout> = Vec::new();
7144            for (i, &input_id) in item.inputs.iter().enumerate() {
7145                if i == *target_idx {
7146                    continue;
7147                }
7148                let arc = cache.get(&input_id).cloned().ok_or_else(|| {
7149                    Error::Msg(format!(
7150                        "PipelinedExecutor: InplaceKernel non-target input {:?} of {:?} \
7151                         not realized",
7152                        input_id, item.node_id,
7153                    ))
7154                    .bt()
7155                })?;
7156                let lay = layout_cache.get(&input_id).cloned().ok_or_else(|| {
7157                    Error::Msg(format!(
7158                        "PipelinedExecutor: InplaceKernel non-target input {:?} of {:?} \
7159                         has no cached layout",
7160                        input_id, item.node_id,
7161                    ))
7162                    .bt()
7163                })?;
7164                input_arcs.push(arc);
7165                kernel_layouts.push(lay);
7166            }
7167            let mut output_arcs = vec![target_arc.clone()];
7168            kernel_layouts.push(target_layout.clone());
7169            // A4b-1: defer the wait — return the handle to the realize loop.
7170            let handle = execute_compiled_with_wait_hint(
7171                compiled,
7172                &input_arcs,
7173                &mut output_arcs,
7174                &kernel_layouts,
7175                will_be_waited,
7176            )?;
7177            // Adopt the target Arc at this node's slot. The realize
7178            // loop's destructive_input cleanup evicts the target's own
7179            // NodeId from the cache afterward.
7180            cache.insert(item.node_id, target_arc);
7181            layout_cache.insert(item.node_id, item.output_layout.clone());
7182            Ok(handle)
7183        }
7184    }
7185}
7186
7187fn poisoned(what: &'static str) -> Error {
7188    Error::Msg(format!("PipelinedExecutor: {} poisoned", what)).bt()
7189}
7190
7191/// Step E A4b-1: record a node's [`CompletionHandle`] in the executor's
7192/// per-node handle map.
7193///
7194/// `Ready` handles (CPU / Vulkan / view-and-alloc arms) carry no async work, so
7195/// we DON'T store them — keeping the map to genuinely-pending entries makes the
7196/// realize-end empty-after-drain assert (open question #6) meaningful and keeps
7197/// the drain O(pending) rather than O(nodes). A re-used NodeId (in-place adopt
7198/// re-keys an existing slot) waits the prior handle first so nothing leaks.
7199#[inline]
7200fn store_handle(
7201    handles: &mut HashMap<NodeId, CompletionHandle>,
7202    node_id: NodeId,
7203    handle: CompletionHandle,
7204) {
7205    if matches!(handle, CompletionHandle::Ready) {
7206        // A prior pending handle at this slot must still be waited (don't drop a
7207        // Pending silently). In practice NodeIds are unique per realize, so this
7208        // is just defensive.
7209        if let Some(prev) = handles.remove(&node_id) {
7210            let _ = prev.wait();
7211        }
7212        return;
7213    }
7214    if let Some(prev) = handles.insert(node_id, handle) {
7215        let _ = prev.wait();
7216    }
7217}
7218
7219/// Step E A4b-3: the FINER cross-device producer wait.
7220///
7221/// Before dispatching a cross-device `Op::Copy` / `Op::Move` WorkItem, the
7222/// executor calls this on the copy's single source input. It removes the
7223/// source producer's [`CompletionHandle`] from the map and waits it — so the
7224/// specific producer P is complete before the D2H reads P's device buffer,
7225/// WITHOUT draining the whole source device (the conservative pre-A4b-3
7226/// behavior, where `to_cpu_bytes`'s `device.synchronize()` blocked on ALL
7227/// in-flight work on that device — including the OTHER sub-DAG's independent
7228/// work A4b-4 wants to overlap).
7229///
7230/// - **CUDA producer** → waits P's recorded `Event` (`cuEventSynchronize`):
7231///   fires after P + its already-ordered stream predecessors, nothing else.
7232/// - **Absent / `Ready` producer** (CPU producer, or a Vulkan producer — which
7233///   under A4b-2 is `Ready` mid-walk because nothing is submitted until
7234///   realize-end) → no-op. A Vulkan SOURCE's own ordering is handled inside
7235///   `download_bytes` (it `force_flush`es the open batch then reads), so there
7236///   is no mid-walk Vulkan handle to wait here; the cross-device Vulkan→CPU hop
7237///   stays correct without one.
7238///
7239/// Removing the handle here (rather than waiting it again at realize-end) keeps
7240/// `drain_handles`' post-drain empty-map assert meaningful and avoids a
7241/// double-wait. Waiting it twice would be harmless (`cuEventSynchronize` on an
7242/// already-signalled event is a fast no-op), but the consume-once contract is
7243/// cleaner. The producing node's *storage* stays in the cache for downstream
7244/// readers; only its completion handle is consumed.
7245fn wait_producer_handle(
7246    handles: &mut HashMap<NodeId, CompletionHandle>,
7247    producer: NodeId,
7248) -> Result<()> {
7249    if let Some(handle) = handles.remove(&producer) {
7250        handle.wait()?;
7251    }
7252    Ok(())
7253}
7254
7255/// Step E A4b-1: realize-end drain — wait every outstanding async handle, then
7256/// clear the map.
7257///
7258/// **Event-recording / wait strategy (A4b-1 §1.2).** CUDA has one stream per
7259/// device, and an `Event` recorded after a node's launch signals when that
7260/// node *and all prior stream work* have completed. So once the
7261/// latest-recorded event on a device has signalled, every earlier event on that
7262/// device is already signalled too: waiting them is a non-blocking
7263/// `cuEventQuery` fast-path, not N host stalls. We therefore wait every stored
7264/// handle (correct + simple).
7265///
7266/// **Open question #4 — "event only where waited" — RESOLVED.** Recording an
7267/// `Event` for every node was measured negligible on a 32-op synthetic, but
7268/// real decode graphs run 150-200+ ops; `pipelined`'s `WaitSet` pre-scan (see
7269/// `compiler_work_and_wait_set_for` / `build_wait_set`) now restricts event
7270/// production to the nodes some later cross-device `Copy`/`Move` will
7271/// individually wait — same-device-only ("elided") nodes get
7272/// `CompletionHandle::Ready` with no `cuEventCreate`/`cuEventRecord` at all
7273/// (`execute_compiled_with_wait_hint`). This drain therefore now retires only
7274/// the (typically few) wait-set handles that were never consumed mid-walk by
7275/// `wait_producer_handle`; it is no longer sufficient on its own to guarantee
7276/// every enqueued CUDA kernel has completed — `sync_active_cuda_devices` below
7277/// covers the elided remainder. We keep a per-node handle (rather than a
7278/// single per-device event) for the wait-set members because A4b-3's finer
7279/// cross-device wait needs to wait a *specific producer's* completion — the
7280/// per-node handle is that seam.
7281fn drain_handles(handles: &mut HashMap<NodeId, CompletionHandle>) -> Result<()> {
7282    for (_node, handle) in handles.drain() {
7283        handle.wait()?;
7284    }
7285    // Open question #6: once handles are stored instead of `wait`ed inline, the
7286    // `#[must_use]` on `CompletionHandle` can't catch a leaked (never-waited)
7287    // handle at the call site. The drain consumes the whole map, so it is empty
7288    // here by construction; assert it to catch a future leak (e.g. a new
7289    // dispatch path that forgets to thread its handle through `store_handle`).
7290    debug_assert!(
7291        handles.is_empty(),
7292        "A4b-1: handle map must be empty after drain"
7293    );
7294    Ok(())
7295}
7296
7297/// Step E A4b open question #4 step 3 — the realize-end complement to the
7298/// "event only where waited" elision. Because most CUDA nodes in a long
7299/// single-device chain no longer record an `Event` (see `drain_handles`'s
7300/// doc), this does ONE blanket `cuStreamSynchronize` per CUDA device that
7301/// still holds LIVE storage in `cache` — the realize target(s) plus any
7302/// surviving intermediates — instead of relying on per-node handles to cover
7303/// them.
7304///
7305/// **Why this is safe + sufficient.** CUDA has one stream per device, and
7306/// this executor dispatches strictly sequentially (one work item at a time,
7307/// in topological order) — so by the time a live node's own kernel was
7308/// launched, every same-device ancestor it depends on was ALREADY enqueued
7309/// earlier on the SAME stream. Stream ordering (not a host wait) guarantees
7310/// those ancestors run to completion no later than the live node's own
7311/// kernel. Syncing the live node's device therefore flushes its entire
7312/// same-device dependency chain, elided or not. Cross-device ancestors are
7313/// unaffected by elision — they always went through an `Op::Copy`/`Move`,
7314/// whose producer is in the `WaitSet` and was already waited explicitly at
7315/// the cross-device boundary (`wait_producer_handle`), mid-walk.
7316///
7317/// **Why evicted (non-live) intermediates don't need this.** A node whose
7318/// storage was evicted before realize-end (the `destructive_input` cleanup)
7319/// is never read by anything this realize returns; A3's stream-ordered
7320/// alloc/free already makes its eventual completion safe without a host
7321/// wait (the driver serializes the free after the freeing stream position,
7322/// same as any other stream-ordered op) — nothing to synchronize for.
7323///
7324/// No-op when `cache` holds no CUDA storage (CPU/Vulkan-only realize).
7325#[cfg(feature = "cuda")]
7326fn sync_active_cuda_devices(cache: &StorageCache) -> Result<()> {
7327    let mut devices: HashMap<fuel_ir::DeviceLocation, fuel_cuda_backend::CudaDevice> =
7328        HashMap::new();
7329    for arc in cache.values() {
7330        let guard = arc
7331            .read()
7332            .map_err(|_| poisoned("cache storage (cuda realize-end sync scan)"))?;
7333        if let fuel_memory::BackendStorage::Cuda(c) = &guard.inner {
7334            devices
7335                .entry(c.device().location())
7336                .or_insert_with(|| c.device().clone());
7337        }
7338    }
7339    for dev in devices.values() {
7340        dev.synchronize()?;
7341    }
7342    Ok(())
7343}
7344
7345/// Non-CUDA builds never produce CUDA storage, so there is nothing to sync —
7346/// keeps the call site unconditional across both feature configurations.
7347#[cfg(not(feature = "cuda"))]
7348fn sync_active_cuda_devices(_cache: &StorageCache) -> Result<()> {
7349    Ok(())
7350}
7351
7352/// Step E A4b-2: a Vulkan [`Completion`](crate::compiled::Completion) over an
7353/// in-flight (submitted, not-yet-waited) batch. `wait` blocks on the batch's
7354/// fence (`vkWaitForFences`) — which fires when the whole submitted command
7355/// buffer has retired on the single compute queue — then releases the batch
7356/// (frees the CB / descriptor sets / transient buffers / retired pool, all now
7357/// idle on the GPU).
7358///
7359/// The fence is per-BATCH, not per-node: one `submit_pending` flushes every op
7360/// recorded since the last submit, so this single handle covers a contiguous run
7361/// of Vulkan nodes (the A2 batching win, preserved — fewer fences, larger
7362/// submissions). `backend` keeps the [`VulkanBackend`] alive so the
7363/// post-fence pool retire + the `DeviceInner` the batch's resources reference
7364/// outlive the wait.
7365///
7366/// `Send` (required by `Completion`): every owned field is `Send` — `Fence` /
7367/// `CommandBuffer` / `DescriptorSet` / `Buffer` / `Allocation` / `CommandPool`
7368/// are all `Send` in vulkane (Arc-of-`DeviceInner` + explicit `unsafe impl`s),
7369/// and `Arc<VulkanBackend>` is `Send + Sync`.
7370/// Step E B1: `batch` is an `Option` ONLY so [`Drop`] can coexist with the
7371/// by-value `into_wait` consume. A type with a `Drop` impl cannot be
7372/// destructured by move (`let VulkanCompletion { backend, batch } = self`,
7373/// E0509), so `into_wait` `take()`s the batch out of the `Option` instead of
7374/// moving it out of the struct, then lets the normal `Drop` run. In every
7375/// reachable state the batch is `Some` until exactly one `into_wait` consumes it.
7376#[cfg(feature = "vulkan")]
7377struct VulkanCompletion {
7378    backend: Arc<fuel_vulkan_backend::VulkanBackend>,
7379    batch: Option<fuel_vulkan_backend::SubmittedBatch>,
7380    /// The device this submitted batch counts against in the in-flight counter
7381    /// (Step E B1). `Drop` decrements this slot.
7382    loc: fuel_ir::DeviceLocation,
7383}
7384
7385/// Step E A4b-4: the element type of the executor's in-flight-Vulkan-batch list.
7386/// A [`VulkanCompletion`] on a Vulkan build; a zero-sized placeholder otherwise
7387/// so the realize loops carry one `Vec<InflightVulkan>` local without `cfg` on
7388/// every use site (the helpers `eager_submit_all_vulkan` / `drain_inflight_vulkan`
7389/// are the only code that ever pushes/drains it, and they are `cfg`-gated).
7390#[cfg(feature = "vulkan")]
7391type InflightVulkan = VulkanCompletion;
7392#[cfg(not(feature = "vulkan"))]
7393type InflightVulkan = ();
7394
7395/// Step E A4b-4: is the cross-device copy's SOURCE buffer Vulkan-resident?
7396///
7397/// Used at the cross-device `Op::Copy`/`Op::Move` boundary to decide whether the
7398/// executor must wait the in-flight Vulkan batches before the copy. A Vulkan→CPU
7399/// D2H reads the source on the host, and the Vulkan `download` path only
7400/// `force_flush`es the OPEN batch (never the executor's eagerly-submitted
7401/// in-flight ones), so for a VULKAN source we must `drain_inflight_vulkan` first
7402/// to read completed data. For a CUDA / CPU source we must NOT wait Vulkan — the
7403/// copy doesn't read any Vulkan buffer, and waiting Vulkan there would needlessly
7404/// serialize the independent Vulkan sub-DAG (killing the overlap A4b-4 exists to
7405/// win). Returns `false` when the producer's storage isn't in the cache (treated
7406/// as not-Vulkan → no Vulkan wait; the CUDA/CPU producer handle still covers it).
7407#[cfg(feature = "vulkan")]
7408fn copy_source_is_vulkan(cache: &StorageCache, producer: NodeId) -> Result<bool> {
7409    if let Some(arc) = cache.get(&producer) {
7410        let guard = arc
7411            .read()
7412            .map_err(|_| poisoned("storage lock probing copy-source backend"))?;
7413        return Ok(matches!(
7414            guard.inner,
7415            fuel_memory::BackendStorage::Vulkan(_)
7416        ));
7417    }
7418    Ok(false)
7419}
7420
7421#[cfg(not(feature = "vulkan"))]
7422#[inline]
7423fn copy_source_is_vulkan(_cache: &StorageCache, _producer: NodeId) -> Result<bool> {
7424    Ok(false)
7425}
7426
7427#[cfg(feature = "vulkan")]
7428impl crate::compiled::Completion for VulkanCompletion {
7429    fn wait(self: Box<Self>) -> Result<()> {
7430        // Move the whole `VulkanCompletion` out of the `Box` (allowed even with a
7431        // `Drop` impl — it's a full move, not a destructure) and consume by value.
7432        (*self).into_wait()
7433    }
7434}
7435
7436#[cfg(feature = "vulkan")]
7437impl VulkanCompletion {
7438    /// Build the handle for an eagerly-submitted Vulkan batch and register it as
7439    /// one in-flight batch on `loc` (Step E B1). The matching decrement is in
7440    /// [`Drop`]. `loc` is the backend's `DeviceLocation::Vulkan { gpu_id }`.
7441    fn new(
7442        backend: Arc<fuel_vulkan_backend::VulkanBackend>,
7443        batch: fuel_vulkan_backend::SubmittedBatch,
7444        loc: fuel_ir::DeviceLocation,
7445    ) -> Self {
7446        crate::dispatch::inflight_inc(loc);
7447        Self {
7448            backend,
7449            batch: Some(batch),
7450            loc,
7451        }
7452    }
7453
7454    /// Block on this batch's fence, retire pools, then free the batch. Consumes
7455    /// `self` by value (the by-value sibling of the boxed `Completion::wait`),
7456    /// used by the executor's `inflight_vulkan` drain (A4b-4) where we hold the
7457    /// `VulkanCompletion` unboxed in a `Vec`.
7458    ///
7459    /// Step E B1: `take()`s the batch out of the `Option` (NOT a destructure
7460    /// move — that's illegal with a `Drop` impl) and waits it; the in-flight
7461    /// decrement then rides `self`'s `Drop` as this returns. So a wait-consume
7462    /// and a bare drop (e.g. an error unwinding before the wait) BOTH decrement
7463    /// exactly once, and `into_wait` never double-counts.
7464    fn into_wait(mut self) -> Result<()> {
7465        // `wait_submitted` consumes the batch by value: waits the fence, retires
7466        // pools, then drops the batch (UAF-safe — nothing the in-flight CB
7467        // references frees before the fence signals). After a `new` the batch is
7468        // always `Some`; `take` leaves `None` so `Drop` doesn't touch it again.
7469        if let Some(batch) = self.batch.take() {
7470            self.backend.wait_submitted(batch)?;
7471        }
7472        Ok(())
7473        // `self` drops here → `inflight_dec(self.loc)`.
7474    }
7475
7476    /// Step E A2.1 (deferred-deletion): retain an evicted DATA buffer until THIS
7477    /// in-flight batch's fence signals, then free it post-fence (on the batch's
7478    /// `Drop` — guaranteed post-fence by follow-on #2). Delegates to
7479    /// [`fuel_vulkan_backend::SubmittedBatch::retain_buffer`].
7480    ///
7481    /// The executor calls this for every in-flight batch when it evicts a Vulkan
7482    /// buffer those batches' CBs may read, INSTEAD of host-blocking on a drain.
7483    /// `batch` is `Some` in every reachable mid-walk state (it is `take`n only by
7484    /// `into_wait`/`wait`, which consume the whole `VulkanCompletion`), so the
7485    /// retain always lands on a live in-flight batch.
7486    fn retain_data(&mut self, buf: std::sync::Arc<fuel_vulkan_backend::VulkanBuffer>) {
7487        if let Some(batch) = self.batch.as_mut() {
7488            batch.retain_buffer(buf);
7489        }
7490    }
7491}
7492
7493#[cfg(feature = "vulkan")]
7494impl Drop for VulkanCompletion {
7495    fn drop(&mut self) {
7496        // The single in-flight decrement for a Vulkan batch — fires whether the
7497        // batch was waited (`into_wait` / `wait`) or merely dropped (error
7498        // unwind), so the per-device count returns to baseline. Relaxed +
7499        // saturating (a scheduling hint, never a correctness gate).
7500        crate::dispatch::inflight_dec(self.loc);
7501    }
7502}
7503
7504/// Step E A4b-4 — eager Vulkan submission during the walk (the OVERLAP enabler).
7505///
7506/// Submits each DISTINCT Vulkan backend's currently-open batch WITHOUT waiting,
7507/// pushing the resulting in-flight [`VulkanCompletion`]s onto `inflight` so the
7508/// executor waits them later (at the in-flight-lifetime guard / realize-end). An
7509/// empty open batch yields `None` and is skipped (idempotent).
7510///
7511/// This is what makes a Vulkan sub-DAG actually START on the iGPU while the
7512/// executor records/dispatches the next (CUDA) chunk — without it the Vulkan
7513/// batch sits merely *recorded* until realize-end and never overlaps the CUDA
7514/// stream (design §5). Called ONLY on a genuinely multi-backend realize (gated by
7515/// the executor's `multi_backend` flag); on a single-device graph it is never
7516/// reached, so pure-Vulkan stays byte-identical to A4b-2 (one realize-end submit).
7517///
7518/// **Whole-chunk granularity (UAF/race-safety, design §4 + the Vulkan
7519/// single-queue OOO-completion semantics).** We submit only at chunk boundaries
7520/// and before a cross-device wait — never mid-chunk — so the batch handed to the
7521/// GPU is a COMPLETE contiguous run of Vulkan nodes with all its intra-CB
7522/// dependency barriers (`recorder.rs` `vkCmdPipelineBarrier`) already in place.
7523/// Vulkan only guarantees that batches on one queue BEGIN in submission order;
7524/// they may overlap / complete out of order, so a split mid-chunk would lose the
7525/// write-before-read ordering for ops that read an earlier op's buffer in the
7526/// SAME chunk. By submitting whole chunks and re-syncing (`drain_inflight_vulkan`)
7527/// before any later Vulkan op records, before any cross-device copy, and before
7528/// any Vulkan-referenced eviction, no in-flight batch is ever read or freed while
7529/// still running.
7530#[cfg(feature = "vulkan")]
7531fn eager_submit_all_vulkan(
7532    cache: &StorageCache,
7533    inflight: &mut Vec<VulkanCompletion>,
7534) -> Result<()> {
7535    // Collect distinct Vulkan backends referenced by the cache (dedup by gpu_id).
7536    let mut seen: Vec<usize> = Vec::new();
7537    let mut backends: Vec<Arc<fuel_vulkan_backend::VulkanBackend>> = Vec::new();
7538    for arc in cache.values() {
7539        let guard = arc
7540            .read()
7541            .map_err(|_| poisoned("storage lock during eager vulkan submit"))?;
7542        if let fuel_memory::BackendStorage::Vulkan(v) = &guard.inner
7543            && let Some(backend) = v.backend()
7544            && !seen.contains(&backend.gpu_id)
7545        {
7546            seen.push(backend.gpu_id);
7547            backends.push(backend.clone());
7548        }
7549    }
7550    for backend in backends {
7551        // Step E B1: the per-device location for the in-flight counter. A batch
7552        // submitted here is one in-flight unit on this iGPU until its handle's
7553        // `Drop` (after `drain_inflight_vulkan` / realize-end).
7554        let loc = DeviceLocation::Vulkan {
7555            gpu_id: backend.gpu_id,
7556        };
7557        if let Some(batch) = backend.submit_pending()? {
7558            inflight.push(VulkanCompletion::new(backend, batch, loc));
7559        }
7560    }
7561    Ok(())
7562}
7563
7564#[cfg(not(feature = "vulkan"))]
7565#[inline]
7566fn eager_submit_all_vulkan(
7567    _cache: &StorageCache,
7568    _inflight: &mut Vec<InflightVulkan>,
7569) -> Result<()> {
7570    Ok(())
7571}
7572
7573/// Step E A4b-4 — wait every in-flight (eagerly-submitted) Vulkan batch, then
7574/// clear the list. The re-sync half of [`eager_submit_all_vulkan`].
7575///
7576/// Each `into_wait` blocks on the batch fence (`vkWaitForFences`), retires the
7577/// backend's descriptor pools, and frees the batch (CB / descriptor sets /
7578/// transient buffers / retired command pool — all now idle on the GPU). After
7579/// this returns, NO submitted Vulkan command buffer is still executing, so it is
7580/// safe to (a) record a new Vulkan op that may read a just-produced buffer,
7581/// (b) D2H-copy a Vulkan buffer on the host, or (c) free a buffer a batch read.
7582///
7583/// Because the eager submit happened at the PRIOR chunk boundary and an
7584/// intervening (e.g. CUDA) chunk has since been recorded/dispatched, the fence is
7585/// typically already signalled here — the wait is a fast no-op, and the iGPU work
7586/// genuinely overlapped the other device's stream. Waiting the Vulkan fence does
7587/// NOT touch the CUDA stream, so the other device keeps running (concurrency
7588/// preserved — design §5 "the per-device guards don't cross-stall").
7589#[cfg(feature = "vulkan")]
7590fn drain_inflight_vulkan(inflight: &mut Vec<VulkanCompletion>) -> Result<()> {
7591    for vc in inflight.drain(..) {
7592        vc.into_wait()?;
7593    }
7594    Ok(())
7595}
7596
7597#[cfg(not(feature = "vulkan"))]
7598#[inline]
7599fn drain_inflight_vulkan(_inflight: &mut Vec<InflightVulkan>) -> Result<()> {
7600    Ok(())
7601}
7602
7603/// Step E A4b-2: the realize-end Vulkan drain, SPLIT into submit-then-wait.
7604///
7605/// Replaces A2's `force_flush_all_vulkan` (which submitted + waited atomically
7606/// inside `force_flush`). For each DISTINCT Vulkan backend referenced by the
7607/// cache, `submit_pending` submits the still-open batch WITHOUT waiting (→ a
7608/// `SubmittedBatch`), wraps it in the executor's [`VulkanCompletion`] handle, and
7609/// `wait`s it. Net for a pure-Vulkan realize: the batch still accumulates across
7610/// the whole walk (the per-op path keeps returning `Ready`; no eager submit —
7611/// that is A4b-4) and is submitted ONCE here, then waited — **byte-identical to
7612/// A2**, same single submission at realize-end, just split through the handle.
7613///
7614/// Idempotent across repeated cache arcs: the first `submit_pending` on a backend
7615/// returns `Some(batch)`; subsequent calls on the same backend see an empty batch
7616/// and return `None` (skipped) — exactly the `force_flush` idempotence A2 relied
7617/// on. No-op for a non-Vulkan build.
7618#[cfg(feature = "vulkan")]
7619fn drain_vulkan_pending(cache: &StorageCache) -> Result<()> {
7620    use crate::compiled::CompletionHandle;
7621    for arc in cache.values() {
7622        let backend = {
7623            let guard = arc
7624                .read()
7625                .map_err(|_| poisoned("storage lock during vulkan submit_pending"))?;
7626            match &guard.inner {
7627                fuel_memory::BackendStorage::Vulkan(v) => v.backend().cloned(),
7628                _ => None,
7629            }
7630        };
7631        let Some(backend) = backend else { continue };
7632        // Submit the open batch (if any) without waiting, then wait via the
7633        // completion handle. Empty batch → None → nothing to wait.
7634        // Step E B1: `new` increments the in-flight counter for this device;
7635        // `handle.wait()` waits + drops the `VulkanCompletion`, decrementing it
7636        // — a balanced submit/retire even on this transient realize-end path.
7637        let loc = DeviceLocation::Vulkan {
7638            gpu_id: backend.gpu_id,
7639        };
7640        if let Some(batch) = backend.submit_pending()? {
7641            let handle: CompletionHandle =
7642                CompletionHandle::Pending(Box::new(VulkanCompletion::new(backend, batch, loc)));
7643            handle.wait()?;
7644        }
7645    }
7646    Ok(())
7647}
7648
7649#[cfg(not(feature = "vulkan"))]
7650fn drain_vulkan_pending(_cache: &StorageCache) -> Result<()> {
7651    Ok(())
7652}
7653
7654/// Step E A2: force the Vulkan backend behind `arc` (if any) to submit + WAIT
7655/// its open batch — the blocking drain before freeing a buffer the batch may
7656/// reference (a destructive eviction) so a recorded-but-unsubmitted command never
7657/// reads freed memory. No-op for non-Vulkan storage, an empty batch, or a
7658/// non-Vulkan build.
7659///
7660/// **Retained for the SINGLE-DEVICE path (byte-identical to pre-A2.1).** A2.1's
7661/// deferred-deletion ([`defer_evicted_vulkan_buffer`]) replaces this only on a
7662/// MULTI-backend realize, where eager-submit + in-flight tracking + the
7663/// realize-end `drain_inflight_vulkan` are all live. On a single-device Vulkan
7664/// realize the A4b machinery is gated off (`multi_backend == false`): the
7665/// cross-batch RAW guard (`pipelined.rs:832`) does not run, so a later Vulkan op
7666/// reading a buffer an eager-submitted batch wrote could race (separate
7667/// submissions only BEGIN in order, may overlap). The blocking `force_flush`
7668/// (submit + wait) is the coherent eviction drain there — exactly the original
7669/// behavior — so single-device stays byte-identical and UAF-safe.
7670#[cfg(feature = "vulkan")]
7671fn force_flush_vulkan(arc: &Arc<RwLock<Storage>>) -> Result<()> {
7672    let guard = arc
7673        .read()
7674        .map_err(|_| poisoned("storage lock during vulkan force_flush"))?;
7675    if let fuel_memory::BackendStorage::Vulkan(v) = &guard.inner
7676        && let Some(backend) = v.backend()
7677    {
7678        backend.force_flush()?;
7679    }
7680    Ok(())
7681}
7682
7683#[cfg(not(feature = "vulkan"))]
7684fn force_flush_vulkan(_arc: &Arc<RwLock<Storage>>) -> Result<()> {
7685    Ok(())
7686}
7687
7688/// Step E A2.1 — DEFERRED-DELETION of a Vulkan data buffer evicted while Vulkan
7689/// work is in flight (the throughput refinement that REPLACES the eviction-time
7690/// drain on a MULTI-backend realize). Called at the per-NodeId destructive
7691/// eviction (`Op::Release`/`Op::Move` cleanup) for the buffer about to leave the
7692/// cache, INSTEAD of `drain_inflight_vulkan` + `force_flush` (two host-blocking
7693/// fence waits) — so the iGPU work the executor was overlapping with CUDA is not
7694/// stalled at every eviction.
7695///
7696/// Two classes of Vulkan reader can hold a reference to `destroyed`'s buffer at
7697/// the eviction:
7698///   1. the **in-flight** `SubmittedBatch`es in `inflight` (submitted CBs, each
7699///      fenced), and
7700///   2. the **open**, not-yet-submitted recorder batch (recorded commands, NO
7701///      fence yet).
7702///
7703/// We make BOTH fence-gated without blocking the host:
7704///   - `eager_submit_all_vulkan` submits the open batch WITHOUT waiting, turning
7705///     it into one more in-flight `SubmittedBatch` (now fenced) pushed onto
7706///     `inflight`. (Whole-chunk granularity — UAF/race-safe per its contract; at a
7707///     destructive eviction the open batch is a contiguous Vulkan run.)
7708///   - We then move a refcount clone of the evicted buffer's `Arc<VulkanBuffer>`
7709///     into EVERY in-flight batch (conservative: we cannot cheaply map
7710///     buffer→batch, exactly the reason the old drain waited *all* of them). Each
7711///     batch frees its retained clone POST-fence on `Drop` (follow-on #2).
7712///
7713/// After this returns the caller `cache.remove`s `destroyed`; the cache's
7714/// `Arc<RwLock<Storage>>` drops, but the buffer's recycler
7715/// (`VulkanBuffer::drop`) reclaims it only when its LAST `Arc` drops — and the
7716/// retained clones keep it alive until their owning batches' fences signal. So the
7717/// GPU's last read of the buffer strictly precedes the free (NO use-after-free),
7718/// the host never blocks at the eviction (the iGPU keeps overlapping CUDA — the
7719/// throughput win), and every batch (hence every retained buffer) is drained by
7720/// realize-end at the latest (`drain_inflight_vulkan`, `pipelined.rs:916/1238`,
7721/// runs unconditionally → NO leak).
7722///
7723/// **Multi-backend only** (the call site gates `if multi_backend`). On a
7724/// single-device realize the open batch is drained by the blocking
7725/// [`force_flush_vulkan`] instead (byte-identical to pre-A2.1; see its doc for
7726/// why the deferred path is unsafe without the cross-batch RAW guard). No-op for a
7727/// non-Vulkan storage, an empty open + no in-flight batches, or a non-Vulkan build.
7728/// Open-batch size (dispatches) at which a deferred eviction submits the batch so the
7729/// GPU runs it while the host keeps recording.
7730#[cfg(feature = "vulkan")]
7731const EVICT_SUBMIT_MIN_DISPATCHES: usize = 48;
7732
7733#[cfg(feature = "vulkan")]
7734fn defer_evicted_vulkan_buffer(
7735    cache: &StorageCache,
7736    destroyed: NodeId,
7737    inflight: &mut Vec<VulkanCompletion>,
7738) -> Result<()> {
7739    // Pull the evicted buffer's device Arc (and its backend) out of the cache BEFORE
7740    // it is removed. Non-Vulkan storage, a host-evicted (no device buffer) Vulkan
7741    // storage, or an absent entry → nothing to retain (no Vulkan reader can hold a
7742    // device buffer).
7743    let (buf, backend) = {
7744        let Some(arc) = cache.get(&destroyed) else {
7745            return Ok(());
7746        };
7747        let guard = arc
7748            .read()
7749            .map_err(|_| poisoned("storage lock during deferred-eviction retain"))?;
7750        match &guard.inner {
7751            fuel_memory::BackendStorage::Vulkan(v) => (v.device_buffer_arc(), v.backend().cloned()),
7752            _ => (None, None),
7753        }
7754    };
7755    let Some(buf) = buf else { return Ok(()) };
7756
7757    // The OPEN batch may hold recorded-but-unsubmitted commands that read `destroyed`:
7758    // retain the buffer on the open batch itself (freed post-fence once that batch is
7759    // submitted and waited). This neither submits nor waits — it used to eager-submit
7760    // here, i.e. one queue submit per eviction (61 per Qwen3 decode step).
7761    // Whether the open batch held recorded work (so the retain above actually kept a reader's
7762    // buffer alive instead of blocking): read BEFORE the eager submit below empties it.
7763    let retained_in_open_batch = backend.as_ref().is_some_and(|b| b.open_batch_len() > 0);
7764    if let Some(backend) = &backend {
7765        backend.retain_in_open_batch(buf.clone());
7766    }
7767    // Retain a clone of the evicted buffer in EVERY in-flight batch. Each frees it
7768    // POST-fence on `Drop` — the buffer outlives the GPU's last read with no host
7769    // block. Conservative over all batches (no cheap buffer→batch map); over-retention
7770    // only lengthens the lifetime, never a UAF, and all batches drain by realize-end.
7771    for vc in inflight.iter_mut() {
7772        vc.retain_data(buf.clone());
7773    }
7774    // Keep the GPU fed: submit the open batch once it has grown by a chunk.
7775    if let Some(backend) = backend
7776        && backend.open_batch_len() >= EVICT_SUBMIT_MIN_DISPATCHES
7777    {
7778        eager_submit_all_vulkan(cache, inflight)?;
7779    }
7780    // Step E A2.1 — throughput-observability. Count a DEFERRED retain that
7781    // actually replaced a host block: an evicted Vulkan buffer retained onto ≥1
7782    // in-flight batch (the open-batch eager-submit and/or pre-existing in-flight
7783    // batches). Pre-A2.1 every such site host-blocked (`force_flush` and/or
7784    // `drain_inflight_vulkan`); now it does not. A test reads
7785    // [`deferred_eviction_retains`] to assert the deferred path fired without a
7786    // drain (deterministic — no wall-clock, which is noisy on this box). When
7787    // `inflight` is empty AND the open batch was empty there was genuinely no in-flight/open
7788    // Vulkan reader to wait for, so no host block was avoided (and none was needed) — not
7789    // counted. A retain onto a non-empty OPEN batch counts (GAP-371: the counter used to look
7790    // only at in-flight batches, so an eviction inside the still-open batch, which is the
7791    // common single-chunk case, never advanced it even though it avoided the host block).
7792    if retained_in_open_batch || !inflight.is_empty() {
7793        DEFERRED_EVICTION_RETAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7794    }
7795    Ok(())
7796}
7797
7798/// Step E A2.1 — cumulative count of deferred-deletion retains that replaced a
7799/// host-blocking eviction drain (an evicted Vulkan buffer retained onto ≥1
7800/// in-flight batch instead of waiting it). Process-global, `Relaxed` — a pure
7801/// test/telemetry observation, never a correctness gate (mirrors the B1 in-flight
7802/// counter idiom). Read by the live deferred-eviction throughput test.
7803#[cfg(feature = "vulkan")]
7804pub static DEFERRED_EVICTION_RETAINS: std::sync::atomic::AtomicUsize =
7805    std::sync::atomic::AtomicUsize::new(0);
7806
7807/// Read the A2.1 deferred-eviction-retain counter (see
7808/// [`DEFERRED_EVICTION_RETAINS`]). `pub` so the live throughput test can assert a
7809/// deferred retain fired (the eviction did NOT host-block on a Vulkan fence).
7810#[cfg(feature = "vulkan")]
7811pub fn deferred_eviction_retains() -> usize {
7812    DEFERRED_EVICTION_RETAINS.load(std::sync::atomic::Ordering::Relaxed)
7813}
7814
7815#[cfg(not(feature = "vulkan"))]
7816#[inline]
7817fn defer_evicted_vulkan_buffer(
7818    _cache: &StorageCache,
7819    _destroyed: NodeId,
7820    _inflight: &mut Vec<InflightVulkan>,
7821) -> Result<()> {
7822    Ok(())
7823}
7824
7825/// Materialize a contiguous Storage Arc from a non-contiguous one.
7826/// Allocates a fresh buffer on the input's backend and copies the
7827/// strided / offset / broadcast input into it via the backend's
7828/// contiguize kernel. The returned Arc is a brand-new buffer; the
7829/// caller is responsible for replacing the cache entry only for the
7830/// duration of one kernel call (the upstream view op's output stays
7831/// in the cache so other consumers still see the strided view).
7832///
7833/// Stage 4 of Layout-on-Node — auto-Contiguize.
7834fn auto_contiguize(arc: &Arc<RwLock<Storage>>, layout: &Layout) -> Result<Arc<RwLock<Storage>>> {
7835    let in_guard = arc
7836        .read()
7837        .map_err(|_| poisoned("input storage lock during auto_contiguize"))?;
7838    let dtype = in_guard.dtype;
7839    let dtype_size = dtype.size_in_bytes();
7840    let new_storage = match &in_guard.inner {
7841        fuel_memory::BackendStorage::Cpu(c) => {
7842            let new_bytes = fuel_cpu_backend::byte_kernels::contiguize_cpu(c, layout, dtype_size)?;
7843            Storage::new(fuel_memory::BackendStorage::Cpu(new_bytes), dtype)
7844        }
7845        #[cfg(feature = "cuda")]
7846        fuel_memory::BackendStorage::Cuda(c) => {
7847            // Native baracuda contiguize (alpha.29). Byte-width-
7848            // dispatched: 1/2/4/8/16 byte elements all route to the
7849            // appropriate kernel. Handles signed strides (Flip),
7850            // zero strides (BroadcastTo), and non-zero element offset.
7851            //
7852            // Three host-side fast paths bake into the baracuda
7853            // launchers: already-contiguous → single cuMemcpyDtoDAsync;
7854            // innermost-stride-1 → per-outer-coord run copy; generic
7855            // → one thread per output element. Retires the prior
7856            // D2H → CPU contiguize_cpu → H2D fallback (two device
7857            // round-trips per non-contig input).
7858            let contig = fuel_cuda_backend::baracuda::contiguize::contiguize_to_fresh(
7859                c, layout, dtype_size,
7860            )?;
7861            Storage::new(fuel_memory::BackendStorage::Cuda(contig), dtype)
7862        }
7863        #[cfg(feature = "vulkan")]
7864        fuel_memory::BackendStorage::Vulkan(v) => {
7865            // Native `strided_copy_signed_*` kernel when it applies (2/4/8-byte
7866            // elements; see `contiguize_vulkan`). Otherwise the V.1.B host round trip:
7867            // D2H → CPU contiguize_cpu → H2D, which forces a flush and a wait
7868            // per call.
7869            let backend = v.backend().ok_or_else(|| {
7870                Error::Msg(
7871                    "auto_contiguize: Vulkan input has no backend handle. \
7872                     Storages flowing through the pipelined executor's Vulkan \
7873                     path must be constructed via VulkanBackend::alloc_bytes_handle \
7874                     / upload_bytes_handle (not the legacy alloc_bytes / \
7875                     upload_bytes which leave VulkanStorageBytes::backend = None)."
7876                        .to_string(),
7877                )
7878                .bt()
7879            })?;
7880            if let Some(native) = fuel_vulkan_backend::contiguize_vulkan(v, layout, dtype_size)? {
7881                return Ok(Arc::new(RwLock::new(Storage::new(
7882                    fuel_memory::BackendStorage::Vulkan(native),
7883                    dtype,
7884                ))));
7885            }
7886            let _t = crate::compiled::op_profile::PhaseTimer::start(
7887                "auto_contiguize.vulkan_host_roundtrip",
7888            );
7889            let host_bytes = backend.download_bytes(v)?;
7890            let host_cpu = fuel_cpu_backend::byte_storage::CpuStorageBytes::from_bytes(&host_bytes);
7891            let contig_cpu =
7892                fuel_cpu_backend::byte_kernels::contiguize_cpu(&host_cpu, layout, dtype_size)?;
7893            let host_contig_bytes = contig_cpu.bytes().to_vec();
7894            let vk_bytes = backend.upload_bytes_handle(&host_contig_bytes)?;
7895            Storage::new(fuel_memory::BackendStorage::Vulkan(vk_bytes), dtype)
7896        }
7897        #[allow(unreachable_patterns)]
7898        _ => {
7899            return Err(Error::Msg(
7900                "auto_contiguize: backend not wired (CPU + CUDA + Vulkan are \
7901                 wired today; Metal extends this match when its byte-storage \
7902                 substrate lands)"
7903                    .to_string(),
7904            )
7905            .bt());
7906        }
7907    };
7908    Ok(Arc::new(RwLock::new(new_storage)))
7909}
7910
7911/// Write-into sibling of [`auto_contiguize`] (CapturedRun executor
7912/// build-out, 4b-γ): materializes a contiguous copy of `arc` at `layout`
7913/// INTO `dest`'s EXISTING buffer instead of allocating a fresh one — the
7914/// path `WorkItemKind::ContiguizeOf`'s Reuse-mode branch needs (device
7915/// allocation is illegal inside a capture scope). `dest` must already be
7916/// sized to the contiguized output's byte count — true by construction,
7917/// since the persistent map only ever holds a buffer THIS SAME code path
7918/// (the warm-run `auto_contiguize` allocation) sized.
7919///
7920/// CUDA-only today: `PersistentOutputs::reuse` (Reuse mode) is only ever
7921/// constructed inside [`PipelinedExecutor::capture_decode`], which is
7922/// `#[cfg(feature = "cuda")]`-gated and validates every compute node
7923/// targets `Cuda` — a CPU or Vulkan storage can never actually reach this
7924/// function in practice. Per this project's "never panic on production
7925/// paths" rule, the other backends still surface a typed gap rather than
7926/// silently mishandling it (never a crash).
7927#[cfg_attr(not(feature = "cuda"), allow(unused_variables))]
7928fn contiguize_into(
7929    dest: &Arc<RwLock<Storage>>,
7930    arc: &Arc<RwLock<Storage>>,
7931    layout: &Layout,
7932) -> Result<()> {
7933    let in_guard = arc
7934        .read()
7935        .map_err(|_| poisoned("input storage lock during contiguize_into"))?;
7936    match &in_guard.inner {
7937        #[cfg(feature = "cuda")]
7938        fuel_memory::BackendStorage::Cuda(src_cuda) => {
7939            let dtype_size = in_guard.dtype.size_in_bytes();
7940            let mut dest_guard = dest
7941                .write()
7942                .map_err(|_| poisoned("dest storage lock during contiguize_into"))?;
7943            let dest_cuda = match &mut dest_guard.inner {
7944                fuel_memory::BackendStorage::Cuda(d) => d,
7945                other => {
7946                    return Err(Error::Msg(format!(
7947                        "contiguize_into: dest is BackendStorage::{:?}, not Cuda",
7948                        other.backend_id(),
7949                    ))
7950                    .bt());
7951                }
7952            };
7953            fuel_cuda_backend::baracuda::contiguize::contiguize_into(
7954                src_cuda, layout, dest_cuda, dtype_size,
7955            )
7956        }
7957        #[allow(unreachable_patterns)]
7958        _ => Err(Error::Msg(
7959            "contiguize_into: only CUDA is wired (PersistentOutputs::reuse / \
7960             capture_decode is CUDA-only today — no CPU/Vulkan consumer exists \
7961             yet; extend this match if one appears)"
7962                .to_string(),
7963        )
7964        .bt()),
7965    }
7966}
7967
7968#[cfg(test)]
7969mod backend_neutral_tests {
7970    use super::*;
7971
7972    #[test]
7973    fn only_deviceless_items_are_backend_neutral() {
7974        let n = NodeId(0);
7975        // Adopting an input-cache entry or aliasing a producer touches no device.
7976        assert!(is_backend_neutral(&WorkItemKind::ConstAdopt));
7977        assert!(is_backend_neutral(&WorkItemKind::ViewOf { input: n }));
7978        assert!(is_backend_neutral(&WorkItemKind::SlotView { producer: n }));
7979        // Contiguize runs on its input's backend; its own `target_backend` is a
7980        // placeholder, so it must not count as a backend switch.
7981        assert!(is_backend_neutral(&WorkItemKind::ContiguizeOf { input: n }));
7982        // Sabotage siblings: anything that runs a kernel of its own or moves bytes
7983        // across devices is NOT, so a real backend switch still arms the
7984        // chunk-boundary logic.
7985        assert!(!is_backend_neutral(&WorkItemKind::Kernel));
7986        assert!(!is_backend_neutral(&WorkItemKind::Copy {
7987            target_location: DeviceLocation::Cpu
7988        }));
7989        assert!(!is_backend_neutral(&WorkItemKind::WriteSlice {
7990            dest: n,
7991            source: n
7992        }));
7993    }
7994}
7995
7996#[cfg(test)]
7997mod tests {
7998    // ---- GAP-380 (a2): the plan-time arm guard ----------------------------------------------
7999
8000    fn iota_graph(backend: BackendId) -> (Graph, NodeId) {
8001        let mut g = Graph::new();
8002        let id = g.push(Node {
8003            op: Op::Iota { len: 4 },
8004            inputs: vec![],
8005            shape: fuel_ir::Shape::from_dims(&[4]),
8006            dtype: DType::F32,
8007        });
8008        g.set_target_backend(id, backend);
8009        (g, id)
8010    }
8011
8012    #[test]
8013    fn an_iota_on_a_backend_with_no_arm_fails_at_plan_time_naming_node_and_op() {
8014        let (g, id) = iota_graph(BackendId::Vulkan);
8015        let err = check_direct_arms_wired(&g, &[id])
8016            .expect_err("Vulkan has no Iota arm")
8017            .to_string();
8018        assert!(
8019            err.contains(&format!("Node#{}", id.0)),
8020            "names the node: {err}"
8021        );
8022        assert!(err.contains("Iota"), "names the op: {err}");
8023        assert!(err.contains("Vulkan"), "names the backend: {err}");
8024    }
8025
8026    /// Sabotage siblings: the same guard passes where the arm IS wired, so the red above is the
8027    /// missing arm and not the guard rejecting everything.
8028    #[test]
8029    fn an_iota_on_cpu_passes_the_arm_guard_and_other_ops_are_not_direct_dispatched() {
8030        let (g, id) = iota_graph(BackendId::Cpu);
8031        check_direct_arms_wired(&g, &[id]).expect("CPU Iota is wired");
8032        assert_eq!(
8033            direct_arm_wired(&Op::Add, BackendId::Cuda),
8034            None,
8035            "Add goes through the binding table"
8036        );
8037        assert_eq!(
8038            direct_arm_wired(&Op::Iota { len: 1 }, BackendId::Cpu),
8039            Some(true)
8040        );
8041        assert_eq!(
8042            direct_arm_wired(&Op::Iota { len: 1 }, BackendId::Cuda),
8043            Some(cfg!(feature = "cuda")),
8044            "the CUDA arm is wired exactly when the cuda feature compiles it"
8045        );
8046    }
8047
8048    use super::*;
8049    use fuel_graph::Node;
8050    use fuel_ir::Shape;
8051
8052    /// Task 5 (C6): `Op::Scan` has no native kernel in Phase 1 — it is
8053    /// always lowered/re-fused before execution — so `op_to_op_kind` must
8054    /// fall through its `_ => None` wildcard for it, exactly like any other
8055    /// not-yet-wired op. Regression lock, not born-red: this is expected to
8056    /// pass immediately.
8057    #[test]
8058    fn scan_has_no_dispatch_op_kind() {
8059        use fuel_graph::{Op, ScanEmit};
8060        assert_eq!(
8061            crate::pipelined::op_to_op_kind(&Op::Scan {
8062                n_carries: 1,
8063                n_xs: 0,
8064                bound: 2,
8065                emit: ScanEmit::All,
8066                early_exit: None
8067            }),
8068            None,
8069        );
8070    }
8071
8072    /// Step E A4b open question #4 — "event only where waited", step 1.
8073    /// `build_wait_set` collects exactly the producers of `Op::Copy`/`Move`
8074    /// nodes in the order: a same-device-only node (never copied/moved) must
8075    /// be ABSENT, and the Copy's own node id must not appear either (it is
8076    /// not its own producer).
8077    #[test]
8078    fn build_wait_set_collects_only_cross_device_copy_producers() {
8079        let mut g = Graph::new();
8080        let const_id = g.push(Node {
8081            op: Op::Const,
8082            inputs: vec![],
8083            shape: Shape::from_dims(&[4]),
8084            dtype: DType::F32,
8085        });
8086        // Same-device-only consumer of const_id — never fed into a Copy/Move.
8087        let same_device_id = g.push(Node {
8088            op: Op::Contiguize,
8089            inputs: vec![const_id],
8090            shape: Shape::from_dims(&[4]),
8091            dtype: DType::F32,
8092        });
8093        // A cross-device Copy whose producer is `same_device_id`.
8094        let copy_id = g.push(Node {
8095            op: Op::Copy {
8096                target: DeviceLocation::Cuda { gpu_id: 0 },
8097            },
8098            inputs: vec![same_device_id],
8099            shape: Shape::from_dims(&[4]),
8100            dtype: DType::F32,
8101        });
8102        let order = vec![const_id, same_device_id, copy_id];
8103
8104        let set = build_wait_set(&g, &order);
8105        assert!(
8106            set.contains(&same_device_id),
8107            "the Copy's producer must be in the wait set"
8108        );
8109        assert!(
8110            !set.contains(&const_id),
8111            "a node with no Copy/Move consumer must be absent from the wait set"
8112        );
8113        assert!(
8114            !set.contains(&copy_id),
8115            "the Copy node itself is not its own producer"
8116        );
8117        assert_eq!(
8118            set.len(),
8119            1,
8120            "only the one true cross-device producer is in the set"
8121        );
8122    }
8123
8124    /// A `Move` producer is collected the same way as a `Copy` producer.
8125    #[test]
8126    fn build_wait_set_collects_move_producers_too() {
8127        let mut g = Graph::new();
8128        let const_id = g.push(Node {
8129            op: Op::Const,
8130            inputs: vec![],
8131            shape: Shape::from_dims(&[4]),
8132            dtype: DType::F32,
8133        });
8134        let move_id = g.push(Node {
8135            op: Op::Move {
8136                target: DeviceLocation::Cpu,
8137            },
8138            inputs: vec![const_id],
8139            shape: Shape::from_dims(&[4]),
8140            dtype: DType::F32,
8141        });
8142        let order = vec![const_id, move_id];
8143
8144        let set = build_wait_set(&g, &order);
8145        assert!(
8146            set.contains(&const_id),
8147            "the Move's producer must be in the wait set"
8148        );
8149        assert_eq!(set.len(), 1);
8150    }
8151
8152    /// A CPU-only order (no `Op::Copy`/`Op::Move` anywhere) yields an empty
8153    /// wait set — every node in it is eligible for elision.
8154    #[test]
8155    fn build_wait_set_is_empty_for_cpu_only_order() {
8156        let mut g = Graph::new();
8157        let const_id = g.push(Node {
8158            op: Op::Const,
8159            inputs: vec![],
8160            shape: Shape::from_dims(&[4]),
8161            dtype: DType::F32,
8162        });
8163        let contig_id = g.push(Node {
8164            op: Op::Contiguize,
8165            inputs: vec![const_id],
8166            shape: Shape::from_dims(&[4]),
8167            dtype: DType::F32,
8168        });
8169        let order = vec![const_id, contig_id];
8170
8171        let set = build_wait_set(&g, &order);
8172        assert!(
8173            set.is_empty(),
8174            "a CPU-only order (no Copy/Move) yields an empty wait set"
8175        );
8176    }
8177
8178    /// `will_be_waited`'s two arms: the conservative `None` fallback (the
8179    /// `OrderSource::Streaming` case) is always `true`; a `Some(set)` checks
8180    /// membership.
8181    #[test]
8182    fn will_be_waited_none_is_conservative_true_for_any_node() {
8183        let ws: WaitSet = None;
8184        assert!(will_be_waited(&ws, NodeId(0)));
8185        assert!(will_be_waited(&ws, NodeId(12345)));
8186    }
8187
8188    #[test]
8189    fn will_be_waited_some_checks_membership() {
8190        let mut set = HashSet::new();
8191        set.insert(NodeId(3));
8192        let ws: WaitSet = Some(set);
8193        assert!(will_be_waited(&ws, NodeId(3)), "member must be waited");
8194        assert!(!will_be_waited(&ws, NodeId(4)), "non-member must be elided");
8195    }
8196
8197    /// A4b-1 test double: a `Completion` whose `wait` flips a shared flag, so a
8198    /// test can observe whether the drain actually waited it.
8199    struct FlagCompletion(std::sync::Arc<std::sync::atomic::AtomicUsize>);
8200    impl crate::compiled::Completion for FlagCompletion {
8201        fn wait(self: Box<Self>) -> Result<()> {
8202            self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
8203            Ok(())
8204        }
8205    }
8206
8207    /// A4b-1: `store_handle` keeps only `Pending` handles (so the post-drain
8208    /// empty-map assert is meaningful and the drain is O(pending)), and
8209    /// `drain_handles` waits each pending handle exactly once then empties the map.
8210    #[test]
8211    fn handle_map_stores_pending_and_drains_once() {
8212        use std::sync::Arc as StdArc;
8213        use std::sync::atomic::{AtomicUsize, Ordering};
8214
8215        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
8216
8217        // Ready handles are not stored.
8218        store_handle(&mut handles, NodeId(1), CompletionHandle::Ready);
8219        assert!(handles.is_empty(), "Ready handles must not be stored");
8220
8221        // Two pending handles are stored and each waited once on drain.
8222        let waited = StdArc::new(AtomicUsize::new(0));
8223        store_handle(
8224            &mut handles,
8225            NodeId(2),
8226            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8227        );
8228        store_handle(
8229            &mut handles,
8230            NodeId(3),
8231            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8232        );
8233        assert_eq!(handles.len(), 2);
8234
8235        drain_handles(&mut handles).expect("drain");
8236        assert_eq!(
8237            waited.load(Ordering::SeqCst),
8238            2,
8239            "each pending handle waited once"
8240        );
8241        assert!(handles.is_empty(), "map empty after drain");
8242    }
8243
8244    /// A4b-1: re-keying a NodeId with a new Pending handle waits the prior one
8245    /// (no leaked async work), and storing `Ready` over a prior Pending also
8246    /// waits it. Defensive — NodeIds are unique per realize in practice.
8247    #[test]
8248    fn handle_map_rekey_waits_previous() {
8249        use std::sync::Arc as StdArc;
8250        use std::sync::atomic::{AtomicUsize, Ordering};
8251
8252        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
8253        let waited = StdArc::new(AtomicUsize::new(0));
8254
8255        store_handle(
8256            &mut handles,
8257            NodeId(7),
8258            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8259        );
8260        // Re-key with another Pending → prior is waited.
8261        store_handle(
8262            &mut handles,
8263            NodeId(7),
8264            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8265        );
8266        assert_eq!(
8267            waited.load(Ordering::SeqCst),
8268            1,
8269            "rekey waited the prior pending"
8270        );
8271
8272        // Store Ready over the live Pending → it is waited too.
8273        store_handle(&mut handles, NodeId(7), CompletionHandle::Ready);
8274        assert_eq!(
8275            waited.load(Ordering::SeqCst),
8276            2,
8277            "Ready-over-Pending waited it"
8278        );
8279        assert!(handles.is_empty());
8280
8281        drain_handles(&mut handles).expect("drain empty");
8282    }
8283
8284    /// A4b-3: `wait_producer_handle` waits the named producer's handle EXACTLY
8285    /// once and removes it from the map (the finer cross-device source-drain
8286    /// consumes the producer's completion before the Copy reads its buffer), and
8287    /// is a no-op for an absent producer (CPU / Vulkan-`Ready` source, or an
8288    /// already-consumed handle). The realize-end drain then waits only what
8289    /// remains — no double-wait.
8290    #[test]
8291    fn wait_producer_handle_consumes_named_handle_once() {
8292        use std::sync::Arc as StdArc;
8293        use std::sync::atomic::{AtomicUsize, Ordering};
8294
8295        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
8296        let waited = StdArc::new(AtomicUsize::new(0));
8297
8298        // Two producers in flight; the Copy's source is NodeId(2).
8299        store_handle(
8300            &mut handles,
8301            NodeId(2),
8302            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8303        );
8304        store_handle(
8305            &mut handles,
8306            NodeId(5),
8307            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8308        );
8309
8310        // Absent producer → no-op (a CPU/Vulkan-Ready source has no handle).
8311        wait_producer_handle(&mut handles, NodeId(99)).expect("absent is no-op");
8312        assert_eq!(
8313            waited.load(Ordering::SeqCst),
8314            0,
8315            "absent producer waited nothing"
8316        );
8317        assert_eq!(handles.len(), 2);
8318
8319        // The cross-device copy's source: waited once, removed from the map.
8320        wait_producer_handle(&mut handles, NodeId(2)).expect("wait source");
8321        assert_eq!(
8322            waited.load(Ordering::SeqCst),
8323            1,
8324            "source producer waited once"
8325        );
8326        assert!(!handles.contains_key(&NodeId(2)), "source handle consumed");
8327        assert!(
8328            handles.contains_key(&NodeId(5)),
8329            "unrelated handle untouched"
8330        );
8331
8332        // Re-waiting the (now absent) source is a no-op — no double-wait.
8333        wait_producer_handle(&mut handles, NodeId(2)).expect("re-wait is no-op");
8334        assert_eq!(waited.load(Ordering::SeqCst), 1, "no double-wait");
8335
8336        // Realize-end drain waits only the remaining unrelated producer.
8337        drain_handles(&mut handles).expect("drain");
8338        assert_eq!(
8339            waited.load(Ordering::SeqCst),
8340            2,
8341            "drain waited the remaining one"
8342        );
8343        assert!(handles.is_empty());
8344    }
8345
8346    /// Op::Contiguize on a contiguous-already input is zero-copy:
8347    /// the executor adopts the input Storage Arc unchanged.
8348    #[test]
8349    fn op_contiguize_zero_copy_on_contiguous_input() {
8350        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
8351
8352        let graph = Arc::new(RwLock::new(Graph::new()));
8353        let (const_id, contig_id) = {
8354            let mut g = graph.write().unwrap();
8355            let const_id = g.push(Node {
8356                op: Op::Const,
8357                inputs: vec![],
8358                shape: Shape::from_dims(&[2, 2]),
8359                dtype: DType::F32,
8360            });
8361            let contig_id = g.push(Node {
8362                op: Op::Contiguize,
8363                inputs: vec![const_id],
8364                shape: Shape::from_dims(&[2, 2]),
8365                dtype: DType::F32,
8366            });
8367            // No need to set target_backend on Contiguize — the
8368            // executor inherits or defaults to CPU.
8369            (const_id, contig_id)
8370        };
8371
8372        let mut inputs = StorageCache::new();
8373        let input_arc = Arc::new(RwLock::new(storage));
8374        let input_arc_for_compare = Arc::clone(&input_arc);
8375        inputs.insert(const_id, input_arc);
8376
8377        let (result_arc, _) =
8378            PipelinedExecutor::realize(graph, contig_id, inputs).expect("realize");
8379
8380        // Same Arc → zero-copy adoption. Compare by raw pointer.
8381        assert!(
8382            Arc::ptr_eq(&result_arc, &input_arc_for_compare),
8383            "Op::Contiguize on contiguous input must adopt the input Arc (zero copy)",
8384        );
8385    }
8386
8387    /// Op::Contiguize on a strided input (here: a transposed view)
8388    /// materializes a fresh contiguous Storage. The output bytes
8389    /// reflect the strided view's logical content, not the input
8390    /// storage's underlying memory order.
8391    #[test]
8392    fn op_contiguize_materializes_on_strided_input() {
8393        // 2x3 row-major: [[1,2,3],[4,5,6]] → transpose → 3x2:
8394        // [[1,4],[2,5],[3,6]]. The transposed view shares the
8395        // original buffer; Op::Contiguize on the transpose
8396        // materializes contiguous bytes matching the transposed
8397        // logical order.
8398        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
8399
8400        let graph = Arc::new(RwLock::new(Graph::new()));
8401        let (const_id, _transpose_id, contig_id) = {
8402            let mut g = graph.write().unwrap();
8403            let const_id = g.push(Node {
8404                op: Op::Const,
8405                inputs: vec![],
8406                shape: Shape::from_dims(&[2, 3]),
8407                dtype: DType::F32,
8408            });
8409            let transpose_id = g.push(Node {
8410                op: Op::Transpose,
8411                inputs: vec![const_id],
8412                shape: Shape::from_dims(&[3, 2]),
8413                dtype: DType::F32,
8414            });
8415            let contig_id = g.push(Node {
8416                op: Op::Contiguize,
8417                inputs: vec![transpose_id],
8418                shape: Shape::from_dims(&[3, 2]),
8419                dtype: DType::F32,
8420            });
8421            (const_id, transpose_id, contig_id)
8422        };
8423
8424        let mut inputs = StorageCache::new();
8425        inputs.insert(const_id, Arc::new(RwLock::new(storage)));
8426
8427        let (result_arc, _) =
8428            PipelinedExecutor::realize(graph, contig_id, inputs).expect("realize");
8429
8430        let guard = result_arc.read().unwrap();
8431        let cpu = if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
8432            c
8433        } else {
8434            panic!("expected Cpu storage");
8435        };
8436        let typed: &[f32] = cpu.as_slice().expect("f32 cast");
8437        // Transposed logical order: [1,4,2,5,3,6].
8438        assert_eq!(
8439            typed,
8440            &[1.0, 4.0, 2.0, 5.0, 3.0, 6.0],
8441            "contiguized transpose must reflect logical (transposed) byte order",
8442        );
8443    }
8444
8445    /// E2E: 3-node graph (Const + Const + Add), pre-seeded inputs,
8446    /// realized through the compiler+executor thread pair, returns
8447    /// expected sum bytes.
8448    #[test]
8449    fn pipelined_realize_const_const_add() {
8450        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
8451        let rhs_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
8452
8453        let graph = Arc::new(RwLock::new(Graph::new()));
8454        let (lhs_id, rhs_id, add_id) = {
8455            let mut g = graph.write().unwrap();
8456            let lhs_id = g.push(Node {
8457                op: Op::Const,
8458                inputs: vec![],
8459                shape: Shape::from_dims(&[3]),
8460                dtype: DType::F32,
8461            });
8462            let rhs_id = g.push(Node {
8463                op: Op::Const,
8464                inputs: vec![],
8465                shape: Shape::from_dims(&[3]),
8466                dtype: DType::F32,
8467            });
8468            let add_id = g.push(Node {
8469                op: Op::Add,
8470                inputs: vec![lhs_id, rhs_id],
8471                shape: Shape::from_dims(&[3]),
8472                dtype: DType::F32,
8473            });
8474            g.set_target_backend(add_id, BackendId::Cpu);
8475            (lhs_id, rhs_id, add_id)
8476        };
8477
8478        let mut inputs = StorageCache::new();
8479        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
8480        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
8481
8482        let (result_arc, _result_layout) =
8483            PipelinedExecutor::realize(graph, add_id, inputs).expect("realize");
8484
8485        let guard = result_arc.read().unwrap();
8486        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
8487            let typed: &[f32] = c.as_slice().expect("f32 cast");
8488            assert_eq!(typed, &[11.0, 22.0, 33.0]);
8489        } else {
8490            panic!("expected CPU output");
8491        }
8492    }
8493
8494    /// CapturedRun executor build-out (Increment 1): capture a 2-op binary
8495    /// chain `z = (a + b) * c` THROUGH the pipelined executor's
8496    /// persistent-output mode, then prove the three capture guarantees on a
8497    /// live GPU:
8498    ///   1. after capture, the fixed output buffer holds the warm-run result
8499    ///      (capture RECORDS launches, it does not execute them);
8500    ///   2. `replay()` recomputes bit-exactly into the SAME fixed buffer;
8501    ///   3. replay reads the FIXED input addresses — overwriting an input
8502    ///      buffer in place and replaying yields the new result, matching an
8503    ///      independent uncaptured `realize`. This is the whole mechanism:
8504    ///      the write-into binary wrapper + the executor's reuse mode +
8505    ///      `capture_run` compose into a replayable decode-step graph.
8506    #[test]
8507    #[ignore = "requires a live CUDA device"]
8508    #[cfg(feature = "cuda")]
8509    fn capture_decode_binary_chain_replays_bit_exact_cuda() {
8510        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8511        use fuel_ir::Shape;
8512        use fuel_memory::BackendStorage;
8513
8514        let Ok(dev) = CudaDevice::new(0) else {
8515            return fuel_test_support::hardware::skip(
8516                fuel_test_support::hardware::Hardware::Cuda,
8517                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
8518            );
8519        };
8520
8521        // z = (a + b) * c, shape [4]. `y = a + b` is a persistent
8522        // INTERMEDIATE; `z` is the persistent target — both fixed-address.
8523        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId, NodeId, NodeId) {
8524            let graph = Arc::new(RwLock::new(Graph::new()));
8525            let (a, b, c, z) = {
8526                let mut g = graph.write().unwrap();
8527                let a = g.push(Node {
8528                    op: Op::Const,
8529                    inputs: vec![],
8530                    shape: Shape::from_dims(&[4]),
8531                    dtype: DType::F32,
8532                });
8533                let b = g.push(Node {
8534                    op: Op::Const,
8535                    inputs: vec![],
8536                    shape: Shape::from_dims(&[4]),
8537                    dtype: DType::F32,
8538                });
8539                let c = g.push(Node {
8540                    op: Op::Const,
8541                    inputs: vec![],
8542                    shape: Shape::from_dims(&[4]),
8543                    dtype: DType::F32,
8544                });
8545                let y = g.push(Node {
8546                    op: Op::Add,
8547                    inputs: vec![a, b],
8548                    shape: Shape::from_dims(&[4]),
8549                    dtype: DType::F32,
8550                });
8551                let z = g.push(Node {
8552                    op: Op::Mul,
8553                    inputs: vec![y, c],
8554                    shape: Shape::from_dims(&[4]),
8555                    dtype: DType::F32,
8556                });
8557                g.set_target_backend(y, BackendId::Cuda);
8558                g.set_target_backend(z, BackendId::Cuda);
8559                (a, b, c, z)
8560            };
8561            (graph, a, b, c, z)
8562        };
8563
8564        let up = |v: &[f32]| -> Arc<RwLock<Storage>> {
8565            let bytes: &[u8] = bytemuck::cast_slice(v);
8566            let cb = CudaStorageBytes::from_cpu_bytes(&dev, bytes).expect("h2d");
8567            Arc::new(RwLock::new(Storage::new(
8568                BackendStorage::Cuda(cb),
8569                DType::F32,
8570            )))
8571        };
8572        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8573            let g = arc.read().unwrap();
8574            let BackendStorage::Cuda(c) = &g.inner else {
8575                panic!("not cuda")
8576            };
8577            let host = c.to_cpu_bytes().expect("d2h");
8578            bytemuck::cast_slice(&host).to_vec()
8579        };
8580
8581        let a_data = [1.0_f32, 2.0, 3.0, 4.0];
8582        let b_data = [10.0_f32, 20.0, 30.0, 40.0];
8583        let c_data = [2.0_f32, 2.0, 2.0, 2.0];
8584        let expect0 = [22.0_f32, 44.0, 66.0, 88.0]; // (a+b)*c
8585
8586        // Fixed input Arcs (shared into capture; overwritten in place later).
8587        let a_arc = up(&a_data);
8588        let b_arc = up(&b_data);
8589        let c_arc = up(&c_data);
8590
8591        let (graph, a, b, c, z) = build();
8592        let mut inputs = StorageCache::new();
8593        inputs.insert(a, a_arc.clone());
8594        inputs.insert(b, b_arc.clone());
8595        inputs.insert(c, c_arc.clone());
8596
8597        let captured =
8598            PipelinedExecutor::capture_decode(Arc::clone(&graph), z, inputs, SymEnv::default())
8599                .expect("capture_decode");
8600
8601        // (1) warm-run result sits in the captured output buffer.
8602        assert_eq!(
8603            read(&captured.output),
8604            &expect0,
8605            "warm-run result after capture"
8606        );
8607
8608        // (2) replay with the same inputs recomputes bit-exactly.
8609        captured.run.replay(&dev).expect("replay");
8610        dev.synchronize().expect("sync");
8611        assert_eq!(read(&captured.output), &expect0, "replay reproduces result");
8612
8613        // (3) overwrite input `a` IN PLACE (same device address), replay ->
8614        //     the new result flows from the FIXED input address. Compare to
8615        //     an independent uncaptured realize with the same new input.
8616        let a2 = [100.0_f32, 200.0, 300.0, 400.0];
8617        {
8618            let g = a_arc.read().unwrap();
8619            let BackendStorage::Cuda(c) = &g.inner else {
8620                panic!("a not cuda")
8621            };
8622            c.write_from_host(bytemuck::cast_slice(&a2))
8623                .expect("in-place H2D");
8624        }
8625        captured.run.replay(&dev).expect("replay 2");
8626        dev.synchronize().expect("sync 2");
8627        let got = read(&captured.output);
8628
8629        let (graph_ref, ar, br, cr, zr) = build();
8630        let mut inputs_ref = StorageCache::new();
8631        inputs_ref.insert(ar, up(&a2));
8632        inputs_ref.insert(br, up(&b_data));
8633        inputs_ref.insert(cr, up(&c_data));
8634        let (ref_arc, _) =
8635            PipelinedExecutor::realize(graph_ref, zr, inputs_ref).expect("ref realize");
8636        let expect1 = read(&ref_arc); // (a2+b)*c = [220,440,660,880]
8637        assert_eq!(
8638            got, expect1,
8639            "replay after in-place input update matches uncaptured realize"
8640        );
8641        assert_eq!(expect1, vec![220.0, 440.0, 660.0, 880.0]);
8642    }
8643
8644    /// CapturedRun executor build-out (Increment 3): capture a DECODE-SHAPED
8645    /// graph — the full dense op-set composing in one capture — and prove it
8646    /// replays bit-exactly against an independent uncaptured realize.
8647    ///
8648    /// Graph (an FFN block + norms, batch=seq=1 like real decode):
8649    ///   n1 = rms_norm(x);  u = n1 · w_up;  s = silu(u);
8650    /// cuBLAS `gemm_dense` matmul IS graph-capturable (regression for the
8651    /// dangling-input bug that once masqueraded as "cuBLAS not replay-safe").
8652    /// Captures `y = a·w` where the caller does NOT retain `w`, FORCES the
8653    /// freed-`w` slot to be reused by garbage buffers, then replays 50× — all
8654    /// must equal the uncaptured realize. Passes iff `capture_decode` retains
8655    /// its input buffers (`CapturedDecode::retained_inputs`).
8656    #[test]
8657    #[ignore = "requires a live CUDA device"]
8658    #[cfg(feature = "cuda")]
8659    fn capture_decode_matmul_replays_bit_exact_cuda() {
8660        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8661        use fuel_ir::Shape;
8662        use fuel_memory::BackendStorage;
8663        let Ok(dev) = CudaDevice::new(0) else { return };
8664        const H: usize = 4;
8665        const F: usize = 8;
8666        let a_data: Vec<f32> = (0..H).map(|i| 0.5 + i as f32).collect();
8667        let w_data: Vec<f32> = (0..H * F).map(|i| 0.01 * (i as f32 + 1.0)).collect();
8668        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId, NodeId) {
8669            let graph = Arc::new(RwLock::new(Graph::new()));
8670            let (a, w, y) = {
8671                let mut g = graph.write().unwrap();
8672                let a = g.push(Node {
8673                    op: Op::Const,
8674                    inputs: vec![],
8675                    shape: Shape::from_dims(&[1, H]),
8676                    dtype: DType::F32,
8677                });
8678                let w = g.push(Node {
8679                    op: Op::Const,
8680                    inputs: vec![],
8681                    shape: Shape::from_dims(&[H, F]),
8682                    dtype: DType::F32,
8683                });
8684                let y = g.push(Node {
8685                    op: Op::MatMul,
8686                    inputs: vec![a, w],
8687                    shape: Shape::from_dims(&[1, F]),
8688                    dtype: DType::F32,
8689                });
8690                g.set_target_backend(y, BackendId::Cuda);
8691                (a, w, y)
8692            };
8693            (graph, a, w, y)
8694        };
8695        let up = |v: &[f32]| {
8696            let b: Vec<u8> = v.iter().flat_map(|f| f.to_le_bytes()).collect();
8697            Arc::new(RwLock::new(Storage::new(
8698                BackendStorage::Cuda(CudaStorageBytes::from_cpu_bytes(&dev, &b).unwrap()),
8699                DType::F32,
8700            )))
8701        };
8702        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8703            let g = arc.read().unwrap();
8704            let BackendStorage::Cuda(c) = &g.inner else {
8705                panic!("not cuda")
8706            };
8707            c.to_cpu_bytes()
8708                .unwrap()
8709                .chunks_exact(4)
8710                .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
8711                .collect()
8712        };
8713        // Reference (uncaptured).
8714        let (gr, ar, wr, yr) = build();
8715        let mut insr = StorageCache::new();
8716        insr.insert(ar, up(&a_data));
8717        insr.insert(wr, up(&w_data));
8718        let (refarc, _) = PipelinedExecutor::realize(gr, yr, insr).unwrap();
8719        let expect = read(&refarc);
8720        // Capture (a + w NOT retained by caller).
8721        let (graph, a, w, y) = build();
8722        let mut inputs = StorageCache::new();
8723        inputs.insert(a, up(&a_data));
8724        inputs.insert(w, up(&w_data));
8725        let captured =
8726            PipelinedExecutor::capture_decode(Arc::clone(&graph), y, inputs, SymEnv::default())
8727                .expect("capture");
8728        assert_eq!(read(&captured.output), expect, "warm result after capture");
8729        // FORCE freed-memory reuse: same-size (H*F) garbage buffers. If `w`
8730        // were dangling, replay would read 999.0s.
8731        let mut squatters = Vec::new();
8732        for _ in 0..8 {
8733            let g: Vec<u8> = (0..H * F).flat_map(|_| 999.0f32.to_le_bytes()).collect();
8734            squatters.push(CudaStorageBytes::from_cpu_bytes(&dev, &g).unwrap());
8735        }
8736        dev.synchronize().unwrap();
8737        let mut bad = 0usize;
8738        for _ in 0..50 {
8739            captured.run.replay(&dev).unwrap();
8740            dev.synchronize().unwrap();
8741            if read(&captured.output) != expect {
8742                bad += 1;
8743            }
8744        }
8745        assert_eq!(
8746            bad, 0,
8747            "cuBLAS matmul capture replays bit-exact ({bad}/50 wrong)"
8748        );
8749    }
8750
8751    /// `Op::MulScalar` / `OpKind::Affine` (the `1/√d` attention scale) is
8752    /// capture-safe (write-into variant + forced-reuse regression).
8753    #[test]
8754    #[ignore = "requires a live CUDA device"]
8755    #[cfg(feature = "cuda")]
8756    fn capture_decode_affine_replays_bit_exact_cuda() {
8757        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8758        use fuel_ir::Shape;
8759        use fuel_memory::BackendStorage;
8760        let Ok(dev) = CudaDevice::new(0) else { return };
8761        const N: usize = 6;
8762        let x_data: Vec<f32> = (0..N).map(|i| 1.0 + i as f32).collect();
8763        let expect: Vec<f32> = x_data.iter().map(|v| v * 0.5).collect();
8764        let graph = Arc::new(RwLock::new(Graph::new()));
8765        let (x, y) = {
8766            let mut g = graph.write().unwrap();
8767            let x = g.push(Node {
8768                op: Op::Const,
8769                inputs: vec![],
8770                shape: Shape::from_dims(&[1, N]),
8771                dtype: DType::F32,
8772            });
8773            let y = g.push(Node {
8774                op: Op::MulScalar(0.5),
8775                inputs: vec![x],
8776                shape: Shape::from_dims(&[1, N]),
8777                dtype: DType::F32,
8778            });
8779            g.set_target_backend(y, BackendId::Cuda);
8780            (x, y)
8781        };
8782        let up = |v: &[f32]| {
8783            let b: Vec<u8> = v.iter().flat_map(|f| f.to_le_bytes()).collect();
8784            Arc::new(RwLock::new(Storage::new(
8785                BackendStorage::Cuda(CudaStorageBytes::from_cpu_bytes(&dev, &b).unwrap()),
8786                DType::F32,
8787            )))
8788        };
8789        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8790            let g = arc.read().unwrap();
8791            let BackendStorage::Cuda(c) = &g.inner else {
8792                panic!("not cuda")
8793            };
8794            c.to_cpu_bytes()
8795                .unwrap()
8796                .chunks_exact(4)
8797                .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
8798                .collect()
8799        };
8800        let mut inputs = StorageCache::new();
8801        inputs.insert(x, up(&x_data));
8802        let captured =
8803            PipelinedExecutor::capture_decode(Arc::clone(&graph), y, inputs, SymEnv::default())
8804                .expect("capture");
8805        assert_eq!(read(&captured.output), expect, "warm result after capture");
8806        let mut sq = Vec::new();
8807        for _ in 0..8 {
8808            let g: Vec<u8> = (0..N).flat_map(|_| 999.0f32.to_le_bytes()).collect();
8809            sq.push(CudaStorageBytes::from_cpu_bytes(&dev, &g).unwrap());
8810        }
8811        dev.synchronize().unwrap();
8812        let mut bad = 0usize;
8813        for _ in 0..50 {
8814            captured.run.replay(&dev).unwrap();
8815            dev.synchronize().unwrap();
8816            if read(&captured.output) != expect {
8817                bad += 1;
8818            }
8819        }
8820        assert_eq!(bad, 0, "affine capture replays bit-exact ({bad}/50 wrong)");
8821    }
8822
8823    /// `index_select` (embedding lookup) IS graph-capturable (regression for
8824    /// the dangling-input bug that once looked like "element 0 dropped on
8825    /// replay"). Captures `emb = index_select(wte, tok)` with `wte` NOT
8826    /// retained by the caller, FORCES the freed-`wte` slot to be reused by
8827    /// garbage buffers, then replays 50× — all must be `[1,2,3,4]`. Passes iff
8828    /// `capture_decode` retains its input buffers.
8829    #[test]
8830    #[ignore = "requires a live CUDA device"]
8831    #[cfg(feature = "cuda")]
8832    fn capture_decode_index_select_replays_bit_exact_cuda() {
8833        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8834        use fuel_ir::Shape;
8835        use fuel_memory::BackendStorage;
8836        let Ok(dev) = CudaDevice::new(0) else { return };
8837        const V: usize = 3;
8838        const H: usize = 4;
8839        let wte_data: Vec<f32> = (0..V)
8840            .flat_map(|v| (0..H).map(move |c| 1.0 + 10.0 * v as f32 + c as f32))
8841            .collect();
8842        let graph = Arc::new(RwLock::new(Graph::new()));
8843        let (tok, wte, emb) = {
8844            let mut g = graph.write().unwrap();
8845            let tok = g.push(Node {
8846                op: Op::Const,
8847                inputs: vec![],
8848                shape: Shape::from_dims(&[1]),
8849                dtype: DType::U32,
8850            });
8851            let wte = g.push(Node {
8852                op: Op::Const,
8853                inputs: vec![],
8854                shape: Shape::from_dims(&[V, H]),
8855                dtype: DType::F32,
8856            });
8857            let emb = g.push(Node {
8858                op: Op::IndexSelect { dim: 0 },
8859                inputs: vec![wte, tok],
8860                shape: Shape::from_dims(&[1, H]),
8861                dtype: DType::F32,
8862            });
8863            g.set_target_backend(emb, BackendId::Cuda);
8864            (tok, wte, emb)
8865        };
8866        let up_f32 = |v: &[f32]| {
8867            let b: Vec<u8> = v.iter().flat_map(|f| f.to_le_bytes()).collect();
8868            Arc::new(RwLock::new(Storage::new(
8869                BackendStorage::Cuda(CudaStorageBytes::from_cpu_bytes(&dev, &b).unwrap()),
8870                DType::F32,
8871            )))
8872        };
8873        let up_u32 = |v: &[u32]| {
8874            let b: Vec<u8> = v.iter().flat_map(|x| x.to_le_bytes()).collect();
8875            Arc::new(RwLock::new(Storage::new(
8876                BackendStorage::Cuda(CudaStorageBytes::from_cpu_bytes(&dev, &b).unwrap()),
8877                DType::U32,
8878            )))
8879        };
8880        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8881            let g = arc.read().unwrap();
8882            let BackendStorage::Cuda(c) = &g.inner else {
8883                panic!("not cuda")
8884            };
8885            c.to_cpu_bytes()
8886                .unwrap()
8887                .chunks_exact(4)
8888                .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
8889                .collect()
8890        };
8891        let tok_arc = up_u32(&[0]);
8892        let mut inputs = StorageCache::new();
8893        inputs.insert(tok, tok_arc.clone());
8894        inputs.insert(wte, up_f32(&wte_data));
8895        let captured =
8896            PipelinedExecutor::capture_decode(Arc::clone(&graph), emb, inputs, SymEnv::default())
8897                .expect("capture");
8898        assert_eq!(
8899            read(&captured.output),
8900            vec![1.0, 2.0, 3.0, 4.0],
8901            "warm result after capture"
8902        );
8903        // FORCE freed-memory reuse: same-size (V*H) garbage buffers reclaim
8904        // `wte`'s slot if it were dangling — replay would then read 999.0s.
8905        let mut squatters = Vec::new();
8906        for _ in 0..8 {
8907            let g: Vec<u8> = (0..V * H).flat_map(|_| 999.0f32.to_le_bytes()).collect();
8908            squatters.push(CudaStorageBytes::from_cpu_bytes(&dev, &g).unwrap());
8909        }
8910        dev.synchronize().unwrap();
8911        let mut bad = 0usize;
8912        for _ in 0..50 {
8913            captured.run.replay(&dev).unwrap();
8914            dev.synchronize().unwrap();
8915            if read(&captured.output) != vec![1.0, 2.0, 3.0, 4.0] {
8916                bad += 1;
8917            }
8918        }
8919        assert_eq!(
8920            bad, 0,
8921            "index_select capture replays bit-exact ({bad}/50 wrong)"
8922        );
8923    }
8924
8925    ///   n1 = rms_norm(x);  s = silu(n1);  p = softmax(s);
8926    ///   r  = p + x;  n2 = rms_norm(r);  y = n2 + x
8927    /// Exercises rms_norm (×2 — proves the per-device RMS workspace is reused
8928    /// across sequential norms inside ONE captured graph), silu + softmax
8929    /// (write-into), and residual adds through the persistent-output capture
8930    /// path. Verified across two input value-sets (robust, not luck).
8931    ///
8932    /// Deliberately EXCLUDES matmul (cuBLAS not graph-replay-safe) and
8933    /// index_select (its host-side shape/stride arrays dangle under capture —
8934    /// proven to mis-replay). Both are surfaced `capture_decode` gaps, not
8935    /// silent mis-replays. See `op_kind_is_capture_writeinto`.
8936    #[test]
8937    #[ignore = "requires a live CUDA device"]
8938    #[cfg(feature = "cuda")]
8939    fn capture_decode_norm_silu_softmax_replays_bit_exact_cuda() {
8940        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8941        use fuel_graph::registry::{FusedOpParams, FusedOps};
8942        use fuel_ir::Shape;
8943        use fuel_memory::BackendStorage;
8944
8945        let Ok(dev) = CudaDevice::new(0) else {
8946            return fuel_test_support::hardware::skip(
8947                fuel_test_support::hardware::Hardware::Cuda,
8948                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
8949            );
8950        };
8951        const H: usize = 6;
8952        let eps = 1e-5f64;
8953
8954        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId) {
8955            let graph = Arc::new(RwLock::new(Graph::new()));
8956            let (x, y) = {
8957                let mut g = graph.write().unwrap();
8958                let mk = |g: &mut Graph, op: Op, ins: Vec<NodeId>, dims: &[usize]| {
8959                    g.push(Node {
8960                        op,
8961                        inputs: ins,
8962                        shape: Shape::from_dims(dims),
8963                        dtype: DType::F32,
8964                    })
8965                };
8966                let rms = || {
8967                    Op::Fused(
8968                        FusedOps::RMS_NORM_LAST_DIM,
8969                        FusedOpParams::RmsNormLastDim { eps },
8970                    )
8971                };
8972                let sm = || Op::Fused(FusedOps::SOFTMAX_LAST_DIM, FusedOpParams::SoftmaxLastDim);
8973                let x = mk(&mut g, Op::Const, vec![], &[1, H]);
8974                let n1 = mk(&mut g, rms(), vec![x], &[1, H]);
8975                let s = mk(&mut g, Op::Silu, vec![n1], &[1, H]);
8976                let p = mk(&mut g, sm(), vec![s], &[1, H]);
8977                let r = mk(&mut g, Op::Add, vec![p, x], &[1, H]);
8978                let n2 = mk(&mut g, rms(), vec![r], &[1, H]);
8979                let y = mk(&mut g, Op::Add, vec![n2, x], &[1, H]);
8980                for id in [n1, s, p, r, n2, y] {
8981                    g.set_target_backend(id, BackendId::Cuda);
8982                }
8983                (x, y)
8984            };
8985            (graph, x, y)
8986        };
8987
8988        let up = |v: &[f32]| -> Arc<RwLock<Storage>> {
8989            let cb = CudaStorageBytes::from_cpu_bytes(&dev, bytemuck::cast_slice(v)).expect("h2d");
8990            Arc::new(RwLock::new(Storage::new(
8991                BackendStorage::Cuda(cb),
8992                DType::F32,
8993            )))
8994        };
8995        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8996            let g = arc.read().unwrap();
8997            let BackendStorage::Cuda(c) = &g.inner else {
8998                panic!("not cuda")
8999            };
9000            bytemuck::cast_slice(&c.to_cpu_bytes().expect("d2h")).to_vec()
9001        };
9002
9003        let x_data: Vec<f32> = (0..H).map(|c| 0.1 * (c as f32 + 1.0)).collect();
9004        let x_arc = up(&x_data);
9005        let (graph, x, y) = build();
9006        let mut inputs = StorageCache::new();
9007        inputs.insert(x, x_arc.clone());
9008
9009        let captured =
9010            PipelinedExecutor::capture_decode(Arc::clone(&graph), y, inputs, SymEnv::default())
9011                .expect("capture_decode norm/silu/softmax");
9012
9013        let realize_ref = |xv: &[f32]| -> Vec<f32> {
9014            let (g, xr, yr) = build();
9015            let mut ins = StorageCache::new();
9016            ins.insert(xr, up(xv));
9017            let (arc, _) = PipelinedExecutor::realize(g, yr, ins).expect("ref realize");
9018            read(&arc)
9019        };
9020        let expect0 = realize_ref(&x_data);
9021
9022        // (1) after capture the output holds the warm result.
9023        assert_eq!(read(&captured.output), expect0, "warm result after capture");
9024        // (2) replay reproduces bit-exactly (incl. RMS workspace reuse on replay).
9025        captured.run.replay(&dev).expect("replay");
9026        dev.synchronize().expect("sync");
9027        assert_eq!(read(&captured.output), expect0, "replay reproduces result");
9028
9029        // (3) overwrite x in place, replay -> matches uncaptured realize (a
9030        //     DIFFERENT value-set — so the chain is robust, not input-lucky).
9031        let x2: Vec<f32> = (0..H).map(|c| 0.3 * (c as f32 + 1.0)).collect();
9032        {
9033            let g = x_arc.read().unwrap();
9034            let BackendStorage::Cuda(c) = &g.inner else {
9035                panic!("x not cuda")
9036            };
9037            c.write_from_host(bytemuck::cast_slice(&x2))
9038                .expect("in-place H2D");
9039        }
9040        captured.run.replay(&dev).expect("replay 2");
9041        dev.synchronize().expect("sync 2");
9042        assert_eq!(
9043            read(&captured.output),
9044            realize_ref(&x2),
9045            "replay after x update matches realize"
9046        );
9047    }
9048
9049    /// CapturedRun executor build-out (Increment 4b-γ): make `ContiguizeOf`
9050    /// (a non-contiguous reshape after `Permute` — the real decode graph's
9051    /// attention-merge reshape shape) AND a 2-input `Op::Concat` (the shape
9052    /// RoPE's CUDA decomposition emits for its rotate-half) BOTH
9053    /// capture-safe in ONE graph, so the crux 4b-γ exists for — allocation
9054    /// of an INTERMEDIATE, non-final buffer inside a capture scope — is
9055    /// actually exercised, not just each gap in isolation.
9056    ///
9057    /// Graph: `x [2,3,4] --Permute[1,0,2]--> [3,2,4]` (non-contiguous)
9058    /// `--Reshape[3,8]--> r` (`ContiguizeOf`, MUST allocate: its input is
9059    /// non-contiguous) `--Concat(dim=1, with b [3,8])--> y [3,16]` (target).
9060    #[test]
9061    #[ignore = "requires a live CUDA device"]
9062    #[cfg(feature = "cuda")]
9063    fn capture_decode_contiguize_then_concat_replays_bit_exact_cuda() {
9064        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
9065        use fuel_ir::Shape;
9066        use fuel_memory::BackendStorage;
9067
9068        let Ok(dev) = CudaDevice::new(0) else {
9069            return fuel_test_support::hardware::skip(
9070                fuel_test_support::hardware::Hardware::Cuda,
9071                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
9072            );
9073        };
9074
9075        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId, NodeId) {
9076            let graph = Arc::new(RwLock::new(Graph::new()));
9077            let (x, b, y) = {
9078                let mut g = graph.write().unwrap();
9079                let x = g.push(Node {
9080                    op: Op::Const,
9081                    inputs: vec![],
9082                    shape: Shape::from_dims(&[2, 3, 4]),
9083                    dtype: DType::F32,
9084                });
9085                let p = g.push(Node {
9086                    op: Op::Permute(vec![1, 0, 2]),
9087                    inputs: vec![x],
9088                    shape: Shape::from_dims(&[3, 2, 4]),
9089                    dtype: DType::F32,
9090                });
9091                let r = g.push(Node {
9092                    op: Op::Reshape(Shape::from_dims(&[3, 8])),
9093                    inputs: vec![p],
9094                    shape: Shape::from_dims(&[3, 8]),
9095                    dtype: DType::F32,
9096                });
9097                let b = g.push(Node {
9098                    op: Op::Const,
9099                    inputs: vec![],
9100                    shape: Shape::from_dims(&[3, 8]),
9101                    dtype: DType::F32,
9102                });
9103                let y = g.push(Node {
9104                    op: Op::Concat { dim: 1 },
9105                    inputs: vec![r, b],
9106                    shape: Shape::from_dims(&[3, 16]),
9107                    dtype: DType::F32,
9108                });
9109                g.set_target_backend(p, BackendId::Cuda);
9110                g.set_target_backend(r, BackendId::Cuda);
9111                g.set_target_backend(y, BackendId::Cuda);
9112                (x, b, y)
9113            };
9114            (graph, x, b, y)
9115        };
9116
9117        let up = |v: &[f32]| -> Arc<RwLock<Storage>> {
9118            let cb = CudaStorageBytes::from_cpu_bytes(&dev, bytemuck::cast_slice(v)).expect("h2d");
9119            Arc::new(RwLock::new(Storage::new(
9120                BackendStorage::Cuda(cb),
9121                DType::F32,
9122            )))
9123        };
9124        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9125            let g = arc.read().unwrap();
9126            let BackendStorage::Cuda(c) = &g.inner else {
9127                panic!("not cuda")
9128            };
9129            bytemuck::cast_slice(&c.to_cpu_bytes().expect("d2h")).to_vec()
9130        };
9131
9132        let x_data: Vec<f32> = (0..24).map(|i| i as f32).collect();
9133        let b_data: Vec<f32> = (0..24).map(|i| 100.0 + i as f32).collect();
9134        let x_arc = up(&x_data);
9135        let (graph, x, b, y) = build();
9136        let mut inputs = StorageCache::new();
9137        inputs.insert(x, x_arc.clone());
9138        // `b` deliberately NOT retained by a local variable — forces
9139        // reliance on `capture_decode`'s own `retained_inputs`, mirroring
9140        // the matmul/index_select regression precedent.
9141        inputs.insert(b, up(&b_data));
9142
9143        let captured =
9144            PipelinedExecutor::capture_decode(Arc::clone(&graph), y, inputs, SymEnv::default())
9145                .expect("capture_decode contiguize+concat");
9146
9147        let realize_ref = |xv: &[f32], bv: &[f32]| -> Vec<f32> {
9148            let (g, xr, br, yr) = build();
9149            let mut ins = StorageCache::new();
9150            ins.insert(xr, up(xv));
9151            ins.insert(br, up(bv));
9152            let (arc, _) = PipelinedExecutor::realize(g, yr, ins).expect("ref realize");
9153            read(&arc)
9154        };
9155        let expect0 = realize_ref(&x_data, &b_data);
9156
9157        // (1) warm-run result sits in the captured output buffer (capture
9158        //     RECORDS launches, it does not execute them at capture time).
9159        assert_eq!(read(&captured.output), expect0, "warm result after capture");
9160
9161        // (2) replay TWICE with unchanged inputs — proves the fixed-address
9162        //     reuse (both the ContiguizeOf intermediate and the Concat
9163        //     output) holds across multiple replay() calls, not just one.
9164        for i in 0..2 {
9165            captured
9166                .run
9167                .replay(&dev)
9168                .unwrap_or_else(|e| panic!("replay {i}: {e:?}"));
9169            dev.synchronize().expect("sync");
9170            assert_eq!(
9171                read(&captured.output),
9172                expect0,
9173                "replay {i} reproduces result"
9174            );
9175        }
9176
9177        // (3) overwrite x in place (a DIFFERENT value-set), replay again ->
9178        //     the new result flows from the FIXED input address, through
9179        //     the fixed ContiguizeOf intermediate, into the fixed Concat
9180        //     output — matches an independent uncaptured realize.
9181        let x2: Vec<f32> = (0..24).map(|i| 1000.0 + i as f32).collect();
9182        {
9183            let g = x_arc.read().unwrap();
9184            let BackendStorage::Cuda(c) = &g.inner else {
9185                panic!("x not cuda")
9186            };
9187            c.write_from_host(bytemuck::cast_slice(&x2))
9188                .expect("in-place H2D");
9189        }
9190        captured.run.replay(&dev).expect("replay 3");
9191        dev.synchronize().expect("sync 3");
9192        assert_eq!(
9193            read(&captured.output),
9194            realize_ref(&x2, &b_data),
9195            "replay after x update matches independent uncaptured realize"
9196        );
9197    }
9198
9199    /// CapturedRun executor build-out (Increment 4b-ζ): a same-device
9200    /// CUDA→CUDA `Op::Copy` — the shape `insert_safety_copies` emits for its
9201    /// aliasing-hazard snapshots in the real Llama decode graph — is
9202    /// capture-safe via `copy_from_cuda_wrapper`'s write-into
9203    /// `BackendStorage::Cuda` branch (`CudaStorageBytes::copy_from_device`).
9204    ///
9205    /// Graph: `x [2,4]`, `b [2,4]` --Copy{target: Cuda{0}}--> `c` (same-device
9206    /// snapshot of `x`) --Add(c, b)--> `y`. Capture, replay twice unchanged,
9207    /// then update `x` in place and replay again — every step must match an
9208    /// independent uncaptured `realize`.
9209    #[test]
9210    #[ignore = "requires a live CUDA device"]
9211    #[cfg(feature = "cuda")]
9212    fn capture_decode_same_device_copy_replays_bit_exact_cuda() {
9213        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
9214        use fuel_ir::Shape;
9215        use fuel_memory::BackendStorage;
9216
9217        let Ok(dev) = CudaDevice::new(0) else {
9218            return fuel_test_support::hardware::skip(
9219                fuel_test_support::hardware::Hardware::Cuda,
9220                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
9221            );
9222        };
9223
9224        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId, NodeId) {
9225            let graph = Arc::new(RwLock::new(Graph::new()));
9226            let (x, b, y) = {
9227                let mut g = graph.write().unwrap();
9228                let x = g.push(Node {
9229                    op: Op::Const,
9230                    inputs: vec![],
9231                    shape: Shape::from_dims(&[2, 4]),
9232                    dtype: DType::F32,
9233                });
9234                let b = g.push(Node {
9235                    op: Op::Const,
9236                    inputs: vec![],
9237                    shape: Shape::from_dims(&[2, 4]),
9238                    dtype: DType::F32,
9239                });
9240                // Same-device CUDA->CUDA copy — the write-into-safe case.
9241                let c = g.push(Node {
9242                    op: Op::Copy {
9243                        target: DeviceLocation::Cuda { gpu_id: 0 },
9244                    },
9245                    inputs: vec![x],
9246                    shape: Shape::from_dims(&[2, 4]),
9247                    dtype: DType::F32,
9248                });
9249                let y = g.push(Node {
9250                    op: Op::Add,
9251                    inputs: vec![c, b],
9252                    shape: Shape::from_dims(&[2, 4]),
9253                    dtype: DType::F32,
9254                });
9255                // Copy's target_backend = SOURCE backend (x is Cuda-resident).
9256                g.set_target_backend(c, BackendId::Cuda);
9257                g.set_target_backend(y, BackendId::Cuda);
9258                (x, b, y)
9259            };
9260            (graph, x, b, y)
9261        };
9262
9263        let up = |v: &[f32]| -> Arc<RwLock<Storage>> {
9264            let cb = CudaStorageBytes::from_cpu_bytes(&dev, bytemuck::cast_slice(v)).expect("h2d");
9265            Arc::new(RwLock::new(Storage::new(
9266                BackendStorage::Cuda(cb),
9267                DType::F32,
9268            )))
9269        };
9270        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9271            let g = arc.read().unwrap();
9272            let BackendStorage::Cuda(c) = &g.inner else {
9273                panic!("not cuda")
9274            };
9275            bytemuck::cast_slice(&c.to_cpu_bytes().expect("d2h")).to_vec()
9276        };
9277
9278        let x_data: Vec<f32> = (0..8).map(|i| i as f32).collect();
9279        let b_data: Vec<f32> = (0..8).map(|i| 100.0 + i as f32).collect();
9280        let x_arc = up(&x_data);
9281        let (graph, x, b, y) = build();
9282        let mut inputs = StorageCache::new();
9283        inputs.insert(x, x_arc.clone());
9284        // `b` deliberately NOT retained by a local variable — forces
9285        // reliance on `capture_decode`'s own `retained_inputs`.
9286        inputs.insert(b, up(&b_data));
9287
9288        let captured =
9289            PipelinedExecutor::capture_decode(Arc::clone(&graph), y, inputs, SymEnv::default())
9290                .expect("capture_decode same-device copy");
9291
9292        let realize_ref = |xv: &[f32], bv: &[f32]| -> Vec<f32> {
9293            let (g, xr, br, yr) = build();
9294            let mut ins = StorageCache::new();
9295            ins.insert(xr, up(xv));
9296            ins.insert(br, up(bv));
9297            let (arc, _) = PipelinedExecutor::realize(g, yr, ins).expect("ref realize");
9298            read(&arc)
9299        };
9300        let expect0 = realize_ref(&x_data, &b_data);
9301
9302        // (1) warm-run result sits in the captured output buffer.
9303        assert_eq!(read(&captured.output), expect0, "warm result after capture");
9304
9305        // (2) replay TWICE with unchanged inputs — the Copy's write-into
9306        //     destination buffer must stay bit-exact across replays.
9307        for i in 0..2 {
9308            captured
9309                .run
9310                .replay(&dev)
9311                .unwrap_or_else(|e| panic!("replay {i}: {e:?}"));
9312            dev.synchronize().expect("sync");
9313            assert_eq!(
9314                read(&captured.output),
9315                expect0,
9316                "replay {i} reproduces result"
9317            );
9318        }
9319
9320        // (3) overwrite x in place (a DIFFERENT value-set), replay again ->
9321        //     the Copy re-runs on the fixed input address into its fixed
9322        //     destination buffer -> matches an independent uncaptured realize.
9323        let x2: Vec<f32> = (0..8).map(|i| 1000.0 + i as f32).collect();
9324        {
9325            let g = x_arc.read().unwrap();
9326            let BackendStorage::Cuda(c) = &g.inner else {
9327                panic!("x not cuda")
9328            };
9329            c.write_from_host(bytemuck::cast_slice(&x2))
9330                .expect("in-place H2D");
9331        }
9332        captured.run.replay(&dev).expect("replay 3");
9333        dev.synchronize().expect("sync 3");
9334        assert_eq!(
9335            read(&captured.output),
9336            realize_ref(&x2, &b_data),
9337            "replay after x update matches independent uncaptured realize"
9338        );
9339    }
9340
9341    /// CapturedRun executor build-out (Increment 4b-ζ): a genuinely
9342    /// cross-device `Op::Copy` (D2H — `target: DeviceLocation::Cpu` from a
9343    /// CUDA-resident source) must still be REJECTED by `capture_decode`'s
9344    /// validation loop — a host round-trip can never be part of a CUDA
9345    /// graph capture. Fast check: no replay, just confirm the typed `Err`.
9346    #[test]
9347    #[ignore = "requires a live CUDA device"]
9348    #[cfg(feature = "cuda")]
9349    fn capture_decode_rejects_cross_device_copy_cuda() {
9350        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
9351        use fuel_ir::Shape;
9352        use fuel_memory::BackendStorage;
9353
9354        let Ok(dev) = CudaDevice::new(0) else {
9355            return fuel_test_support::hardware::skip(
9356                fuel_test_support::hardware::Hardware::Cuda,
9357                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
9358            );
9359        };
9360
9361        let graph = Arc::new(RwLock::new(Graph::new()));
9362        let (x, y) = {
9363            let mut g = graph.write().unwrap();
9364            let x = g.push(Node {
9365                op: Op::Const,
9366                inputs: vec![],
9367                shape: Shape::from_dims(&[2, 4]),
9368                dtype: DType::F32,
9369            });
9370            // Genuinely cross-device: D2H.
9371            let y = g.push(Node {
9372                op: Op::Copy {
9373                    target: DeviceLocation::Cpu,
9374                },
9375                inputs: vec![x],
9376                shape: Shape::from_dims(&[2, 4]),
9377                dtype: DType::F32,
9378            });
9379            g.set_target_backend(y, BackendId::Cuda); // source backend = Cuda
9380            (x, y)
9381        };
9382
9383        let x_data: Vec<f32> = (0..8).map(|i| i as f32).collect();
9384        let cb =
9385            CudaStorageBytes::from_cpu_bytes(&dev, bytemuck::cast_slice(&x_data)).expect("h2d");
9386        let x_arc = Arc::new(RwLock::new(Storage::new(
9387            BackendStorage::Cuda(cb),
9388            DType::F32,
9389        )));
9390        let mut inputs = StorageCache::new();
9391        inputs.insert(x, x_arc);
9392
9393        let result = PipelinedExecutor::capture_decode(graph, y, inputs, SymEnv::default());
9394        let msg = match result {
9395            Ok(_) => panic!("D2H Op::Copy must be rejected by capture_decode"),
9396            Err(e) => e.to_string(),
9397        };
9398        assert!(
9399            msg.contains("cross-device"),
9400            "error should describe the cross-device rejection: {msg}"
9401        );
9402    }
9403
9404    /// CapturedDecodeSession (Increment 4a): drive the warm→capture→replay
9405    /// orchestration over MANY tokens on a synthetic decode-shaped session —
9406    /// the real per-token decode pattern. Capture once, then per token
9407    /// H2D-update the fixed input buffer IN PLACE + replay, asserting each
9408    /// token's output is bit-exact against an independent uncaptured realize.
9409    /// A kernel-agnostic proof of the state machine + fixed-buffer mechanics
9410    /// (matmul + index_select excluded pending baracuda capture-safe kernels).
9411    #[test]
9412    #[ignore = "requires a live CUDA device"]
9413    #[cfg(feature = "cuda")]
9414    fn captured_decode_session_replays_many_tokens_cuda() {
9415        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
9416        use fuel_graph::registry::{FusedOpParams, FusedOps};
9417        use fuel_ir::Shape;
9418        use fuel_memory::BackendStorage;
9419
9420        let Ok(dev) = CudaDevice::new(0) else {
9421            return fuel_test_support::hardware::skip(
9422                fuel_test_support::hardware::Hardware::Cuda,
9423                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
9424            );
9425        };
9426        const H: usize = 6;
9427        let eps = 1e-5f64;
9428
9429        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId) {
9430            let graph = Arc::new(RwLock::new(Graph::new()));
9431            let (x, y) = {
9432                let mut g = graph.write().unwrap();
9433                let mk = |g: &mut Graph, op: Op, ins: Vec<NodeId>, dims: &[usize]| {
9434                    g.push(Node {
9435                        op,
9436                        inputs: ins,
9437                        shape: Shape::from_dims(dims),
9438                        dtype: DType::F32,
9439                    })
9440                };
9441                let rms = || {
9442                    Op::Fused(
9443                        FusedOps::RMS_NORM_LAST_DIM,
9444                        FusedOpParams::RmsNormLastDim { eps },
9445                    )
9446                };
9447                let sm = || Op::Fused(FusedOps::SOFTMAX_LAST_DIM, FusedOpParams::SoftmaxLastDim);
9448                let x = mk(&mut g, Op::Const, vec![], &[1, H]);
9449                let n1 = mk(&mut g, rms(), vec![x], &[1, H]);
9450                let s = mk(&mut g, Op::Silu, vec![n1], &[1, H]);
9451                let p = mk(&mut g, sm(), vec![s], &[1, H]);
9452                let r = mk(&mut g, Op::Add, vec![p, x], &[1, H]);
9453                let n2 = mk(&mut g, rms(), vec![r], &[1, H]);
9454                let y = mk(&mut g, Op::Add, vec![n2, x], &[1, H]);
9455                for id in [n1, s, p, r, n2, y] {
9456                    g.set_target_backend(id, BackendId::Cuda);
9457                }
9458                (x, y)
9459            };
9460            (graph, x, y)
9461        };
9462        let up = |v: &[f32]| -> Arc<RwLock<Storage>> {
9463            let cb = CudaStorageBytes::from_cpu_bytes(&dev, bytemuck::cast_slice(v)).expect("h2d");
9464            Arc::new(RwLock::new(Storage::new(
9465                BackendStorage::Cuda(cb),
9466                DType::F32,
9467            )))
9468        };
9469        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9470            let g = arc.read().unwrap();
9471            let BackendStorage::Cuda(c) = &g.inner else {
9472                panic!("not cuda")
9473            };
9474            bytemuck::cast_slice(&c.to_cpu_bytes().expect("d2h")).to_vec()
9475        };
9476        let realize_ref = |xv: &[f32]| -> Vec<f32> {
9477            let (g, xr, yr) = build();
9478            let mut ins = StorageCache::new();
9479            ins.insert(xr, up(xv));
9480            let (arc, _) = PipelinedExecutor::realize(g, yr, ins).expect("ref realize");
9481            read(&arc)
9482        };
9483
9484        // 5 distinct "tokens" (distinct per-token input value-sets).
9485        let tokens: Vec<Vec<f32>> = (0..5)
9486            .map(|t| {
9487                (0..H)
9488                    .map(|c| 0.1 * (t as f32 + 1.0) * (c as f32 + 1.0))
9489                    .collect()
9490            })
9491            .collect();
9492
9493        // Capture ONCE against token 0's fixed input buffer.
9494        let x_arc = up(&tokens[0]);
9495        let (graph, x, y) = build();
9496        let mut inputs = StorageCache::new();
9497        inputs.insert(x, x_arc.clone());
9498        let session =
9499            CapturedDecodeSession::capture(Arc::clone(&graph), y, inputs, &[x], SymEnv::default())
9500                .expect("capture session");
9501
9502        // Warm result (token 0) already sits in the output buffer.
9503        assert_eq!(
9504            read(session.output()),
9505            realize_ref(&tokens[0]),
9506            "warm token 0"
9507        );
9508
9509        // The decode loop: replay every token (incl. re-replaying token 0) via
9510        // in-place H2D update of the fixed input + one graph launch.
9511        for (t, tok) in tokens.iter().enumerate() {
9512            let out = session
9513                .replay_token(&[(x, bytemuck::cast_slice(tok))])
9514                .expect("replay_token");
9515            assert_eq!(
9516                read(&out),
9517                realize_ref(tok),
9518                "replayed token {t} matches uncaptured realize"
9519            );
9520        }
9521        // Distinct tokens must give distinct outputs (live recompute, not stale).
9522        assert_ne!(
9523            realize_ref(&tokens[0]),
9524            realize_ref(&tokens[1]),
9525            "tokens must differ"
9526        );
9527    }
9528
9529    /// PR-C1 behavior contract: `realize_with_optimized_route` with an
9530    /// **empty** route (the no-pressure / no-telemetry case) is
9531    /// byte-identical to `realize_with_optimized` (arm-0). On a branchless
9532    /// graph the route has no branches to resolve, so both must produce
9533    /// the same bytes — realize is unchanged from Phase B.
9534    #[test]
9535    fn realize_with_optimized_route_empty_equals_arm0() {
9536        use crate::optimize::OptimizedGraph;
9537
9538        let build = || {
9539            let graph = Arc::new(RwLock::new(Graph::new()));
9540            let (lhs_id, rhs_id, add_id) = {
9541                let mut g = graph.write().unwrap();
9542                let lhs_id = g.push(Node {
9543                    op: Op::Const,
9544                    inputs: vec![],
9545                    shape: Shape::from_dims(&[3]),
9546                    dtype: DType::F32,
9547                });
9548                let rhs_id = g.push(Node {
9549                    op: Op::Const,
9550                    inputs: vec![],
9551                    shape: Shape::from_dims(&[3]),
9552                    dtype: DType::F32,
9553                });
9554                let add_id = g.push(Node {
9555                    op: Op::Add,
9556                    inputs: vec![lhs_id, rhs_id],
9557                    shape: Shape::from_dims(&[3]),
9558                    dtype: DType::F32,
9559                });
9560                g.set_target_backend(add_id, BackendId::Cpu);
9561                (lhs_id, rhs_id, add_id)
9562            };
9563            let mut inputs = StorageCache::new();
9564            inputs.insert(
9565                lhs_id,
9566                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9567                    1.0_f32, 2.0, 3.0,
9568                ]))),
9569            );
9570            inputs.insert(
9571                rhs_id,
9572                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9573                    10.0_f32, 20.0, 30.0,
9574                ]))),
9575            );
9576            (graph, add_id, inputs)
9577        };
9578
9579        let read_bytes = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9580            let guard = arc.read().unwrap();
9581            match &guard.inner {
9582                fuel_memory::BackendStorage::Cpu(c) => {
9583                    c.as_slice::<f32>().expect("f32 cast").to_vec()
9584                }
9585                _ => panic!("expected CPU output"),
9586            }
9587        };
9588
9589        // Stamp the fixture with the LIVE topology generation rather than a
9590        // hard-coded 0. The executor's chunk-boundary check compares the plan's
9591        // stamped generation against `topology_generation()`; a real
9592        // `OptimizedGraph` carries the generation snapshotted at optimize time
9593        // (`plan.rs` `compile_plan`, which reads it *after* the bindings table
9594        // is warm), so it already reflects every registered backend. Force
9595        // `global_bindings()` init here so any feature-gated auto-registration
9596        // has run and settled the counter before we read it — otherwise a stale
9597        // read would be bumped out from under us the first time realize warms
9598        // the bindings. Under default features this is 0; under
9599        // `--features vulkan`, `register_derived_gpu_caps` bumps it to 1.
9600        drop(global_bindings());
9601        let live_gen = crate::dispatch::topology_generation();
9602
9603        // Arm-0 path.
9604        let (g_a, add_a, in_a) = build();
9605        let opt_a = OptimizedGraph {
9606            roots: vec![add_a],
9607            generation: live_gen,
9608            placements: None,
9609            eviction: None,
9610        };
9611        let (arm0_arc, _) = PipelinedExecutor::realize_with_optimized(g_a, add_a, in_a, &opt_a)
9612            .expect("arm-0 realize");
9613        let arm0 = read_bytes(&arm0_arc);
9614
9615        // Empty-route path — must match arm-0 exactly.
9616        let (g_r, add_r, in_r) = build();
9617        let opt_r = OptimizedGraph {
9618            roots: vec![add_r],
9619            generation: live_gen,
9620            placements: None,
9621            eviction: None,
9622        };
9623        let empty_route = PickedRoute::new();
9624        let (route_arc, _) =
9625            PipelinedExecutor::realize_with_optimized_route(g_r, add_r, in_r, &opt_r, &empty_route)
9626                .expect("empty-route realize");
9627        let routed = read_bytes(&route_arc);
9628
9629        assert_eq!(arm0, vec![11.0, 22.0, 33.0]);
9630        assert_eq!(
9631            routed, arm0,
9632            "an empty route realizes byte-identically to arm-0 (Phase B contract)",
9633        );
9634    }
9635
9636    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
9637    /// §5): [`PipelinedExecutor::realize_with_optimized_picking_cached_env`]
9638    /// over a shared `order_cache` must (a) realize byte-identically to the
9639    /// uncached arm-0 path, on both the cold (empty cache) and warm
9640    /// (populated cache) call, and (b) actually populate the cache on the
9641    /// first call rather than silently never using it.
9642    #[test]
9643    fn realize_with_optimized_picking_cached_env_matches_arm0_cold_and_warm() {
9644        use crate::optimize::OptimizedGraph;
9645        use std::sync::OnceLock;
9646
9647        let build = || {
9648            let graph = Arc::new(RwLock::new(Graph::new()));
9649            let (lhs_id, rhs_id, add_id) = {
9650                let mut g = graph.write().unwrap();
9651                let lhs_id = g.push(Node {
9652                    op: Op::Const,
9653                    inputs: vec![],
9654                    shape: Shape::from_dims(&[3]),
9655                    dtype: DType::F32,
9656                });
9657                let rhs_id = g.push(Node {
9658                    op: Op::Const,
9659                    inputs: vec![],
9660                    shape: Shape::from_dims(&[3]),
9661                    dtype: DType::F32,
9662                });
9663                let add_id = g.push(Node {
9664                    op: Op::Add,
9665                    inputs: vec![lhs_id, rhs_id],
9666                    shape: Shape::from_dims(&[3]),
9667                    dtype: DType::F32,
9668                });
9669                g.set_target_backend(add_id, BackendId::Cpu);
9670                (lhs_id, rhs_id, add_id)
9671            };
9672            let mut inputs = StorageCache::new();
9673            inputs.insert(
9674                lhs_id,
9675                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9676                    1.0_f32, 2.0, 3.0,
9677                ]))),
9678            );
9679            inputs.insert(
9680                rhs_id,
9681                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9682                    10.0_f32, 20.0, 30.0,
9683                ]))),
9684            );
9685            (graph, add_id, inputs)
9686        };
9687        let read_bytes = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9688            let guard = arc.read().unwrap();
9689            match &guard.inner {
9690                fuel_memory::BackendStorage::Cpu(c) => {
9691                    c.as_slice::<f32>().expect("f32 cast").to_vec()
9692                }
9693                _ => panic!("expected CPU output"),
9694            }
9695        };
9696
9697        drop(global_bindings());
9698        let live_gen = crate::dispatch::topology_generation();
9699
9700        let (g, add, inputs) = build();
9701        let optimized = OptimizedGraph {
9702            roots: vec![add],
9703            generation: live_gen,
9704            placements: None,
9705            eviction: None,
9706        };
9707        let order_cache: OnceLock<Vec<NodeId>> = OnceLock::new();
9708        assert!(order_cache.get().is_none(), "sanity: cache starts empty");
9709
9710        // Cold call: cache miss, must compute AND populate.
9711        let (cold_arc, _) = PipelinedExecutor::realize_with_optimized_picking_cached_env(
9712            g.clone(),
9713            add,
9714            inputs,
9715            &optimized,
9716            &order_cache,
9717            None,
9718            None,
9719            SymEnv::default(),
9720        )
9721        .expect("cold cached realize");
9722        assert_eq!(read_bytes(&cold_arc), vec![11.0, 22.0, 33.0]);
9723        assert!(
9724            order_cache.get().is_some(),
9725            "the cold call must populate order_cache, not leave it empty"
9726        );
9727        let cached_order_after_cold = order_cache.get().unwrap().clone();
9728
9729        // Warm call: cache hit. Fresh inputs (same graph, new values) so the
9730        // realized OUTPUT differs from the cold call while the dispatch
9731        // ORDER (what's cached) must not change.
9732        let mut warm_inputs = StorageCache::new();
9733        warm_inputs.insert(
9734            g.read().unwrap().node(add).inputs[0],
9735            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9736                100.0_f32, 200.0, 300.0,
9737            ]))),
9738        );
9739        warm_inputs.insert(
9740            g.read().unwrap().node(add).inputs[1],
9741            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9742                1.0_f32, 2.0, 3.0,
9743            ]))),
9744        );
9745        let (warm_arc, _) = PipelinedExecutor::realize_with_optimized_picking_cached_env(
9746            g,
9747            add,
9748            warm_inputs,
9749            &optimized,
9750            &order_cache,
9751            None,
9752            None,
9753            SymEnv::default(),
9754        )
9755        .expect("warm cached realize");
9756        assert_eq!(
9757            read_bytes(&warm_arc),
9758            vec![101.0, 202.0, 303.0],
9759            "warm call must realize its OWN rebound inputs, not replay stale output",
9760        );
9761        assert_eq!(
9762            order_cache.get().unwrap(),
9763            &cached_order_after_cold,
9764            "the warm call must reuse the SAME cached order, not recompute a different one",
9765        );
9766    }
9767
9768    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
9769    /// §5), PM review question: does `OrderSource::Cached` weaken the
9770    /// existing `TopologyChanged` chunk-boundary check? No — proven at the
9771    /// unit level (not a live topology-bump integration test, deliberately:
9772    /// `bump_topology_generation()` mutates a process-wide atomic shared by
9773    /// every concurrently-running test in this binary, including the cold/
9774    /// warm cache test above, which reads it into a local at the start of
9775    /// ITS OWN body and would flake if another test's bump landed mid-call;
9776    /// introducing that cross-test hazard isn't worth it when the two arms'
9777    /// `generation_for` expressions are provably identical). `generation_for`
9778    /// is private to this module, so it's tested directly here: given the
9779    /// SAME `&OptimizedGraph`, `Cached` and `Optimized` must report the
9780    /// IDENTICAL generation — the chunk-boundary check that compares this
9781    /// value against the LIVE `topology_generation()` fires exactly the
9782    /// same way for both, so caching cannot silently skip or weaken it.
9783    #[test]
9784    fn cached_generation_for_matches_optimized_generation_for() {
9785        let optimized = OptimizedGraph {
9786            roots: vec![NodeId(0)],
9787            generation: 42,
9788            placements: None,
9789            eviction: None,
9790        };
9791        let order_cache: std::sync::OnceLock<Vec<NodeId>> = std::sync::OnceLock::new();
9792
9793        let optimized_gen = generation_for(&OrderSource::Optimized {
9794            optimized: &optimized,
9795            route: None,
9796        });
9797        let cached_gen = generation_for(&OrderSource::Cached {
9798            optimized: &optimized,
9799            order_cache: &order_cache,
9800        });
9801        assert_eq!(
9802            optimized_gen,
9803            Some(42),
9804            "sanity: Optimized reports the OptimizedGraph's own generation",
9805        );
9806        assert_eq!(
9807            cached_gen, optimized_gen,
9808            "Cached must report the SAME generation as Optimized for the same \
9809             OptimizedGraph -- the TopologyChanged check cannot tell the two apart, \
9810             by construction, so caching cannot silently weaken it",
9811        );
9812    }
9813
9814    /// **PR-C3 reorder-invariance gate (CPU, runnable — ORDERING level).**
9815    /// The auto-overlap reorder is a HINT: it changes only *which order*
9816    /// independent device runs dispatch in, never *which* nodes run nor the
9817    /// result. The byte-identical-OUTPUT proof is necessarily LIVE (the
9818    /// reorder fires only on a ≥2-device graph, which needs ≥2 real backends
9819    /// to realize — see `cuda_vulkan_multidevice_realize_live`'s
9820    /// `[22,86,192,340]` oracle, which now flows through this reorder, plus
9821    /// the dual-GPU `cuda_vulkan_overlap_bench_live` arbitrary-graph
9822    /// auto-overlap gate). THIS test proves the ordering-level invariant on a
9823    /// CPU-only path: the C3 reorder of a two-device graph is a valid
9824    /// topological **permutation** of the un-reordered topo order — same node
9825    /// multiset, every node still after its inputs — that genuinely DIFFERS
9826    /// from the un-reordered order (so the reorder fired). Because the
9827    /// executor caches each node's result and every op is deterministic,
9828    /// realizing any valid topological order yields identical bytes; this
9829    /// test guards the precondition (a valid permutation) that makes that so.
9830    #[test]
9831    fn c3_reorder_is_a_valid_topo_permutation() {
9832        // Two INDEPENDENT device sub-chains over distinct consts reconverging
9833        // at a final CUDA add, the Vulkan root bridged to CUDA by an explicit
9834        // Op::Copy (a residency seam = its own run). Reconverge inputs in the
9835        // "wrong" (cuda-first) order, the order the un-reordered topo DFS pops
9836        // CUDA-last — exactly the arbitrary-graph shape the auto-overlap pass
9837        // must fix. The chains are UNARY (Relu) so each stays a single
9838        // contiguous run (no const-re-read fan-in fragmenting them), exactly
9839        // like the live benchmark's `relu(mul·add)` chains; the CUDA chain is
9840        // HEAVIER (4 vs 2) so the critical-path reorder emits it first.
9841        // (Stamps only; not realized here — the ordering proof, CPU-runnable.)
9842        let n = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9843            g.push(Node {
9844                op,
9845                inputs,
9846                shape: Shape::from_dims(&[3]),
9847                dtype: DType::F32,
9848            })
9849        };
9850        let mut g = Graph::new();
9851        let ca = n(&mut g, Op::Const, vec![]);
9852        let cb = n(&mut g, Op::Const, vec![]);
9853        // CUDA chain — HEAVIER (4 unary stages, one contiguous run).
9854        let mut cprev = ca;
9855        for _ in 0..4 {
9856            cprev = n(&mut g, Op::Relu, vec![cprev]);
9857            g.set_target_backend(cprev, BackendId::Cuda);
9858        }
9859        let c2 = cprev; // CUDA chunk root
9860        // Vulkan chain — lighter (2 unary stages).
9861        let mut vprev = cb;
9862        for _ in 0..2 {
9863            vprev = n(&mut g, Op::Relu, vec![vprev]);
9864            g.set_target_backend(vprev, BackendId::Vulkan);
9865        }
9866        let v2 = vprev; // Vulkan chunk root
9867        // Vulkan -> CUDA copy (residency seam), then reconverge on CUDA with
9868        // inputs [cuda_root, copy] (cuda-first).
9869        let copy = g.push(Node {
9870            op: Op::Copy {
9871                target: DeviceLocation::Cuda { gpu_id: 0 },
9872            },
9873            inputs: vec![v2],
9874            shape: Shape::from_dims(&[3]),
9875            dtype: DType::F32,
9876        });
9877        g.set_target_backend(copy, BackendId::Cuda);
9878        let out = n(&mut g, Op::Add, vec![c2, copy]);
9879        g.set_target_backend(out, BackendId::Cuda);
9880
9881        let unreordered = execution_plan(&g, &[out]);
9882        let reordered = fuel_graph::lower_runs_arm0(&g, &[out]);
9883
9884        // (1) The reorder FIRED — the order changed (else the test is
9885        //     vacuous + auto-overlap did nothing on an arbitrary graph).
9886        assert_ne!(
9887            reordered, unreordered,
9888            "the C3 reorder must change the order on a two-device graph; \
9889             reordered={reordered:?} unreordered={unreordered:?}",
9890        );
9891
9892        // (2) Same node multiset — a permutation, no add/drop.
9893        let mut a = unreordered.clone();
9894        let mut b = reordered.clone();
9895        a.sort();
9896        b.sort();
9897        assert_eq!(a, b, "the reorder is a permutation of the same node set");
9898
9899        // (3) The reordered order is a VALID topological order: every node
9900        //     appears after all of its inputs that are in the order.
9901        let pos: std::collections::HashMap<NodeId, usize> = reordered
9902            .iter()
9903            .enumerate()
9904            .map(|(i, &node)| (node, i))
9905            .collect();
9906        for (i, &node) in reordered.iter().enumerate() {
9907            for &inp in &g.node(node).inputs {
9908                if let Some(&j) = pos.get(&inp) {
9909                    assert!(
9910                        j < i,
9911                        "input {inp:?} of {node:?} must precede it in the reordered \
9912                         order; reordered={reordered:?}",
9913                    );
9914                }
9915            }
9916        }
9917
9918        // (4) The overlap-relevant property: BOTH device producer chunks
9919        //     (the CUDA root c2, the Vulkan root v2) are emitted BEFORE the
9920        //     host-blocking cross-device copy — the A4b overlap topology the
9921        //     un-reordered cuda-last DFS violates — AND the HEAVIER CUDA chunk
9922        //     is emitted first (critical-path: the auto-submit device runs
9923        //     earliest, the live-overlap regression guard).
9924        let p = |node: NodeId| pos[&node];
9925        assert!(p(c2) < p(copy), "CUDA chunk before the cross-device copy");
9926        assert!(p(v2) < p(copy), "Vulkan chunk before the cross-device copy");
9927        assert!(
9928            p(c2) < p(v2),
9929            "the heavier CUDA chunk is emitted before the lighter Vulkan chunk \
9930             (critical-path heavy-first); reordered={reordered:?}",
9931        );
9932    }
9933
9934    /// **C3 follow-on — the OPERAND-ORDER-INVARIANCE gate (CPU, runnable —
9935    /// the reliable operand-independence proof).** The residual the live
9936    /// `cuda_vulkan_overlap_bench_live` benchmark targets is whether the
9937    /// reconverge OPERAND order (`xc.add(&xv)` vs `xv.add(&xc)`) changes the
9938    /// wall-clock overlap. Wall-clock is thermally noisy on a heterogeneous
9939    /// dev box; the DETERMINISTIC root guarantee is this: the C3-reordered
9940    /// dispatch order the executor consumes is **byte-identical for both
9941    /// operand orders**. If the lowered order is the same, the executor
9942    /// processes the SAME WorkItem stream with the SAME cross-device
9943    /// submit/wait timing, so overlap cannot depend on the operand order.
9944    ///
9945    /// This builds the SAME two-device reconverge as
9946    /// `c3_reorder_is_a_valid_topo_permutation` but TWICE — once cuda-first
9947    /// (`add(cuda_root, copy)`), once vulkan-first (`add(copy, cuda_root)`)
9948    /// — over structurally identical graphs (same node ids, only the
9949    /// reconverge's two inputs swapped) and asserts `lower_runs_arm0` emits
9950    /// the identical op/device run sequence. The live executor trace confirms
9951    /// the same: both operand orders produce the identical WorkItem stream
9952    /// (the eager-submit/drain/wait sequence at every cross-device copy is the
9953    /// same, and the CUDA chunk is enqueued first in both).
9954    #[test]
9955    fn c3_reorder_is_operand_order_invariant() {
9956        // Build the two-device reconverge with the reconverge inputs in the
9957        // given order; return (graph, out) over a FRESH graph so node ids line
9958        // up 1:1 between the two builds (only the add's input order differs).
9959        let build = |cuda_first: bool| -> (Graph, NodeId) {
9960            let n = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9961                g.push(Node {
9962                    op,
9963                    inputs,
9964                    shape: Shape::from_dims(&[3]),
9965                    dtype: DType::F32,
9966                })
9967            };
9968            let mut g = Graph::new();
9969            let ca = n(&mut g, Op::Const, vec![]);
9970            let cb = n(&mut g, Op::Const, vec![]);
9971            let mut cprev = ca;
9972            for _ in 0..4 {
9973                cprev = n(&mut g, Op::Relu, vec![cprev]);
9974                g.set_target_backend(cprev, BackendId::Cuda);
9975            }
9976            let c2 = cprev;
9977            let mut vprev = cb;
9978            for _ in 0..2 {
9979                vprev = n(&mut g, Op::Relu, vec![vprev]);
9980                g.set_target_backend(vprev, BackendId::Vulkan);
9981            }
9982            let v2 = vprev;
9983            let copy = g.push(Node {
9984                op: Op::Copy {
9985                    target: DeviceLocation::Cuda { gpu_id: 0 },
9986                },
9987                inputs: vec![v2],
9988                shape: Shape::from_dims(&[3]),
9989                dtype: DType::F32,
9990            });
9991            g.set_target_backend(copy, BackendId::Cuda);
9992            // The ONE knob: the reconverge's two inputs, swapped.
9993            let inputs = if cuda_first {
9994                vec![c2, copy]
9995            } else {
9996                vec![copy, c2]
9997            };
9998            let out = n(&mut g, Op::Add, inputs);
9999            g.set_target_backend(out, BackendId::Cuda);
10000            (g, out)
10001        };
10002
10003        let (g_cf, out_cf) = build(true);
10004        let (g_vf, out_vf) = build(false);
10005
10006        // Lower both via the production path (dispatch_order → lower_runs_arm0
10007        // → device_alternating_order, the C3 reorder).
10008        let order_cf = fuel_graph::lower_runs_arm0(&g_cf, &[out_cf]);
10009        let order_vf = fuel_graph::lower_runs_arm0(&g_vf, &[out_vf]);
10010
10011        // The decisive guarantee: the lowered dispatch order — as an
10012        // (op, device) sequence — is IDENTICAL for both operand orders. (Node
10013        // ids can differ if the build assigned them differently, but here the
10014        // builds are structurally identical so even the ids match; compare the
10015        // op/device sequence to be robust + descriptive on failure.)
10016        let tag = |g: &Graph, ids: &[NodeId]| -> Vec<(String, Option<BackendId>)> {
10017            ids.iter()
10018                .map(|&id| (format!("{:?}", g.node(id).op), g.target_backend(id)))
10019                .collect()
10020        };
10021        let seq_cf = tag(&g_cf, &order_cf);
10022        let seq_vf = tag(&g_vf, &order_vf);
10023        assert_eq!(
10024            seq_cf, seq_vf,
10025            "the C3-reordered dispatch order MUST be identical for both \
10026             reconverge operand orders (operand-order-invariance — the \
10027             executor then sees the same WorkItem stream regardless of \
10028             operand order, so overlap is operand-insensitive).\n\
10029             cuda-first = {seq_cf:?}\nvulkan-first = {seq_vf:?}",
10030        );
10031    }
10032
10033    /// A selector that always takes the LAST arm (arm 1) so a non-arm-0
10034    /// pick is observable (a `WinnerSelector` picks arm-0 ⇒ empty route).
10035    #[cfg(test)]
10036    #[derive(Debug)]
10037    struct PickLast;
10038    #[cfg(test)]
10039    impl RuntimeSelector for PickLast {
10040        fn select<'a>(
10041            &self,
10042            set: &'a crate::ranker::AlternativeSet,
10043        ) -> Option<&'a crate::ranker::Candidate> {
10044            set.alternatives().last()
10045        }
10046    }
10047
10048    /// Build the 2-arm diamond (mirrors `route_picker::tests::diamond`):
10049    /// arm-0 on CUDA, arm-1 on CPU; the arm exits carry their
10050    /// `target_backend` so the picker reads each arm's placement. Returns
10051    /// `(graph_arc, branch, post)`.
10052    #[cfg(test)]
10053    fn picking_diamond() -> (Arc<RwLock<Graph>>, NodeId, NodeId) {
10054        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
10055            g.push(Node {
10056                op,
10057                inputs,
10058                shape: Shape::from_dims(&[2]),
10059                dtype: DType::F32,
10060            })
10061        };
10062        let mut g = Graph::new();
10063        let pre = node(&mut g, Op::Const, vec![]);
10064        let diverge = node(&mut g, Op::Relu, vec![pre]);
10065        let arm0 = node(&mut g, Op::Silu, vec![diverge]);
10066        let arm1 = node(&mut g, Op::GeluTanh, vec![diverge]);
10067        g.set_target_backend(arm0, BackendId::Cuda);
10068        g.set_target_backend(arm1, BackendId::Cpu);
10069        let reconverge = node(&mut g, Op::Relu, vec![arm0]);
10070        let mut b = g.open_branch(diverge);
10071        b.add_arm(arm0);
10072        b.add_arm(arm1);
10073        let branch = b
10074            .finalize_branches(&mut g, reconverge)
10075            .expect("well-formed 2-arm branch")
10076            .expect("2 arms survive");
10077        let post = node(&mut g, Op::Tanh, vec![reconverge]);
10078        (Arc::new(RwLock::new(g)), branch, post)
10079    }
10080
10081    /// Step E Phase C, PR C1: the streaming picking entry's gate.
10082    /// `streaming_pick_for` (the streaming successor of the old one-shot
10083    /// `pick_route_for`) must (1) return `Some(pick)` when a selector + a
10084    /// branch are present (⇒ the `OrderSource::Streaming` walk), (2) return
10085    /// `None` with no selector (the `runtime_selector_disabled` opt-out ⇒
10086    /// arm-0), and (3) short-circuit to `None` on a branchless graph (the
10087    /// fast-path ⇒ the untouched `dispatch_order` lowering).
10088    #[test]
10089    fn streaming_pick_for_gates() {
10090        let (graph, _branch, post) = picking_diamond();
10091        let _ = post;
10092
10093        // (1) selector + branch ⇒ Some(pick).
10094        let sel: Arc<dyn RuntimeSelector> = Arc::new(PickLast);
10095        assert!(
10096            PipelinedExecutor::streaming_pick_for(&graph, Some(sel.clone()), None)
10097                .expect("ok")
10098                .is_some(),
10099            "selector + branch ⇒ a streaming pick",
10100        );
10101
10102        // (2) no selector ⇒ None (arm-0 lowering).
10103        assert!(
10104            PipelinedExecutor::streaming_pick_for(&graph, None, None)
10105                .expect("ok")
10106                .is_none(),
10107            "no selector ⇒ no streaming pick (arm-0 lowering)",
10108        );
10109
10110        // (3) branchless graph + selector ⇒ None (the fast-path).
10111        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
10112            g.push(Node {
10113                op,
10114                inputs,
10115                shape: Shape::from_dims(&[2]),
10116                dtype: DType::F32,
10117            })
10118        };
10119        let bl_graph = {
10120            let mut g = Graph::new();
10121            let c1 = node(&mut g, Op::Const, vec![]);
10122            let c2 = node(&mut g, Op::Const, vec![]);
10123            let add = node(&mut g, Op::Add, vec![c1, c2]);
10124            g.set_target_backend(add, BackendId::Cpu);
10125            Arc::new(RwLock::new(g))
10126        };
10127        assert!(
10128            PipelinedExecutor::streaming_pick_for(&bl_graph, Some(sel), None)
10129                .expect("ok")
10130                .is_none(),
10131            "branchless graph ⇒ no branches ⇒ no streaming pick (fast-path)",
10132        );
10133    }
10134
10135    /// **C1 byte-identity gate (executor layer).** The STREAMED dispatch
10136    /// order — produced by the compiler thread's lazy per-branch resolution
10137    /// (`walk_picked_route_streaming` over `resolve_branch`, the same path
10138    /// `order_for(OrderSource::Streaming)` collects) — equals the ONE-SHOT
10139    /// order (`lower_picked_route` over the route the eager `pick_route`
10140    /// resolves) on the branched diamond, for both arm-0 (WinnerSelector)
10141    /// and arm-1 (PickLast). This is the proof that C1 changes *when* a
10142    /// branch resolves, not *which* arm — the same selector, the same
10143    /// `resolve_branch`, the same emitted order.
10144    #[test]
10145    fn streamed_order_equals_one_shot() {
10146        let (graph, _branch, post) = picking_diamond();
10147        let g = graph.read().unwrap();
10148        let bindings = global_bindings();
10149
10150        for sel in [
10151            Arc::new(crate::ranker::WinnerSelector) as Arc<dyn RuntimeSelector>,
10152            Arc::new(PickLast) as Arc<dyn RuntimeSelector>,
10153        ] {
10154            // One-shot: resolve the whole route, then lower.
10155            let one_shot_route = pick_route(&g, &[post], &bindings, sel.as_ref(), None);
10156            let one_shot = fuel_graph::lower_picked_route(&g, &[post], &one_shot_route);
10157
10158            // Streamed: resolve each branch lazily at the frontier via the
10159            // SAME `resolve_branch` the compiler thread uses.
10160            let streamed = fuel_graph::lower_picked_route_streaming(&g, &[post], |branch| {
10161                resolve_branch(&g, branch, &bindings, sel.as_ref())
10162            });
10163
10164            assert_eq!(
10165                streamed, one_shot,
10166                "streamed order must equal one-shot for selector {sel:?}",
10167            );
10168        }
10169    }
10170
10171    /// Realizing a node whose target_backend isn't set surfaces a
10172    /// typed error (no panic).
10173    #[test]
10174    fn pipelined_errors_on_unset_target_backend() {
10175        let graph = Arc::new(RwLock::new(Graph::new()));
10176        let (lhs_id, rhs_id, add_id) = {
10177            let mut g = graph.write().unwrap();
10178            let lhs = g.push(Node {
10179                op: Op::Const,
10180                inputs: vec![],
10181                shape: Shape::from_dims(&[2]),
10182                dtype: DType::F32,
10183            });
10184            let rhs = g.push(Node {
10185                op: Op::Const,
10186                inputs: vec![],
10187                shape: Shape::from_dims(&[2]),
10188                dtype: DType::F32,
10189            });
10190            // Deliberately do NOT call set_target_backend on the Add.
10191            let add = g.push(Node {
10192                op: Op::Add,
10193                inputs: vec![lhs, rhs],
10194                shape: Shape::from_dims(&[2]),
10195                dtype: DType::F32,
10196            });
10197            (lhs, rhs, add)
10198        };
10199
10200        let mut inputs = StorageCache::new();
10201        inputs.insert(
10202            lhs_id,
10203            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]))),
10204        );
10205        inputs.insert(
10206            rhs_id,
10207            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[3.0_f32, 4.0]))),
10208        );
10209
10210        let result = PipelinedExecutor::realize(graph, add_id, inputs);
10211        assert!(result.is_err(), "missing target_backend must error");
10212        let msg = result.unwrap_err().to_string();
10213        assert!(
10214            msg.contains("target_backend"),
10215            "error names the unmet precondition: {msg}"
10216        );
10217    }
10218
10219    /// Realizing a Const-only graph adopts the pre-seeded input
10220    /// without calling any kernel.
10221    #[test]
10222    fn pipelined_realize_const_only() {
10223        let storage = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0, 7.0]);
10224
10225        let graph = Arc::new(RwLock::new(Graph::new()));
10226        let const_id = {
10227            let mut g = graph.write().unwrap();
10228            g.push(Node {
10229                op: Op::Const,
10230                inputs: vec![],
10231                shape: Shape::from_dims(&[3]),
10232                dtype: DType::F32,
10233            })
10234        };
10235
10236        let mut inputs = StorageCache::new();
10237        inputs.insert(const_id, Arc::new(RwLock::new(storage)));
10238
10239        let (result_arc, _) =
10240            PipelinedExecutor::realize(graph, const_id, inputs).expect("realize const");
10241        let guard = result_arc.read().unwrap();
10242        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
10243            let typed: &[f32] = c.as_slice().unwrap();
10244            assert_eq!(typed, &[5.0, 6.0, 7.0]);
10245        }
10246    }
10247
10248    /// Missing input-cache entry for a Const surfaces a typed error.
10249    #[test]
10250    fn pipelined_errors_on_missing_const_input() {
10251        let graph = Arc::new(RwLock::new(Graph::new()));
10252        let const_id = {
10253            let mut g = graph.write().unwrap();
10254            g.push(Node {
10255                op: Op::Const,
10256                inputs: vec![],
10257                shape: Shape::from_dims(&[2]),
10258                dtype: DType::F32,
10259            })
10260        };
10261        // Deliberately empty input cache.
10262        let inputs = StorageCache::new();
10263        let result = PipelinedExecutor::realize(graph, const_id, inputs);
10264        assert!(result.is_err());
10265    }
10266
10267    /// E2E: 2-node graph (Const + Relu) — exercises the unary
10268    /// dispatch wrapper + kernel through the pipelined executor.
10269    #[test]
10270    fn pipelined_realize_const_relu() {
10271        let storage = fuel_memory::from_slice_cpu(&[-1.0_f32, 0.0, 0.5, -3.5, 7.25]);
10272        let graph = Arc::new(RwLock::new(Graph::new()));
10273        let (in_id, relu_id) = {
10274            let mut g = graph.write().unwrap();
10275            let in_id = g.push(Node {
10276                op: Op::Const,
10277                inputs: vec![],
10278                shape: Shape::from_dims(&[5]),
10279                dtype: DType::F32,
10280            });
10281            let relu_id = g.push(Node {
10282                op: Op::Relu,
10283                inputs: vec![in_id],
10284                shape: Shape::from_dims(&[5]),
10285                dtype: DType::F32,
10286            });
10287            g.set_target_backend(relu_id, BackendId::Cpu);
10288            (in_id, relu_id)
10289        };
10290        let mut inputs = StorageCache::new();
10291        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10292
10293        let (result_arc, _) = PipelinedExecutor::realize(graph, relu_id, inputs).expect("realize");
10294        let guard = result_arc.read().unwrap();
10295        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
10296            let typed: &[f32] = c.as_slice().expect("f32 cast");
10297            assert_eq!(typed, &[0.0, 0.0, 0.5, 0.0, 7.25]);
10298        }
10299    }
10300
10301    /// E2E: Const + Const + Sub + Mul + Div — exercises three more
10302    /// of the freshly-migrated binary kernels in one graph. Verifies
10303    /// that intermediates flow through the cache as expected.
10304    #[test]
10305    fn pipelined_realize_chained_binary_ops() {
10306        let a_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
10307        let b_storage = fuel_memory::from_slice_cpu(&[3.0_f32, 5.0]);
10308        let c_storage = fuel_memory::from_slice_cpu(&[2.0_f32, 4.0]);
10309
10310        let graph = Arc::new(RwLock::new(Graph::new()));
10311        let (a_id, b_id, c_id, sub_id, mul_id, div_id) = {
10312            let mut g = graph.write().unwrap();
10313            let a = g.push(Node {
10314                op: Op::Const,
10315                inputs: vec![],
10316                shape: Shape::from_dims(&[2]),
10317                dtype: DType::F32,
10318            });
10319            let b = g.push(Node {
10320                op: Op::Const,
10321                inputs: vec![],
10322                shape: Shape::from_dims(&[2]),
10323                dtype: DType::F32,
10324            });
10325            let c = g.push(Node {
10326                op: Op::Const,
10327                inputs: vec![],
10328                shape: Shape::from_dims(&[2]),
10329                dtype: DType::F32,
10330            });
10331            // (a - b)         = [7, 15]
10332            let sub = g.push(Node {
10333                op: Op::Sub,
10334                inputs: vec![a, b],
10335                shape: Shape::from_dims(&[2]),
10336                dtype: DType::F32,
10337            });
10338            // (a - b) * c     = [14, 60]
10339            let mul = g.push(Node {
10340                op: Op::Mul,
10341                inputs: vec![sub, c],
10342                shape: Shape::from_dims(&[2]),
10343                dtype: DType::F32,
10344            });
10345            // ((a-b)*c) / b   = [14/3, 12]
10346            let div = g.push(Node {
10347                op: Op::Div,
10348                inputs: vec![mul, b],
10349                shape: Shape::from_dims(&[2]),
10350                dtype: DType::F32,
10351            });
10352            g.set_target_backend(sub, BackendId::Cpu);
10353            g.set_target_backend(mul, BackendId::Cpu);
10354            g.set_target_backend(div, BackendId::Cpu);
10355            (a, b, c, sub, mul, div)
10356        };
10357
10358        let _ = (sub_id, mul_id);
10359        let mut inputs = StorageCache::new();
10360        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
10361        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
10362        inputs.insert(c_id, Arc::new(RwLock::new(c_storage)));
10363
10364        let (result_arc, _) = PipelinedExecutor::realize(graph, div_id, inputs).expect("realize");
10365        let guard = result_arc.read().unwrap();
10366        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
10367            let typed: &[f32] = c.as_slice().unwrap();
10368            assert!((typed[0] - (14.0_f32 / 3.0)).abs() < 1e-6);
10369            assert!((typed[1] - 12.0).abs() < 1e-6);
10370        }
10371    }
10372
10373    /// E2E: Const + Transpose — verifies metadata-only view ops
10374    /// share the input's Storage Arc and produce a strided Layout.
10375    /// Stage 3 of Layout-on-Node.
10376    #[test]
10377    fn pipelined_realize_transpose_is_metadata_only() {
10378        // shape [2, 3]; transpose → shape [3, 2], strided
10379        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
10380        let graph = Arc::new(RwLock::new(Graph::new()));
10381        let (in_id, t_id) = {
10382            let mut g = graph.write().unwrap();
10383            let in_id = g.push(Node {
10384                op: Op::Const,
10385                inputs: vec![],
10386                shape: Shape::from_dims(&[2, 3]),
10387                dtype: DType::F32,
10388            });
10389            let t_id = g.push(Node {
10390                op: Op::Transpose,
10391                inputs: vec![in_id],
10392                shape: Shape::from_dims(&[3, 2]),
10393                dtype: DType::F32,
10394            });
10395            // Note: NO set_target_backend — transpose is metadata-only
10396            // and doesn't run on a backend.
10397            (in_id, t_id)
10398        };
10399        let mut inputs = StorageCache::new();
10400        let in_arc = Arc::new(RwLock::new(storage));
10401        inputs.insert(in_id, Arc::clone(&in_arc));
10402
10403        let (result_arc, result_layout) =
10404            PipelinedExecutor::realize(graph, t_id, inputs).expect("realize");
10405
10406        // The output Storage Arc is the SAME Arc as the input —
10407        // metadata-only adoption shares bytes.
10408        assert!(
10409            Arc::ptr_eq(&result_arc, &in_arc),
10410            "transpose must share input bytes"
10411        );
10412
10413        // The output Layout is the transposed view.
10414        assert_eq!(result_layout.shape().dims(), &[3, 2]);
10415        assert_eq!(result_layout.stride(), &[1, 3]);
10416        assert!(!result_layout.is_contiguous());
10417    }
10418
10419    /// E2E: Const + Flip(dim=0) — verifies Op::Flip is metadata-only.
10420    /// The output Storage Arc must be the SAME Arc (no copy);
10421    /// the output Layout has a negated stride at dim 0 and a
10422    /// shifted start_offset.
10423    #[test]
10424    fn pipelined_realize_flip_is_metadata_only() {
10425        // shape [3, 4]; flip dim 0 → shape [3, 4], stride [-4, 1], offset 8.
10426        let data: Vec<f32> = (1..=12).map(|x| x as f32).collect();
10427        let storage = fuel_memory::from_slice_cpu(&data);
10428        let graph = Arc::new(RwLock::new(Graph::new()));
10429        let (in_id, f_id) = {
10430            let mut g = graph.write().unwrap();
10431            let in_id = g.push(Node {
10432                op: Op::Const,
10433                inputs: vec![],
10434                shape: Shape::from_dims(&[3, 4]),
10435                dtype: DType::F32,
10436            });
10437            let f_id = g.push(Node {
10438                op: Op::Flip { dim: 0 },
10439                inputs: vec![in_id],
10440                shape: Shape::from_dims(&[3, 4]),
10441                dtype: DType::F32,
10442            });
10443            (in_id, f_id)
10444        };
10445        let mut inputs = StorageCache::new();
10446        let in_arc = Arc::new(RwLock::new(storage));
10447        inputs.insert(in_id, Arc::clone(&in_arc));
10448
10449        let (result_arc, result_layout) =
10450            PipelinedExecutor::realize(graph, f_id, inputs).expect("realize");
10451
10452        assert!(
10453            Arc::ptr_eq(&result_arc, &in_arc),
10454            "flip must share input bytes"
10455        );
10456        assert_eq!(result_layout.shape().dims(), &[3, 4]);
10457        assert_eq!(result_layout.stride(), &[-4_isize, 1]);
10458        assert_eq!(result_layout.start_offset(), 8);
10459        assert!(!result_layout.is_contiguous());
10460    }
10461
10462    /// E2E: Const + Permute(rank-3 axes [2, 0, 1]) — verifies the
10463    /// general permute path through metadata-only adoption.
10464    #[test]
10465    fn pipelined_realize_permute_is_metadata_only() {
10466        // shape [2, 3, 4]; permute axes [2, 0, 1] → shape [4, 2, 3]
10467        let data: Vec<f32> = (1..=24).map(|x| x as f32).collect();
10468        let storage = fuel_memory::from_slice_cpu(&data);
10469        let graph = Arc::new(RwLock::new(Graph::new()));
10470        let (in_id, p_id) = {
10471            let mut g = graph.write().unwrap();
10472            let in_id = g.push(Node {
10473                op: Op::Const,
10474                inputs: vec![],
10475                shape: Shape::from_dims(&[2, 3, 4]),
10476                dtype: DType::F32,
10477            });
10478            let p_id = g.push(Node {
10479                op: Op::Permute(vec![2, 0, 1]),
10480                inputs: vec![in_id],
10481                shape: Shape::from_dims(&[4, 2, 3]),
10482                dtype: DType::F32,
10483            });
10484            (in_id, p_id)
10485        };
10486        let mut inputs = StorageCache::new();
10487        let in_arc = Arc::new(RwLock::new(storage));
10488        inputs.insert(in_id, Arc::clone(&in_arc));
10489
10490        let (result_arc, result_layout) =
10491            PipelinedExecutor::realize(graph, p_id, inputs).expect("realize");
10492
10493        assert!(Arc::ptr_eq(&result_arc, &in_arc));
10494        assert_eq!(result_layout.shape().dims(), &[4, 2, 3]);
10495        // Original strides for shape [2, 3, 4] are [12, 4, 1].
10496        // After permute axes [2, 0, 1]: [strides[2], strides[0], strides[1]] = [1, 12, 4].
10497        assert_eq!(result_layout.stride(), &[1, 12, 4]);
10498    }
10499
10500    /// E2E: Const + Cast(f32→f64) — verifies cast through the
10501    /// pipelined executor. Output Storage has the target dtype;
10502    /// bytes encode the widened values.
10503    #[test]
10504    fn pipelined_realize_cast_f32_to_f64() {
10505        let storage = fuel_memory::from_slice_cpu(&[1.5_f32, -2.25, 100.0]);
10506        let graph = Arc::new(RwLock::new(Graph::new()));
10507        let (in_id, c_id) = {
10508            let mut g = graph.write().unwrap();
10509            let in_id = g.push(Node {
10510                op: Op::Const,
10511                inputs: vec![],
10512                shape: Shape::from_dims(&[3]),
10513                dtype: DType::F32,
10514            });
10515            let c_id = g.push(Node {
10516                op: Op::Cast(DType::F64),
10517                inputs: vec![in_id],
10518                shape: Shape::from_dims(&[3]),
10519                dtype: DType::F64,
10520            });
10521            g.set_target_backend(c_id, BackendId::Cpu);
10522            (in_id, c_id)
10523        };
10524        let mut inputs = StorageCache::new();
10525        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10526
10527        let (result_arc, result_layout) =
10528            PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
10529        assert_eq!(result_layout.shape().dims(), &[3]);
10530
10531        let guard = result_arc.read().unwrap();
10532        assert_eq!(guard.dtype, DType::F64);
10533        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10534            panic!("expected Cpu storage");
10535        };
10536        assert_eq!(c.as_slice::<f64>().unwrap(), &[1.5_f64, -2.25, 100.0]);
10537    }
10538
10539    /// E2E: Const + Cast(f32→bf16) + Cast(bf16→f32) — round trip
10540    /// through bf16; verifies the Cast wrapper's source-dtype
10541    /// dispatch (different sources hit different match arms).
10542    /// Inputs chosen to round-trip exactly through bf16.
10543    #[test]
10544    fn pipelined_realize_cast_round_trip_via_bf16() {
10545        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, -3.0, 0.5]);
10546        let graph = Arc::new(RwLock::new(Graph::new()));
10547        let (in_id, c1_id, c2_id) = {
10548            let mut g = graph.write().unwrap();
10549            let in_id = g.push(Node {
10550                op: Op::Const,
10551                inputs: vec![],
10552                shape: Shape::from_dims(&[4]),
10553                dtype: DType::F32,
10554            });
10555            let c1_id = g.push(Node {
10556                op: Op::Cast(DType::BF16),
10557                inputs: vec![in_id],
10558                shape: Shape::from_dims(&[4]),
10559                dtype: DType::BF16,
10560            });
10561            let c2_id = g.push(Node {
10562                op: Op::Cast(DType::F32),
10563                inputs: vec![c1_id],
10564                shape: Shape::from_dims(&[4]),
10565                dtype: DType::F32,
10566            });
10567            g.set_target_backend(c1_id, BackendId::Cpu);
10568            g.set_target_backend(c2_id, BackendId::Cpu);
10569            (in_id, c1_id, c2_id)
10570        };
10571        let _ = c1_id;
10572        let mut inputs = StorageCache::new();
10573        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10574
10575        let (result_arc, _) = PipelinedExecutor::realize(graph, c2_id, inputs).expect("realize");
10576        let guard = result_arc.read().unwrap();
10577        assert_eq!(guard.dtype, DType::F32);
10578        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10579            panic!("expected Cpu storage");
10580        };
10581        assert_eq!(c.as_slice::<f32>().unwrap(), &[1.0_f32, 2.0, -3.0, 0.5]);
10582    }
10583
10584    /// E2E: Const + Slice — slice is metadata-only; the output Arc
10585    /// shares bytes with the input, and the Layout's start_offset
10586    /// + narrowed shape reflect the slice. Stage 3 of Layout-on-Node
10587    ///
10588    /// extended to cover Op::Slice via Layout::narrow.
10589    #[test]
10590    fn pipelined_realize_slice_is_metadata_only() {
10591        // shape [5]; slice dim 0 from index 1 with len 3 → shape [3]
10592        // Source: [10, 20, 30, 40, 50]; slice → [20, 30, 40]
10593        let storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0]);
10594        let graph = Arc::new(RwLock::new(Graph::new()));
10595        let (in_id, s_id) = {
10596            let mut g = graph.write().unwrap();
10597            let in_id = g.push(Node {
10598                op: Op::Const,
10599                inputs: vec![],
10600                shape: Shape::from_dims(&[5]),
10601                dtype: DType::F32,
10602            });
10603            let s_id = g.push(Node {
10604                op: Op::Slice {
10605                    dim: 0,
10606                    start: 1,
10607                    len: 3,
10608                },
10609                inputs: vec![in_id],
10610                shape: Shape::from_dims(&[3]),
10611                dtype: DType::F32,
10612            });
10613            (in_id, s_id)
10614        };
10615        let mut inputs = StorageCache::new();
10616        let in_arc = Arc::new(RwLock::new(storage));
10617        inputs.insert(in_id, Arc::clone(&in_arc));
10618
10619        let (result_arc, result_layout) =
10620            PipelinedExecutor::realize(graph, s_id, inputs).expect("realize");
10621
10622        // Bytes shared with the input.
10623        assert!(Arc::ptr_eq(&result_arc, &in_arc));
10624        assert_eq!(result_layout.shape().dims(), &[3]);
10625        // Slice into a contiguous source: the resulting layout has
10626        // start_offset = original_stride[0] * start = 1 * 1 = 1,
10627        // and stride [1] (still contiguous within the narrowed dim).
10628        assert_eq!(result_layout.start_offset(), 1);
10629        assert_eq!(result_layout.stride(), &[1]);
10630    }
10631
10632    /// E2E: Const + Slice + SumAll — slice is metadata-only, but
10633    /// sum needs contiguous bytes, so auto-Contiguize materializes
10634    /// the slice before reduce. Tests the stage 3+4 integration
10635    /// through Op::Slice. Sum of `[20, 30, 40]` is 90.
10636    #[test]
10637    fn pipelined_realize_slice_then_sum_all() {
10638        let storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0]);
10639        let graph = Arc::new(RwLock::new(Graph::new()));
10640        let (in_id, s_id, sum_id) = {
10641            let mut g = graph.write().unwrap();
10642            let in_id = g.push(Node {
10643                op: Op::Const,
10644                inputs: vec![],
10645                shape: Shape::from_dims(&[5]),
10646                dtype: DType::F32,
10647            });
10648            let s_id = g.push(Node {
10649                op: Op::Slice {
10650                    dim: 0,
10651                    start: 1,
10652                    len: 3,
10653                },
10654                inputs: vec![in_id],
10655                shape: Shape::from_dims(&[3]),
10656                dtype: DType::F32,
10657            });
10658            let sum_id = g.push(Node {
10659                op: Op::SumAll,
10660                inputs: vec![s_id],
10661                shape: Shape::from_dims(&[]),
10662                dtype: DType::F32,
10663            });
10664            g.set_target_backend(sum_id, BackendId::Cpu);
10665            (in_id, s_id, sum_id)
10666        };
10667        let _ = s_id;
10668        let mut inputs = StorageCache::new();
10669        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10670
10671        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
10672        let guard = result_arc.read().unwrap();
10673        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10674            panic!("expected Cpu storage");
10675        };
10676        assert_eq!(c.as_slice::<f32>().unwrap(), &[90.0]);
10677    }
10678
10679    /// E2E: Const + Flip + ReluElementwise — Flip is metadata-only,
10680    /// then a kernel that doesn't yet handle negative strides forces
10681    /// auto-Contiguize to materialize through StridedIndex (which
10682    /// handles signed strides natively). Verifies the post-flip
10683    /// data ordering ([4, 3, 2, 1]) is correctly seen by the kernel.
10684    #[test]
10685    fn pipelined_realize_flip_then_relu_materializes_in_reverse() {
10686        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
10687        let graph = Arc::new(RwLock::new(Graph::new()));
10688        let (in_id, _f_id, r_id) = {
10689            let mut g = graph.write().unwrap();
10690            let in_id = g.push(Node {
10691                op: Op::Const,
10692                inputs: vec![],
10693                shape: Shape::from_dims(&[4]),
10694                dtype: DType::F32,
10695            });
10696            let f_id = g.push(Node {
10697                op: Op::Flip { dim: 0 },
10698                inputs: vec![in_id],
10699                shape: Shape::from_dims(&[4]),
10700                dtype: DType::F32,
10701            });
10702            let r_id = g.push(Node {
10703                op: Op::Relu,
10704                inputs: vec![f_id],
10705                shape: Shape::from_dims(&[4]),
10706                dtype: DType::F32,
10707            });
10708            g.set_target_backend(r_id, BackendId::Cpu);
10709            (in_id, f_id, r_id)
10710        };
10711        let mut inputs = StorageCache::new();
10712        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10713
10714        let (result_arc, result_layout) =
10715            PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
10716        let guard = result_arc.read().unwrap();
10717        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10718            panic!("expected Cpu storage");
10719        };
10720        assert_eq!(c.as_slice::<f32>().unwrap(), &[4.0, 3.0, 2.0, 1.0]);
10721        assert_eq!(result_layout.shape().dims(), &[4]);
10722        assert!(result_layout.is_contiguous(), "relu output is contiguous");
10723    }
10724
10725    /// E2E: Const + BroadcastTo — verifies that broadcast layouts
10726    /// have stride 0 on the broadcast dim while sharing the input's
10727    /// bytes. Stage 3 of Layout-on-Node.
10728    #[test]
10729    fn pipelined_realize_broadcast_is_metadata_only() {
10730        // shape [3]; broadcast to [4, 3] — leading dim is 0-stride
10731        let storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
10732        let graph = Arc::new(RwLock::new(Graph::new()));
10733        let (in_id, b_id) = {
10734            let mut g = graph.write().unwrap();
10735            let in_id = g.push(Node {
10736                op: Op::Const,
10737                inputs: vec![],
10738                shape: Shape::from_dims(&[3]),
10739                dtype: DType::F32,
10740            });
10741            let b_id = g.push(Node {
10742                op: Op::BroadcastTo(Shape::from_dims(&[4, 3])),
10743                inputs: vec![in_id],
10744                shape: Shape::from_dims(&[4, 3]),
10745                dtype: DType::F32,
10746            });
10747            (in_id, b_id)
10748        };
10749        let mut inputs = StorageCache::new();
10750        let in_arc = Arc::new(RwLock::new(storage));
10751        inputs.insert(in_id, Arc::clone(&in_arc));
10752
10753        let (result_arc, result_layout) =
10754            PipelinedExecutor::realize(graph, b_id, inputs).expect("realize");
10755
10756        assert!(Arc::ptr_eq(&result_arc, &in_arc));
10757        assert_eq!(result_layout.shape().dims(), &[4, 3]);
10758        // Broadcasted leading dim has stride 0.
10759        assert_eq!(result_layout.stride(), &[0, 1]);
10760    }
10761
10762    /// E2E: Const + Const + MatMul — exercises rank-2 matmul
10763    /// through the pipelined executor. Inputs are contiguous (no
10764    /// auto-Contiguize needed); the kernel walks them via the
10765    /// (m, n, k) carried in OpParams::Matmul.
10766    #[test]
10767    fn pipelined_realize_matmul_2x3_times_3x2() {
10768        // [[1, 2, 3], [4, 5, 6]] @ [[7, 8], [9, 10], [11, 12]]
10769        //   = [[58, 64], [139, 154]]
10770        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
10771        let rhs_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0, 9.0, 10.0, 11.0, 12.0]);
10772
10773        let graph = Arc::new(RwLock::new(Graph::new()));
10774        let (lhs_id, rhs_id, mm_id) = {
10775            let mut g = graph.write().unwrap();
10776            let lhs = g.push(Node {
10777                op: Op::Const,
10778                inputs: vec![],
10779                shape: Shape::from_dims(&[2, 3]),
10780                dtype: DType::F32,
10781            });
10782            let rhs = g.push(Node {
10783                op: Op::Const,
10784                inputs: vec![],
10785                shape: Shape::from_dims(&[3, 2]),
10786                dtype: DType::F32,
10787            });
10788            let mm = g.push(Node {
10789                op: Op::MatMul,
10790                inputs: vec![lhs, rhs],
10791                shape: Shape::from_dims(&[2, 2]),
10792                dtype: DType::F32,
10793            });
10794            g.set_target_backend(mm, BackendId::Cpu);
10795            (lhs, rhs, mm)
10796        };
10797        let mut inputs = StorageCache::new();
10798        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
10799        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
10800
10801        let (result_arc, result_layout) =
10802            PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
10803        assert_eq!(result_layout.shape().dims(), &[2, 2]);
10804        assert!(result_layout.is_contiguous());
10805
10806        let guard = result_arc.read().unwrap();
10807        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10808            panic!("expected Cpu storage");
10809        };
10810        assert_eq!(c.as_slice::<f32>().unwrap(), &[58.0, 64.0, 139.0, 154.0]);
10811    }
10812
10813    /// E2E: batched matmul through the pipelined executor. Two
10814    /// batches of [2, 2] @ [2, 2]; the kernel iterates over
10815    /// `batch_count` and produces concatenated outputs.
10816    #[test]
10817    fn pipelined_realize_matmul_batched_2x_2x2_times_2x2() {
10818        let lhs_storage = fuel_memory::from_slice_cpu(&[
10819            1.0_f32, 2.0, 3.0, 4.0, // batch 0
10820            1.0, 0.0, 0.0, 1.0, // batch 1 (identity)
10821        ]);
10822        let rhs_storage = fuel_memory::from_slice_cpu(&[
10823            5.0_f32, 6.0, 7.0, 8.0, // batch 0
10824            10.0, 20.0, 30.0, 40.0, // batch 1
10825        ]);
10826
10827        let graph = Arc::new(RwLock::new(Graph::new()));
10828        let (lhs_id, rhs_id, mm_id) = {
10829            let mut g = graph.write().unwrap();
10830            let lhs = g.push(Node {
10831                op: Op::Const,
10832                inputs: vec![],
10833                shape: Shape::from_dims(&[2, 2, 2]),
10834                dtype: DType::F32,
10835            });
10836            let rhs = g.push(Node {
10837                op: Op::Const,
10838                inputs: vec![],
10839                shape: Shape::from_dims(&[2, 2, 2]),
10840                dtype: DType::F32,
10841            });
10842            let mm = g.push(Node {
10843                op: Op::MatMul,
10844                inputs: vec![lhs, rhs],
10845                shape: Shape::from_dims(&[2, 2, 2]),
10846                dtype: DType::F32,
10847            });
10848            g.set_target_backend(mm, BackendId::Cpu);
10849            (lhs, rhs, mm)
10850        };
10851        let mut inputs = StorageCache::new();
10852        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
10853        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
10854
10855        let (result_arc, result_layout) =
10856            PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
10857        assert_eq!(result_layout.shape().dims(), &[2, 2, 2]);
10858        assert!(result_layout.is_contiguous());
10859
10860        let guard = result_arc.read().unwrap();
10861        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10862            panic!("expected Cpu storage");
10863        };
10864        // batch 0: [[1,2],[3,4]] @ [[5,6],[7,8]] = [[19,22],[43,50]]
10865        // batch 1: identity @ [[10,20],[30,40]]   = [[10,20],[30,40]]
10866        assert_eq!(
10867            c.as_slice::<f32>().unwrap(),
10868            &[19.0, 22.0, 43.0, 50.0, 10.0, 20.0, 30.0, 40.0]
10869        );
10870    }
10871
10872    /// E2E: F64 elementwise add through the pipelined executor.
10873    /// Verifies that capability-driven dispatch correctly routes
10874    /// (AddElementwise, F64) to the f64 wrapper/kernel.
10875    #[test]
10876    fn pipelined_realize_add_f64() {
10877        let lhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0]);
10878        let rhs = fuel_memory::from_slice_cpu(&[10.0_f64, 20.0, 30.0]);
10879        let graph = Arc::new(RwLock::new(Graph::new()));
10880        let (l_id, r_id, op_id) = {
10881            let mut g = graph.write().unwrap();
10882            let l = g.push(Node {
10883                op: Op::Const,
10884                inputs: vec![],
10885                shape: Shape::from_dims(&[3]),
10886                dtype: DType::F64,
10887            });
10888            let r = g.push(Node {
10889                op: Op::Const,
10890                inputs: vec![],
10891                shape: Shape::from_dims(&[3]),
10892                dtype: DType::F64,
10893            });
10894            let op = g.push(Node {
10895                op: Op::Add,
10896                inputs: vec![l, r],
10897                shape: Shape::from_dims(&[3]),
10898                dtype: DType::F64,
10899            });
10900            g.set_target_backend(op, BackendId::Cpu);
10901            (l, r, op)
10902        };
10903        let mut inputs = StorageCache::new();
10904        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10905        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10906        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
10907        let guard = result_arc.read().unwrap();
10908        assert_eq!(guard.dtype, DType::F64);
10909        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10910            panic!("expected Cpu storage");
10911        };
10912        assert_eq!(c.as_slice::<f64>().unwrap(), &[11.0_f64, 22.0, 33.0]);
10913    }
10914
10915    /// E2E: Op::Equal F32 → Bool mask through the pipelined executor (GAP-168c).
10916    /// Verifies (a) the binding-table key `(EqualElementwise, [F32, F32, U8],
10917    /// Cpu)` resolves, (b) the executor allocates a U8-sized output
10918    /// buffer (1 byte per element, not 4), (c) the kernel writes the
10919    /// expected mask bits including IEEE-754 NaN handling
10920    /// (`NaN == NaN` is false).
10921    #[test]
10922    fn pipelined_realize_eq_f32_to_bool_mask() {
10923        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, f32::NAN, 0.0]);
10924        let rhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -0.0]);
10925        let graph = Arc::new(RwLock::new(Graph::new()));
10926        let (l_id, r_id, eq_id) = {
10927            let mut g = graph.write().unwrap();
10928            let l = g.push(Node {
10929                op: Op::Const,
10930                inputs: vec![],
10931                shape: Shape::from_dims(&[5]),
10932                dtype: DType::F32,
10933            });
10934            let r = g.push(Node {
10935                op: Op::Const,
10936                inputs: vec![],
10937                shape: Shape::from_dims(&[5]),
10938                dtype: DType::F32,
10939            });
10940            let eq = g.push(Node {
10941                op: Op::Equal,
10942                inputs: vec![l, r],
10943                shape: Shape::from_dims(&[5]),
10944                dtype: DType::Bool,
10945            });
10946            g.set_target_backend(eq, BackendId::Cpu);
10947            (l, r, eq)
10948        };
10949        let mut inputs = StorageCache::new();
10950        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10951        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10952        let (result_arc, _) = PipelinedExecutor::realize(graph, eq_id, inputs).expect("realize");
10953        let guard = result_arc.read().unwrap();
10954        assert_eq!(guard.dtype, DType::Bool);
10955        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10956            panic!("expected Cpu storage");
10957        };
10958        let mask: &[u8] = c.as_slice().expect("u8 view");
10959        // Index 0: 1.0 == 1.0 → 1.
10960        // Index 1: 2.0 != 5.0 → 0.
10961        // Index 2: 3.0 == 3.0 → 1.
10962        // Index 3: NaN == NaN → 0 (IEEE-754).
10963        // Index 4: 0.0 == -0.0 → 1 (IEEE-754 zero equality).
10964        assert_eq!(mask, &[1, 0, 1, 0, 1]);
10965    }
10966
10967    /// E2E: Op::Ne F32 → Bool mask. Mirrors the Eq F32 test with
10968    /// inverted predicate; NaN-vs-NaN slot now yields `1` (since
10969    /// `NaN != NaN` per IEEE-754).
10970    #[test]
10971    fn pipelined_realize_ne_f32_to_bool_mask() {
10972        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, f32::NAN, 0.0]);
10973        let rhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -0.0]);
10974        let graph = Arc::new(RwLock::new(Graph::new()));
10975        let (l_id, r_id, ne_id) = {
10976            let mut g = graph.write().unwrap();
10977            let l = g.push(Node {
10978                op: Op::Const,
10979                inputs: vec![],
10980                shape: Shape::from_dims(&[5]),
10981                dtype: DType::F32,
10982            });
10983            let r = g.push(Node {
10984                op: Op::Const,
10985                inputs: vec![],
10986                shape: Shape::from_dims(&[5]),
10987                dtype: DType::F32,
10988            });
10989            let ne = g.push(Node {
10990                op: Op::Ne,
10991                inputs: vec![l, r],
10992                shape: Shape::from_dims(&[5]),
10993                dtype: DType::Bool,
10994            });
10995            g.set_target_backend(ne, BackendId::Cpu);
10996            (l, r, ne)
10997        };
10998        let mut inputs = StorageCache::new();
10999        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11000        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11001        let (result_arc, _) = PipelinedExecutor::realize(graph, ne_id, inputs).expect("realize");
11002        let guard = result_arc.read().unwrap();
11003        assert_eq!(guard.dtype, DType::Bool);
11004        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11005            panic!("expected Cpu storage");
11006        };
11007        let mask: &[u8] = c.as_slice().expect("u8 view");
11008        // Inverse of the Eq test:
11009        // 1.0 != 1.0 → 0;  2.0 != 5.0 → 1;  3.0 != 3.0 → 0;
11010        // NaN != NaN → 1 (IEEE-754);  0.0 != -0.0 → 0 (IEEE-754).
11011        assert_eq!(mask, &[0, 1, 0, 1, 0]);
11012    }
11013
11014    /// E2E: Op::Lt F32 → Bool mask. Confirms strict-less-than semantics
11015    /// + IEEE-754 NaN handling (any comparison with NaN is unordered →
11016    ///
11017    /// `0`).
11018    #[test]
11019    fn pipelined_realize_lt_f32_to_bool_mask() {
11020        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -1.0]);
11021        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 3.0, 0.0, 0.0]);
11022        let graph = Arc::new(RwLock::new(Graph::new()));
11023        let (l_id, r_id, lt_id) = {
11024            let mut g = graph.write().unwrap();
11025            let l = g.push(Node {
11026                op: Op::Const,
11027                inputs: vec![],
11028                shape: Shape::from_dims(&[5]),
11029                dtype: DType::F32,
11030            });
11031            let r = g.push(Node {
11032                op: Op::Const,
11033                inputs: vec![],
11034                shape: Shape::from_dims(&[5]),
11035                dtype: DType::F32,
11036            });
11037            let lt = g.push(Node {
11038                op: Op::Lt,
11039                inputs: vec![l, r],
11040                shape: Shape::from_dims(&[5]),
11041                dtype: DType::Bool,
11042            });
11043            g.set_target_backend(lt, BackendId::Cpu);
11044            (l, r, lt)
11045        };
11046        let mut inputs = StorageCache::new();
11047        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11048        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11049        let (result_arc, _) = PipelinedExecutor::realize(graph, lt_id, inputs).expect("realize");
11050        let guard = result_arc.read().unwrap();
11051        assert_eq!(guard.dtype, DType::Bool);
11052        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11053            panic!("expected Cpu storage");
11054        };
11055        let mask: &[u8] = c.as_slice().expect("u8 view");
11056        // 1.0 < 2.0 → 1;  5.0 < 5.0 → 0 (strict);  3.0 < 3.0 → 0;
11057        // NaN < 0.0 → 0 (unordered);  -1.0 < 0.0 → 1.
11058        assert_eq!(mask, &[1, 0, 0, 0, 1]);
11059    }
11060
11061    /// E2E: Op::Le F32 → Bool mask. Distinct from Lt at the equal slot
11062    /// (`5.0 <= 5.0` = 1, vs Lt's `5.0 < 5.0` = 0). NaN unordered → 0.
11063    #[test]
11064    fn pipelined_realize_le_f32_to_bool_mask() {
11065        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -1.0]);
11066        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 2.0, 0.0, 0.0]);
11067        let graph = Arc::new(RwLock::new(Graph::new()));
11068        let (l_id, r_id, le_id) = {
11069            let mut g = graph.write().unwrap();
11070            let l = g.push(Node {
11071                op: Op::Const,
11072                inputs: vec![],
11073                shape: Shape::from_dims(&[5]),
11074                dtype: DType::F32,
11075            });
11076            let r = g.push(Node {
11077                op: Op::Const,
11078                inputs: vec![],
11079                shape: Shape::from_dims(&[5]),
11080                dtype: DType::F32,
11081            });
11082            let le = g.push(Node {
11083                op: Op::Le,
11084                inputs: vec![l, r],
11085                shape: Shape::from_dims(&[5]),
11086                dtype: DType::Bool,
11087            });
11088            g.set_target_backend(le, BackendId::Cpu);
11089            (l, r, le)
11090        };
11091        let mut inputs = StorageCache::new();
11092        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11093        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11094        let (result_arc, _) = PipelinedExecutor::realize(graph, le_id, inputs).expect("realize");
11095        let guard = result_arc.read().unwrap();
11096        assert_eq!(guard.dtype, DType::Bool);
11097        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11098            panic!("expected Cpu storage");
11099        };
11100        let mask: &[u8] = c.as_slice().expect("u8 view");
11101        // 1.0 <= 2.0 → 1;  5.0 <= 5.0 → 1 (key Lt difference);
11102        // 3.0 <= 2.0 → 0;  NaN <= 0.0 → 0 (unordered);  -1.0 <= 0.0 → 1.
11103        assert_eq!(mask, &[1, 1, 0, 0, 1]);
11104    }
11105
11106    /// E2E: Op::Gt F32 → Bool mask. Strict-greater: equality slot is
11107    /// `0`. NaN unordered → `0`.
11108    #[test]
11109    fn pipelined_realize_gt_f32_to_bool_mask() {
11110        let lhs = fuel_memory::from_slice_cpu(&[3.0_f32, 5.0, 2.0, f32::NAN, 1.0]);
11111        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 3.0, 0.0, 0.0]);
11112        let graph = Arc::new(RwLock::new(Graph::new()));
11113        let (l_id, r_id, gt_id) = {
11114            let mut g = graph.write().unwrap();
11115            let l = g.push(Node {
11116                op: Op::Const,
11117                inputs: vec![],
11118                shape: Shape::from_dims(&[5]),
11119                dtype: DType::F32,
11120            });
11121            let r = g.push(Node {
11122                op: Op::Const,
11123                inputs: vec![],
11124                shape: Shape::from_dims(&[5]),
11125                dtype: DType::F32,
11126            });
11127            let gt = g.push(Node {
11128                op: Op::Gt,
11129                inputs: vec![l, r],
11130                shape: Shape::from_dims(&[5]),
11131                dtype: DType::Bool,
11132            });
11133            g.set_target_backend(gt, BackendId::Cpu);
11134            (l, r, gt)
11135        };
11136        let mut inputs = StorageCache::new();
11137        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11138        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11139        let (result_arc, _) = PipelinedExecutor::realize(graph, gt_id, inputs).expect("realize");
11140        let guard = result_arc.read().unwrap();
11141        assert_eq!(guard.dtype, DType::Bool);
11142        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11143            panic!("expected Cpu storage");
11144        };
11145        let mask: &[u8] = c.as_slice().expect("u8 view");
11146        // 3.0 > 2.0 → 1;  5.0 > 5.0 → 0 (strict);  2.0 > 3.0 → 0;
11147        // NaN > 0.0 → 0 (unordered);  1.0 > 0.0 → 1.
11148        assert_eq!(mask, &[1, 0, 0, 0, 1]);
11149    }
11150
11151    /// E2E: Op::Ge F32 → Bool mask. Greater-or-equal: equality slot
11152    /// is `1` (distinguishes from Gt). NaN unordered → `0`. Closes
11153    /// the comparison family with full `[Eq, Ne, Lt, Le, Gt, Ge]`
11154    /// coverage.
11155    #[test]
11156    fn pipelined_realize_ge_f32_to_bool_mask() {
11157        let lhs = fuel_memory::from_slice_cpu(&[3.0_f32, 5.0, 2.0, f32::NAN, 0.0]);
11158        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 3.0, 0.0, 0.0]);
11159        let graph = Arc::new(RwLock::new(Graph::new()));
11160        let (l_id, r_id, ge_id) = {
11161            let mut g = graph.write().unwrap();
11162            let l = g.push(Node {
11163                op: Op::Const,
11164                inputs: vec![],
11165                shape: Shape::from_dims(&[5]),
11166                dtype: DType::F32,
11167            });
11168            let r = g.push(Node {
11169                op: Op::Const,
11170                inputs: vec![],
11171                shape: Shape::from_dims(&[5]),
11172                dtype: DType::F32,
11173            });
11174            let ge = g.push(Node {
11175                op: Op::Ge,
11176                inputs: vec![l, r],
11177                shape: Shape::from_dims(&[5]),
11178                dtype: DType::Bool,
11179            });
11180            g.set_target_backend(ge, BackendId::Cpu);
11181            (l, r, ge)
11182        };
11183        let mut inputs = StorageCache::new();
11184        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11185        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11186        let (result_arc, _) = PipelinedExecutor::realize(graph, ge_id, inputs).expect("realize");
11187        let guard = result_arc.read().unwrap();
11188        assert_eq!(guard.dtype, DType::Bool);
11189        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11190            panic!("expected Cpu storage");
11191        };
11192        let mask: &[u8] = c.as_slice().expect("u8 view");
11193        // 3.0 >= 2.0 → 1;  5.0 >= 5.0 → 1 (key Gt difference);
11194        // 2.0 >= 3.0 → 0;  NaN >= 0.0 → 0 (unordered);  0.0 >= 0.0 → 1.
11195        assert_eq!(mask, &[1, 1, 0, 0, 1]);
11196    }
11197
11198    /// E2E: Op::Equal F64 → Bool mask. Confirms the F64 wrapper is
11199    /// independently registered and routed (binding-table key
11200    /// `(EqualElementwise, [F64, F64, U8], Cpu)`).
11201    #[test]
11202    fn pipelined_realize_eq_f64_to_bool_mask() {
11203        let lhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0]);
11204        let rhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 4.0]);
11205        let graph = Arc::new(RwLock::new(Graph::new()));
11206        let (l_id, r_id, eq_id) = {
11207            let mut g = graph.write().unwrap();
11208            let l = g.push(Node {
11209                op: Op::Const,
11210                inputs: vec![],
11211                shape: Shape::from_dims(&[3]),
11212                dtype: DType::F64,
11213            });
11214            let r = g.push(Node {
11215                op: Op::Const,
11216                inputs: vec![],
11217                shape: Shape::from_dims(&[3]),
11218                dtype: DType::F64,
11219            });
11220            let eq = g.push(Node {
11221                op: Op::Equal,
11222                inputs: vec![l, r],
11223                shape: Shape::from_dims(&[3]),
11224                dtype: DType::Bool,
11225            });
11226            g.set_target_backend(eq, BackendId::Cpu);
11227            (l, r, eq)
11228        };
11229        let mut inputs = StorageCache::new();
11230        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11231        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11232        let (result_arc, _) = PipelinedExecutor::realize(graph, eq_id, inputs).expect("realize");
11233        let guard = result_arc.read().unwrap();
11234        assert_eq!(guard.dtype, DType::Bool);
11235        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11236            panic!("expected Cpu storage");
11237        };
11238        let mask: &[u8] = c.as_slice().expect("u8 view");
11239        assert_eq!(mask, &[1, 1, 0]);
11240    }
11241
11242    /// E2E: Op::Where ternary select — `out[i] = if cond[i] != 0 { a[i] } else { b[i] }`.
11243    /// Validates (a) the binding-table key `(Where, [Bool, F32, F32, F32], Cpu)`
11244    /// resolves to the where_f32 wrapper, (b) the Bool cond input drives
11245    /// the per-slot pick, (c) outputs preserve the input dtype.
11246    ///
11247    /// GAP-168(c): the cond STORAGE is tagged Bool, not merely the graph node.
11248    /// Bool and U8 are byte-identical, so leaving the storage U8 under a Bool
11249    /// node is exactly the mismatch this cut exists to make visible.
11250    #[test]
11251    fn pipelined_realize_where_f32_picks_per_slot_from_bool_mask() {
11252        // cond = [1, 0, 1, 0, 1]; a = [1, 2, 3, 4, 5]; b = [10, 20, 30, 40, 50]
11253        // expected = [1, 20, 3, 40, 5]
11254        let mut cond_storage = fuel_memory::from_slice_cpu(&[1u8, 0, 1, 0, 1]);
11255        cond_storage.dtype = DType::Bool; // GAP-168(c): a Bool mask, not U8 bytes
11256        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0]);
11257        let b_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0]);
11258        let graph = Arc::new(RwLock::new(Graph::new()));
11259        let (cond_id, a_id, b_id, where_id) = {
11260            let mut g = graph.write().unwrap();
11261            let cond = g.push(Node {
11262                op: Op::Const,
11263                inputs: vec![],
11264                shape: Shape::from_dims(&[5]),
11265                dtype: DType::Bool,
11266            });
11267            let a = g.push(Node {
11268                op: Op::Const,
11269                inputs: vec![],
11270                shape: Shape::from_dims(&[5]),
11271                dtype: DType::F32,
11272            });
11273            let b = g.push(Node {
11274                op: Op::Const,
11275                inputs: vec![],
11276                shape: Shape::from_dims(&[5]),
11277                dtype: DType::F32,
11278            });
11279            let w = g.push(Node {
11280                op: Op::Where,
11281                inputs: vec![cond, a, b],
11282                shape: Shape::from_dims(&[5]),
11283                dtype: DType::F32,
11284            });
11285            g.set_target_backend(w, BackendId::Cpu);
11286            (cond, a, b, w)
11287        };
11288        let mut inputs = StorageCache::new();
11289        inputs.insert(cond_id, Arc::new(RwLock::new(cond_storage)));
11290        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
11291        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
11292        let (result_arc, _) = PipelinedExecutor::realize(graph, where_id, inputs).expect("realize");
11293        let guard = result_arc.read().unwrap();
11294        assert_eq!(guard.dtype, DType::F32);
11295        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11296            panic!("expected Cpu storage");
11297        };
11298        let out: &[f32] = c.as_slice().expect("f32 view");
11299        assert_eq!(out, &[1.0, 20.0, 3.0, 40.0, 5.0]);
11300    }
11301
11302    /// E2E: full chain `eq → where`. Compares two f32 vectors, then
11303    /// uses the resulting Bool mask to pick from a third tensor (or a
11304    /// fallback). Validates the comparison-family + Where ops compose
11305    /// end-to-end.
11306    #[test]
11307    fn pipelined_realize_eq_then_where_full_chain() {
11308        // a = [1, 2, 3]; b = [1, 5, 3] → eq = [1, 0, 1]
11309        // pick = [10, 20, 30]; fallback = [99, 99, 99]
11310        // result = [10, 99, 30]
11311        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
11312        let b_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0]);
11313        let pick_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
11314        let fb_storage = fuel_memory::from_slice_cpu(&[99.0_f32, 99.0, 99.0]);
11315        let graph = Arc::new(RwLock::new(Graph::new()));
11316        let (a_id, b_id, pick_id, fb_id, where_id) = {
11317            let mut g = graph.write().unwrap();
11318            let a = g.push(Node {
11319                op: Op::Const,
11320                inputs: vec![],
11321                shape: Shape::from_dims(&[3]),
11322                dtype: DType::F32,
11323            });
11324            let b = g.push(Node {
11325                op: Op::Const,
11326                inputs: vec![],
11327                shape: Shape::from_dims(&[3]),
11328                dtype: DType::F32,
11329            });
11330            let pick = g.push(Node {
11331                op: Op::Const,
11332                inputs: vec![],
11333                shape: Shape::from_dims(&[3]),
11334                dtype: DType::F32,
11335            });
11336            let fb = g.push(Node {
11337                op: Op::Const,
11338                inputs: vec![],
11339                shape: Shape::from_dims(&[3]),
11340                dtype: DType::F32,
11341            });
11342            let eq = g.push(Node {
11343                op: Op::Equal,
11344                inputs: vec![a, b],
11345                shape: Shape::from_dims(&[3]),
11346                dtype: DType::Bool,
11347            });
11348            let w = g.push(Node {
11349                op: Op::Where,
11350                inputs: vec![eq, pick, fb],
11351                shape: Shape::from_dims(&[3]),
11352                dtype: DType::F32,
11353            });
11354            g.set_target_backend(eq, BackendId::Cpu);
11355            g.set_target_backend(w, BackendId::Cpu);
11356            (a, b, pick, fb, w)
11357        };
11358        let mut inputs = StorageCache::new();
11359        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
11360        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
11361        inputs.insert(pick_id, Arc::new(RwLock::new(pick_storage)));
11362        inputs.insert(fb_id, Arc::new(RwLock::new(fb_storage)));
11363        let (result_arc, _) = PipelinedExecutor::realize(graph, where_id, inputs).expect("realize");
11364        let guard = result_arc.read().unwrap();
11365        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11366            panic!("expected Cpu storage");
11367        };
11368        let out: &[f32] = c.as_slice().expect("f32 view");
11369        assert_eq!(out, &[10.0, 99.0, 30.0]);
11370    }
11371
11372    /// E2E: Q4_0 QMatMul through the pipelined executor — proves
11373    /// quantized weights can flow into the unified path. Activations
11374    /// are F32, weights are U32-typed (raw block bytes).
11375    /// Construct a Q4_0 weight tensor where every weight = 1.0
11376    /// (d=1.0, every nibble=9 → 1*(9-8)=1), so A @ W^T computes
11377    /// the per-row sum of activations.
11378    #[test]
11379    fn pipelined_realize_qmatmul_q4_0_unit_weight_sums_activations() {
11380        use fuel_graph::QuantType;
11381        use half::f16;
11382        let block_size = std::mem::size_of::<fuel_quantized::BlockQ4_0>();
11383        let mut w_bytes = vec![0u8; 2 * block_size];
11384        for block_idx in 0..2 {
11385            let off = block_idx * block_size;
11386            let d_bytes = f16::from_f32(1.0).to_le_bytes();
11387            w_bytes[off..off + 2].copy_from_slice(&d_bytes);
11388            for i in 0..16 {
11389                w_bytes[off + 2 + i] = 0x99;
11390            }
11391        }
11392        // Weight tensor is U32-typed (rank-1, length = bytes/4)
11393        let w_storage = fuel_memory::Storage::new(
11394            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
11395                &w_bytes,
11396            )),
11397            DType::U32,
11398        );
11399
11400        let act_vec: Vec<f32> = (1..=32).map(|x| x as f32).collect();
11401        let act_storage = fuel_memory::from_slice_cpu(&act_vec);
11402
11403        let graph = Arc::new(RwLock::new(Graph::new()));
11404        let (act_id, w_id, mm_id) = {
11405            let mut g = graph.write().unwrap();
11406            let act = g.push(Node {
11407                op: Op::Const,
11408                inputs: vec![],
11409                shape: Shape::from_dims(&[1, 32]),
11410                dtype: DType::F32,
11411            });
11412            let w = g.push(Node {
11413                op: Op::Const,
11414                inputs: vec![],
11415                shape: Shape::from_dims(&[w_bytes.len() / 4]),
11416                dtype: DType::U32,
11417            });
11418            let mm = g.push(Node {
11419                op: Op::Fused(
11420                    fuel_graph::registry::FusedOps::QMATMUL,
11421                    fuel_graph::registry::FusedOpParams::QMatMul {
11422                        quant_type: QuantType::Q4_0,
11423                        k: 32,
11424                        n: 2,
11425                    },
11426                ),
11427                inputs: vec![act, w],
11428                shape: Shape::from_dims(&[1, 2]),
11429                dtype: DType::F32,
11430            });
11431            g.set_target_backend(mm, BackendId::Cpu);
11432            (act, w, mm)
11433        };
11434        let mut inputs = StorageCache::new();
11435        inputs.insert(act_id, Arc::new(RwLock::new(act_storage)));
11436        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
11437        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11438        let guard = result_arc.read().unwrap();
11439        assert_eq!(guard.dtype, DType::F32);
11440        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11441            panic!("expected Cpu storage");
11442        };
11443        let r: &[f32] = c.as_slice().unwrap();
11444        // Both rows = sum(1..=32) = 528, within Q8_1 round-trip
11445        // tolerance.
11446        assert!((r[0] - 528.0).abs() < 0.5, "got {}, want 528", r[0]);
11447        assert!((r[1] - 528.0).abs() < 0.5, "got {}, want 528", r[1]);
11448    }
11449
11450    /// E2E: QMatMul with Q5_0 weights — verifies the new quant
11451    /// dispatch arm picks `qmatmul_q5_0_f32`. We build weights by
11452    /// quantizing all-ones via `BlockQ5_0::from_float`, then
11453    /// compare pipelined output against the direct fuel_quantized
11454    /// matmul on the same blocks.
11455    #[test]
11456    fn pipelined_realize_qmatmul_q5_0_against_reference() {
11457        use fuel_graph::QuantType;
11458        use fuel_quantized::{BlockQ5_0, GgmlType};
11459        let n = 2;
11460        let k = 64; // 2 blocks per row
11461        // Quantize an all-ones [n, k] weight matrix.
11462        let w_f32 = vec![1.0_f32; n * k];
11463        let blocks_per_row = k / BlockQ5_0::BLCK_SIZE;
11464        let mut w_blocks = vec![BlockQ5_0::zeros(); n * blocks_per_row];
11465        BlockQ5_0::from_float(&w_f32, &mut w_blocks);
11466        // Reinterpret block slice as bytes (BlockQ5_0 is #[repr(C)]).
11467        let bytes_per_block = std::mem::size_of::<BlockQ5_0>();
11468        let w_bytes: Vec<u8> = unsafe {
11469            std::slice::from_raw_parts(
11470                w_blocks.as_ptr() as *const u8,
11471                w_blocks.len() * bytes_per_block,
11472            )
11473        }
11474        .to_vec();
11475        let w_storage = fuel_memory::Storage::new(
11476            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
11477                &w_bytes,
11478            )),
11479            DType::U32,
11480        );
11481        let act_vec: Vec<f32> = (1..=k).map(|x| x as f32).collect();
11482        let act_storage = fuel_memory::from_slice_cpu(&act_vec);
11483        // Reference: direct matmul through fuel_quantized.
11484        let mut ref_out = vec![0.0_f32; n];
11485        fuel_quantized::matmul::<BlockQ5_0>((1, k, n), &act_vec, &w_blocks, &mut ref_out)
11486            .expect("ref matmul");
11487
11488        let graph = Arc::new(RwLock::new(Graph::new()));
11489        let (act_id, w_id, mm_id) = {
11490            let mut g = graph.write().unwrap();
11491            let act = g.push(Node {
11492                op: Op::Const,
11493                inputs: vec![],
11494                shape: Shape::from_dims(&[1, k]),
11495                dtype: DType::F32,
11496            });
11497            let w = g.push(Node {
11498                op: Op::Const,
11499                inputs: vec![],
11500                shape: Shape::from_dims(&[w_bytes.len() / 4]),
11501                dtype: DType::U32,
11502            });
11503            let mm = g.push(Node {
11504                op: Op::Fused(
11505                    fuel_graph::registry::FusedOps::QMATMUL,
11506                    fuel_graph::registry::FusedOpParams::QMatMul {
11507                        quant_type: QuantType::Q5_0,
11508                        k,
11509                        n,
11510                    },
11511                ),
11512                inputs: vec![act, w],
11513                shape: Shape::from_dims(&[1, n]),
11514                dtype: DType::F32,
11515            });
11516            g.set_target_backend(mm, BackendId::Cpu);
11517            (act, w, mm)
11518        };
11519        let mut inputs = StorageCache::new();
11520        inputs.insert(act_id, Arc::new(RwLock::new(act_storage)));
11521        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
11522        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11523        let guard = result_arc.read().unwrap();
11524        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11525            panic!("expected Cpu storage");
11526        };
11527        let r: &[f32] = c.as_slice().unwrap();
11528        // Bit-exact against same kernel via the trait, since both
11529        // paths run fuel_quantized::matmul<BlockQ5_0>.
11530        assert_eq!(
11531            r,
11532            ref_out.as_slice(),
11533            "pipelined Q5_0 differs from reference: got {r:?}, want {ref_out:?}"
11534        );
11535    }
11536
11537    /// E2E: QMatMul with Q6K (256-element super-block k-quant).
11538    /// Same idea as the Q5_0 test — bit-exact against the
11539    /// reference fuel_quantized::matmul<BlockQ6K>. Confirms the
11540    /// dispatch arm wires `qmatmul_q6k_f32` correctly.
11541    #[test]
11542    fn pipelined_realize_qmatmul_q6k_against_reference() {
11543        use fuel_graph::QuantType;
11544        use fuel_quantized::{BlockQ6K, GgmlType};
11545        let n = 2;
11546        let k = 256; // 1 super-block per row
11547        let w_f32 = vec![1.0_f32; n * k];
11548        let blocks_per_row = k / BlockQ6K::BLCK_SIZE;
11549        let mut w_blocks = vec![BlockQ6K::zeros(); n * blocks_per_row];
11550        BlockQ6K::from_float(&w_f32, &mut w_blocks);
11551        let bytes_per_block = std::mem::size_of::<BlockQ6K>();
11552        let w_bytes: Vec<u8> = unsafe {
11553            std::slice::from_raw_parts(
11554                w_blocks.as_ptr() as *const u8,
11555                w_blocks.len() * bytes_per_block,
11556            )
11557        }
11558        .to_vec();
11559        let w_storage = fuel_memory::Storage::new(
11560            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
11561                &w_bytes,
11562            )),
11563            DType::U32,
11564        );
11565        let act_vec: Vec<f32> = (1..=k).map(|x| x as f32 / 100.0).collect();
11566        let act_storage = fuel_memory::from_slice_cpu(&act_vec);
11567        let mut ref_out = vec![0.0_f32; n];
11568        fuel_quantized::matmul::<BlockQ6K>((1, k, n), &act_vec, &w_blocks, &mut ref_out)
11569            .expect("ref matmul");
11570
11571        let graph = Arc::new(RwLock::new(Graph::new()));
11572        let (act_id, w_id, mm_id) = {
11573            let mut g = graph.write().unwrap();
11574            let act = g.push(Node {
11575                op: Op::Const,
11576                inputs: vec![],
11577                shape: Shape::from_dims(&[1, k]),
11578                dtype: DType::F32,
11579            });
11580            let w = g.push(Node {
11581                op: Op::Const,
11582                inputs: vec![],
11583                shape: Shape::from_dims(&[w_bytes.len() / 4]),
11584                dtype: DType::U32,
11585            });
11586            let mm = g.push(Node {
11587                op: Op::Fused(
11588                    fuel_graph::registry::FusedOps::QMATMUL,
11589                    fuel_graph::registry::FusedOpParams::QMatMul {
11590                        quant_type: QuantType::Q6K,
11591                        k,
11592                        n,
11593                    },
11594                ),
11595                inputs: vec![act, w],
11596                shape: Shape::from_dims(&[1, n]),
11597                dtype: DType::F32,
11598            });
11599            g.set_target_backend(mm, BackendId::Cpu);
11600            (act, w, mm)
11601        };
11602        let mut inputs = StorageCache::new();
11603        inputs.insert(act_id, Arc::new(RwLock::new(act_storage)));
11604        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
11605        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11606        let guard = result_arc.read().unwrap();
11607        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11608            panic!("expected Cpu storage");
11609        };
11610        let r: &[f32] = c.as_slice().unwrap();
11611        assert_eq!(
11612            r,
11613            ref_out.as_slice(),
11614            "pipelined Q6K differs from reference: got {r:?}, want {ref_out:?}"
11615        );
11616    }
11617
11618    /// E2E: BF16 RmsNormLastDim through the pipelined executor.
11619    /// Verifies that capability-driven dispatch routes the
11620    /// half-float norm op to the bf16-specific kernel (which
11621    /// accumulates in f32 internally).
11622    #[test]
11623    fn pipelined_realize_rms_norm_bf16() {
11624        let v: Vec<half::bf16> = [3.0_f32, 4.0]
11625            .iter()
11626            .map(|&x| half::bf16::from_f32(x))
11627            .collect();
11628        let storage = fuel_memory::from_slice_cpu(&v);
11629        let graph = Arc::new(RwLock::new(Graph::new()));
11630        let (in_id, op_id) = {
11631            let mut g = graph.write().unwrap();
11632            let in_id = g.push(Node {
11633                op: Op::Const,
11634                inputs: vec![],
11635                shape: Shape::from_dims(&[1, 2]),
11636                dtype: DType::BF16,
11637            });
11638            let op_id = g.push(Node {
11639                op: Op::Fused(
11640                    fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM,
11641                    fuel_graph::registry::FusedOpParams::RmsNormLastDim { eps: 0.0 },
11642                ),
11643                inputs: vec![in_id],
11644                shape: Shape::from_dims(&[1, 2]),
11645                dtype: DType::BF16,
11646            });
11647            g.set_target_backend(op_id, BackendId::Cpu);
11648            (in_id, op_id)
11649        };
11650        let mut inputs = StorageCache::new();
11651        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11652        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
11653        let guard = result_arc.read().unwrap();
11654        assert_eq!(guard.dtype, DType::BF16);
11655        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11656            panic!("expected Cpu storage");
11657        };
11658        let r: &[half::bf16] = c.as_slice().unwrap();
11659        let rms = (12.5_f32).sqrt();
11660        // bf16's ~3-digit mantissa absorbs the divisor; allow ~5%.
11661        assert!((r[0].to_f32() - 3.0 / rms).abs() < 0.05);
11662        assert!((r[1].to_f32() - 4.0 / rms).abs() < 0.05);
11663    }
11664
11665    /// E2E: BF16 matmul through the pipelined executor — proves
11666    /// the LLM forward-pass blocker (every transformer layer
11667    /// is dominated by matmul). Identity matmul on bf16 round-
11668    /// trips small integers exactly.
11669    #[test]
11670    fn pipelined_realize_matmul_bf16_identity() {
11671        let lhs_v: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0]
11672            .iter()
11673            .map(|&x| half::bf16::from_f32(x))
11674            .collect();
11675        let rhs_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0]
11676            .iter()
11677            .map(|&x| half::bf16::from_f32(x))
11678            .collect();
11679        let lhs = fuel_memory::from_slice_cpu(&lhs_v);
11680        let rhs = fuel_memory::from_slice_cpu(&rhs_v);
11681        let graph = Arc::new(RwLock::new(Graph::new()));
11682        let (l_id, r_id, mm_id) = {
11683            let mut g = graph.write().unwrap();
11684            let l = g.push(Node {
11685                op: Op::Const,
11686                inputs: vec![],
11687                shape: Shape::from_dims(&[2, 2]),
11688                dtype: DType::BF16,
11689            });
11690            let r = g.push(Node {
11691                op: Op::Const,
11692                inputs: vec![],
11693                shape: Shape::from_dims(&[2, 2]),
11694                dtype: DType::BF16,
11695            });
11696            let mm = g.push(Node {
11697                op: Op::MatMul,
11698                inputs: vec![l, r],
11699                shape: Shape::from_dims(&[2, 2]),
11700                dtype: DType::BF16,
11701            });
11702            g.set_target_backend(mm, BackendId::Cpu);
11703            (l, r, mm)
11704        };
11705        let mut inputs = StorageCache::new();
11706        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11707        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11708        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11709        let guard = result_arc.read().unwrap();
11710        assert_eq!(guard.dtype, DType::BF16);
11711        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11712            panic!("expected Cpu storage");
11713        };
11714        let r: &[half::bf16] = c.as_slice().unwrap();
11715        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
11716        assert_eq!(result_f32, vec![1.0, 2.0, 3.0, 4.0]);
11717    }
11718
11719    /// E2E (ROADMAP row 34): a mixed `[F32, W, F32]` matmul (f32 activation, half weight) runs on
11720    /// the CPU through the NATIVE kernel, with the weight left half-width: the output is f32 and
11721    /// equals the f64 matmul over the widened weights to f32 accumulation error. The weight is
11722    /// rounded to its stored half type first.
11723    fn mixed_cpu_matmul_matches_f64(weight_dtype: DType) {
11724        let (m, n, k) = (3_usize, 5_usize, 7_usize);
11725        let a: Vec<f32> = (0..m * k)
11726            .map(|i| ((i * 37 % 19) as f32 - 9.0) / 8.0)
11727            .collect();
11728        let w_f32: Vec<f32> = (0..k * n)
11729            .map(|i| ((i * 53 % 23) as f32 - 11.0) / 10.0)
11730            .collect();
11731        let (w_storage, widened): (_, Vec<f32>) = if weight_dtype == DType::BF16 {
11732            let h: Vec<half::bf16> = w_f32.iter().map(|&x| half::bf16::from_f32(x)).collect();
11733            let wide = h.iter().map(|x| x.to_f32()).collect();
11734            (fuel_memory::from_slice_cpu(&h), wide)
11735        } else {
11736            let h: Vec<half::f16> = w_f32.iter().map(|&x| half::f16::from_f32(x)).collect();
11737            let wide = h.iter().map(|x| x.to_f32()).collect();
11738            (fuel_memory::from_slice_cpu(&h), wide)
11739        };
11740        let graph = Arc::new(RwLock::new(Graph::new()));
11741        let (l_id, r_id, mm_id) = {
11742            let mut g = graph.write().unwrap();
11743            let l = g.push(Node {
11744                op: Op::Const,
11745                inputs: vec![],
11746                shape: Shape::from_dims(&[m, k]),
11747                dtype: DType::F32,
11748            });
11749            let r = g.push(Node {
11750                op: Op::Const,
11751                inputs: vec![],
11752                shape: Shape::from_dims(&[k, n]),
11753                dtype: weight_dtype,
11754            });
11755            let mm = g.push(Node {
11756                op: Op::MatMul,
11757                inputs: vec![l, r],
11758                shape: Shape::from_dims(&[m, n]),
11759                dtype: DType::F32,
11760            });
11761            g.set_target_backend(mm, BackendId::Cpu);
11762            (l, r, mm)
11763        };
11764        let mut inputs = StorageCache::new();
11765        inputs.insert(l_id, Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&a))));
11766        inputs.insert(r_id, Arc::new(RwLock::new(w_storage)));
11767        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11768        let guard = result_arc.read().unwrap();
11769        assert_eq!(guard.dtype, DType::F32);
11770        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11771            panic!("expected Cpu storage");
11772        };
11773        let got: &[f32] = c.as_slice().unwrap();
11774        for i in 0..m {
11775            for j in 0..n {
11776                let want: f64 = (0..k)
11777                    .map(|kk| a[i * k + kk] as f64 * widened[kk * n + j] as f64)
11778                    .sum();
11779                let err = (got[i * n + j] as f64 - want).abs();
11780                assert!(
11781                    err < 1e-5,
11782                    "{weight_dtype:?} [{i},{j}]: got {}, want {want}",
11783                    got[i * n + j]
11784                );
11785            }
11786        }
11787    }
11788
11789    #[test]
11790    fn pipelined_realize_mixed_f32_bf16_matmul_is_native_on_cpu() {
11791        mixed_cpu_matmul_matches_f64(DType::BF16);
11792    }
11793
11794    #[test]
11795    fn pipelined_realize_mixed_f32_f16_matmul_is_native_on_cpu() {
11796        mixed_cpu_matmul_matches_f64(DType::F16);
11797    }
11798
11799    /// E2E: F16 sum-reduce — verifies bf16/f16 reduction dispatch
11800    /// works through the executor.
11801    #[test]
11802    fn pipelined_realize_sum_dim_f16() {
11803        let v: Vec<half::f16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]
11804            .iter()
11805            .map(|&x| half::f16::from_f32(x))
11806            .collect();
11807        let storage = fuel_memory::from_slice_cpu(&v);
11808        let graph = Arc::new(RwLock::new(Graph::new()));
11809        let (in_id, sum_id) = {
11810            let mut g = graph.write().unwrap();
11811            let in_id = g.push(Node {
11812                op: Op::Const,
11813                inputs: vec![],
11814                shape: Shape::from_dims(&[2, 3]),
11815                dtype: DType::F16,
11816            });
11817            let sum_id = g.push(Node {
11818                op: Op::SumDim(1),
11819                inputs: vec![in_id],
11820                shape: Shape::from_dims(&[2]),
11821                dtype: DType::F16,
11822            });
11823            g.set_target_backend(sum_id, BackendId::Cpu);
11824            (in_id, sum_id)
11825        };
11826        let mut inputs = StorageCache::new();
11827        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11828        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
11829        let guard = result_arc.read().unwrap();
11830        assert_eq!(guard.dtype, DType::F16);
11831        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11832            panic!("expected Cpu storage");
11833        };
11834        let r: &[half::f16] = c.as_slice().unwrap();
11835        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
11836        assert_eq!(result_f32, vec![6.0, 15.0]);
11837    }
11838
11839    /// E2E: BF16 elementwise add through the pipelined executor.
11840    #[test]
11841    fn pipelined_realize_add_bf16() {
11842        let lhs_vec: Vec<half::bf16> = [1.0_f32, 2.0, 3.0]
11843            .iter()
11844            .map(|&x| half::bf16::from_f32(x))
11845            .collect();
11846        let rhs_vec: Vec<half::bf16> = [10.0_f32, 20.0, 30.0]
11847            .iter()
11848            .map(|&x| half::bf16::from_f32(x))
11849            .collect();
11850        let lhs = fuel_memory::from_slice_cpu(&lhs_vec);
11851        let rhs = fuel_memory::from_slice_cpu(&rhs_vec);
11852        let graph = Arc::new(RwLock::new(Graph::new()));
11853        let (l_id, r_id, op_id) = {
11854            let mut g = graph.write().unwrap();
11855            let l = g.push(Node {
11856                op: Op::Const,
11857                inputs: vec![],
11858                shape: Shape::from_dims(&[3]),
11859                dtype: DType::BF16,
11860            });
11861            let r = g.push(Node {
11862                op: Op::Const,
11863                inputs: vec![],
11864                shape: Shape::from_dims(&[3]),
11865                dtype: DType::BF16,
11866            });
11867            let op = g.push(Node {
11868                op: Op::Add,
11869                inputs: vec![l, r],
11870                shape: Shape::from_dims(&[3]),
11871                dtype: DType::BF16,
11872            });
11873            g.set_target_backend(op, BackendId::Cpu);
11874            (l, r, op)
11875        };
11876        let mut inputs = StorageCache::new();
11877        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11878        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11879        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
11880        let guard = result_arc.read().unwrap();
11881        assert_eq!(guard.dtype, DType::BF16);
11882        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11883            panic!("expected Cpu storage");
11884        };
11885        let r: &[half::bf16] = c.as_slice().unwrap();
11886        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
11887        assert_eq!(result_f32, vec![11.0, 22.0, 33.0]);
11888    }
11889
11890    /// E2E: F16 unary chain — Const + Sqr + Sqrt — verifies F16
11891    /// dispatch works and the via-f32 round-trip kernels behave
11892    /// correctly through the executor.
11893    #[test]
11894    fn pipelined_realize_sqr_then_sqrt_f16() {
11895        let v: Vec<half::f16> = [1.0_f32, 4.0, 9.0]
11896            .iter()
11897            .map(|&x| half::f16::from_f32(x))
11898            .collect();
11899        let storage = fuel_memory::from_slice_cpu(&v);
11900        let graph = Arc::new(RwLock::new(Graph::new()));
11901        let (in_id, sqrt_id) = {
11902            let mut g = graph.write().unwrap();
11903            let in_id = g.push(Node {
11904                op: Op::Const,
11905                inputs: vec![],
11906                shape: Shape::from_dims(&[3]),
11907                dtype: DType::F16,
11908            });
11909            let sqr_id = g.push(Node {
11910                op: Op::Sqr,
11911                inputs: vec![in_id],
11912                shape: Shape::from_dims(&[3]),
11913                dtype: DType::F16,
11914            });
11915            let sqrt_id = g.push(Node {
11916                op: Op::Sqrt,
11917                inputs: vec![sqr_id],
11918                shape: Shape::from_dims(&[3]),
11919                dtype: DType::F16,
11920            });
11921            g.set_target_backend(sqr_id, BackendId::Cpu);
11922            g.set_target_backend(sqrt_id, BackendId::Cpu);
11923            (in_id, sqrt_id)
11924        };
11925        let mut inputs = StorageCache::new();
11926        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11927        let (result_arc, _) = PipelinedExecutor::realize(graph, sqrt_id, inputs).expect("realize");
11928        let guard = result_arc.read().unwrap();
11929        assert_eq!(guard.dtype, DType::F16);
11930        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11931            panic!("expected Cpu storage");
11932        };
11933        let r: &[half::f16] = c.as_slice().unwrap();
11934        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
11935        // f16 has ~3 decimal digits; sqrt(sqr(x)) = |x| within rounding.
11936        for (got, want) in result_f32.iter().zip(&[1.0_f32, 4.0, 9.0]) {
11937            assert!((got - want).abs() < 0.05, "got {got}, want {want}");
11938        }
11939    }
11940
11941    /// E2E: F64 sum-reduce along one dim through the pipelined
11942    /// executor.
11943    #[test]
11944    fn pipelined_realize_sum_dim_f64() {
11945        let storage = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
11946        let graph = Arc::new(RwLock::new(Graph::new()));
11947        let (in_id, sum_id) = {
11948            let mut g = graph.write().unwrap();
11949            let in_id = g.push(Node {
11950                op: Op::Const,
11951                inputs: vec![],
11952                shape: Shape::from_dims(&[2, 3]),
11953                dtype: DType::F64,
11954            });
11955            let sum_id = g.push(Node {
11956                op: Op::SumDim(1),
11957                inputs: vec![in_id],
11958                shape: Shape::from_dims(&[2]),
11959                dtype: DType::F64,
11960            });
11961            g.set_target_backend(sum_id, BackendId::Cpu);
11962            (in_id, sum_id)
11963        };
11964        let mut inputs = StorageCache::new();
11965        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11966        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
11967        let guard = result_arc.read().unwrap();
11968        assert_eq!(guard.dtype, DType::F64);
11969        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11970            panic!("expected Cpu storage");
11971        };
11972        assert_eq!(c.as_slice::<f64>().unwrap(), &[6.0_f64, 15.0]);
11973    }
11974
11975    /// E2E: F64 matmul through the pipelined executor.
11976    #[test]
11977    fn pipelined_realize_matmul_2x3_times_3x2_f64() {
11978        let lhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
11979        let rhs = fuel_memory::from_slice_cpu(&[7.0_f64, 8.0, 9.0, 10.0, 11.0, 12.0]);
11980        let graph = Arc::new(RwLock::new(Graph::new()));
11981        let (l_id, r_id, mm_id) = {
11982            let mut g = graph.write().unwrap();
11983            let l = g.push(Node {
11984                op: Op::Const,
11985                inputs: vec![],
11986                shape: Shape::from_dims(&[2, 3]),
11987                dtype: DType::F64,
11988            });
11989            let r = g.push(Node {
11990                op: Op::Const,
11991                inputs: vec![],
11992                shape: Shape::from_dims(&[3, 2]),
11993                dtype: DType::F64,
11994            });
11995            let mm = g.push(Node {
11996                op: Op::MatMul,
11997                inputs: vec![l, r],
11998                shape: Shape::from_dims(&[2, 2]),
11999                dtype: DType::F64,
12000            });
12001            g.set_target_backend(mm, BackendId::Cpu);
12002            (l, r, mm)
12003        };
12004        let mut inputs = StorageCache::new();
12005        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
12006        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
12007        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
12008        let guard = result_arc.read().unwrap();
12009        assert_eq!(guard.dtype, DType::F64);
12010        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12011            panic!("expected Cpu storage");
12012        };
12013        assert_eq!(
12014            c.as_slice::<f64>().unwrap(),
12015            &[58.0_f64, 64.0, 139.0, 154.0]
12016        );
12017    }
12018
12019    /// E2E: F64 unary chain — Const + Sqr + Sqrt — verifies that
12020    /// the kernel-binding lookup picks the f64 entries when the
12021    /// graph nodes carry DType::F64.
12022    #[test]
12023    fn pipelined_realize_sqr_then_sqrt_f64() {
12024        let storage = fuel_memory::from_slice_cpu(&[1.0_f64, 4.0, 9.0]);
12025        let graph = Arc::new(RwLock::new(Graph::new()));
12026        let (in_id, sqrt_id) = {
12027            let mut g = graph.write().unwrap();
12028            let in_id = g.push(Node {
12029                op: Op::Const,
12030                inputs: vec![],
12031                shape: Shape::from_dims(&[3]),
12032                dtype: DType::F64,
12033            });
12034            let sqr_id = g.push(Node {
12035                op: Op::Sqr,
12036                inputs: vec![in_id],
12037                shape: Shape::from_dims(&[3]),
12038                dtype: DType::F64,
12039            });
12040            let sqrt_id = g.push(Node {
12041                op: Op::Sqrt,
12042                inputs: vec![sqr_id],
12043                shape: Shape::from_dims(&[3]),
12044                dtype: DType::F64,
12045            });
12046            g.set_target_backend(sqr_id, BackendId::Cpu);
12047            g.set_target_backend(sqrt_id, BackendId::Cpu);
12048            (in_id, sqrt_id)
12049        };
12050        let mut inputs = StorageCache::new();
12051        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12052        let (result_arc, _) = PipelinedExecutor::realize(graph, sqrt_id, inputs).expect("realize");
12053        let guard = result_arc.read().unwrap();
12054        assert_eq!(guard.dtype, DType::F64);
12055        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12056            panic!("expected Cpu storage");
12057        };
12058        assert_eq!(c.as_slice::<f64>().unwrap(), &[1.0_f64, 4.0, 9.0]);
12059    }
12060
12061    /// E2E: ArgMaxDim — produces U32 output indices.
12062    #[test]
12063    fn pipelined_realize_argmax_dim() {
12064        // input [2, 3] = [[1, 5, 2], [9, 0, 4]]
12065        // argmax dim=1 → [1, 0]
12066        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 2.0, 9.0, 0.0, 4.0]);
12067        let graph = Arc::new(RwLock::new(Graph::new()));
12068        let (in_id, op_id) = {
12069            let mut g = graph.write().unwrap();
12070            let in_id = g.push(Node {
12071                op: Op::Const,
12072                inputs: vec![],
12073                shape: Shape::from_dims(&[2, 3]),
12074                dtype: DType::F32,
12075            });
12076            let op_id = g.push(Node {
12077                op: Op::ArgMaxDim(1),
12078                inputs: vec![in_id],
12079                shape: Shape::from_dims(&[2]),
12080                dtype: DType::U32,
12081            });
12082            g.set_target_backend(op_id, BackendId::Cpu);
12083            (in_id, op_id)
12084        };
12085        let mut inputs = StorageCache::new();
12086        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12087        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12088        let guard = result_arc.read().unwrap();
12089        assert_eq!(guard.dtype, DType::U32);
12090        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12091            panic!("expected Cpu storage");
12092        };
12093        assert_eq!(c.as_slice::<u32>().unwrap(), &[1u32, 0]);
12094    }
12095
12096    /// E2E: IndexAdd along outer dim — accumulate updates into a
12097    /// rank-1 base tensor at indexed positions.
12098    #[test]
12099    fn pipelined_realize_index_add_simple() {
12100        let base = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
12101        let indices = fuel_memory::from_slice_cpu(&[0u32, 0]);
12102        let src = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
12103        let graph = Arc::new(RwLock::new(Graph::new()));
12104        let (b_id, i_id, s_id, op_id) = {
12105            let mut g = graph.write().unwrap();
12106            let b = g.push(Node {
12107                op: Op::Const,
12108                inputs: vec![],
12109                shape: Shape::from_dims(&[3]),
12110                dtype: DType::F32,
12111            });
12112            let i = g.push(Node {
12113                op: Op::Const,
12114                inputs: vec![],
12115                shape: Shape::from_dims(&[2]),
12116                dtype: DType::U32,
12117            });
12118            let s = g.push(Node {
12119                op: Op::Const,
12120                inputs: vec![],
12121                shape: Shape::from_dims(&[2]),
12122                dtype: DType::F32,
12123            });
12124            let op = g.push(Node {
12125                op: Op::IndexAdd { dim: 0 },
12126                inputs: vec![b, i, s],
12127                shape: Shape::from_dims(&[3]),
12128                dtype: DType::F32,
12129            });
12130            g.set_target_backend(op, BackendId::Cpu);
12131            (b, i, s, op)
12132        };
12133        let mut inputs = StorageCache::new();
12134        inputs.insert(b_id, Arc::new(RwLock::new(base)));
12135        inputs.insert(i_id, Arc::new(RwLock::new(indices)));
12136        inputs.insert(s_id, Arc::new(RwLock::new(src)));
12137        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12138        let guard = result_arc.read().unwrap();
12139        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12140            panic!("expected Cpu storage");
12141        };
12142        // 10 + 1 + 2 = 13; 20 untouched; 30 untouched.
12143        assert_eq!(c.as_slice::<f32>().unwrap(), &[13.0, 20.0, 30.0]);
12144    }
12145
12146    /// E2E: ScatterAdd along outer dim — same-rank indices, base
12147    /// starts as zeros, src adds values at scatter positions.
12148    #[test]
12149    fn pipelined_realize_scatter_add_outer_dim() {
12150        // base [3, 2] = zeros; indices [2, 2] = [[0, 1], [2, 0]];
12151        // src [2, 2] = [[1, 2], [3, 4]]; dim=0
12152        // → out = [[1, 4], [0, 2], [3, 0]]
12153        let base = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
12154        let indices = fuel_memory::from_slice_cpu(&[0u32, 1, 2, 0]);
12155        let src = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
12156        let graph = Arc::new(RwLock::new(Graph::new()));
12157        let (b_id, i_id, s_id, op_id) = {
12158            let mut g = graph.write().unwrap();
12159            let b = g.push(Node {
12160                op: Op::Const,
12161                inputs: vec![],
12162                shape: Shape::from_dims(&[3, 2]),
12163                dtype: DType::F32,
12164            });
12165            let i = g.push(Node {
12166                op: Op::Const,
12167                inputs: vec![],
12168                shape: Shape::from_dims(&[2, 2]),
12169                dtype: DType::U32,
12170            });
12171            let s = g.push(Node {
12172                op: Op::Const,
12173                inputs: vec![],
12174                shape: Shape::from_dims(&[2, 2]),
12175                dtype: DType::F32,
12176            });
12177            let op = g.push(Node {
12178                op: Op::ScatterAdd { dim: 0 },
12179                inputs: vec![b, i, s],
12180                shape: Shape::from_dims(&[3, 2]),
12181                dtype: DType::F32,
12182            });
12183            g.set_target_backend(op, BackendId::Cpu);
12184            (b, i, s, op)
12185        };
12186        let mut inputs = StorageCache::new();
12187        inputs.insert(b_id, Arc::new(RwLock::new(base)));
12188        inputs.insert(i_id, Arc::new(RwLock::new(indices)));
12189        inputs.insert(s_id, Arc::new(RwLock::new(src)));
12190        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12191        let guard = result_arc.read().unwrap();
12192        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12193            panic!("expected Cpu storage");
12194        };
12195        assert_eq!(
12196            c.as_slice::<f32>().unwrap(),
12197            &[1.0, 4.0, 0.0, 2.0, 3.0, 0.0]
12198        );
12199    }
12200
12201    /// E2E: Rope through the pipelined executor. cos=0, sin=1
12202    /// rotates the head_dim halves with sign per the rotate_half
12203    /// convention.
12204    #[test]
12205    fn pipelined_realize_rope_pi_over_two() {
12206        // x [1, 1, 4] = [1, 2, 3, 4]. cos=[0,0,0,0], sin=[1,1,1,1].
12207        // Expected: [-3, -4, 1, 2].
12208        let x = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
12209        let cos = fuel_memory::from_slice_cpu(&[0.0_f32, 0.0, 0.0, 0.0]);
12210        let sin = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
12211        let graph = Arc::new(RwLock::new(Graph::new()));
12212        let (x_id, cos_id, sin_id, r_id) = {
12213            let mut g = graph.write().unwrap();
12214            let x = g.push(Node {
12215                op: Op::Const,
12216                inputs: vec![],
12217                shape: Shape::from_dims(&[1, 1, 4]),
12218                dtype: DType::F32,
12219            });
12220            let c = g.push(Node {
12221                op: Op::Const,
12222                inputs: vec![],
12223                shape: Shape::from_dims(&[1, 4]),
12224                dtype: DType::F32,
12225            });
12226            let s = g.push(Node {
12227                op: Op::Const,
12228                inputs: vec![],
12229                shape: Shape::from_dims(&[1, 4]),
12230                dtype: DType::F32,
12231            });
12232            let r = g.push(Node {
12233                op: Op::Fused(
12234                    fuel_graph::registry::FusedOps::ROPE,
12235                    fuel_graph::registry::FusedOpParams::Rope,
12236                ),
12237                inputs: vec![x, c, s],
12238                shape: Shape::from_dims(&[1, 1, 4]),
12239                dtype: DType::F32,
12240            });
12241            g.set_target_backend(r, BackendId::Cpu);
12242            (x, c, s, r)
12243        };
12244        let mut inputs = StorageCache::new();
12245        inputs.insert(x_id, Arc::new(RwLock::new(x)));
12246        inputs.insert(cos_id, Arc::new(RwLock::new(cos)));
12247        inputs.insert(sin_id, Arc::new(RwLock::new(sin)));
12248        let (result_arc, _) = PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
12249        let guard = result_arc.read().unwrap();
12250        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12251            panic!("expected Cpu storage");
12252        };
12253        assert_eq!(c.as_slice::<f32>().unwrap(), &[-3.0, -4.0, 1.0, 2.0]);
12254    }
12255
12256    /// E2E: Gather along inner dim. Source [2, 4]; indices [2, 3];
12257    /// output [2, 3] = picks from each row by per-row indices.
12258    #[test]
12259    fn pipelined_realize_gather_inner_dim() {
12260        let source =
12261            fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0]);
12262        let indices = fuel_memory::from_slice_cpu(&[0u32, 2, 1, 3, 0, 0]);
12263        let graph = Arc::new(RwLock::new(Graph::new()));
12264        let (src_id, idx_id, g_id) = {
12265            let mut g = graph.write().unwrap();
12266            let s = g.push(Node {
12267                op: Op::Const,
12268                inputs: vec![],
12269                shape: Shape::from_dims(&[2, 4]),
12270                dtype: DType::F32,
12271            });
12272            let i = g.push(Node {
12273                op: Op::Const,
12274                inputs: vec![],
12275                shape: Shape::from_dims(&[2, 3]),
12276                dtype: DType::U32,
12277            });
12278            let g_id = g.push(Node {
12279                op: Op::Gather { dim: 1 },
12280                inputs: vec![s, i],
12281                shape: Shape::from_dims(&[2, 3]),
12282                dtype: DType::F32,
12283            });
12284            g.set_target_backend(g_id, BackendId::Cpu);
12285            (s, i, g_id)
12286        };
12287        let mut inputs = StorageCache::new();
12288        inputs.insert(src_id, Arc::new(RwLock::new(source)));
12289        inputs.insert(idx_id, Arc::new(RwLock::new(indices)));
12290        let (result_arc, _) = PipelinedExecutor::realize(graph, g_id, inputs).expect("realize");
12291        let guard = result_arc.read().unwrap();
12292        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12293            panic!("expected Cpu storage");
12294        };
12295        assert_eq!(
12296            c.as_slice::<f32>().unwrap(),
12297            &[10.0, 30.0, 20.0, 80.0, 50.0, 50.0]
12298        );
12299    }
12300
12301    /// E2E: IndexSelect — embedding-table lookup. Source is a
12302    /// `[vocab=4, d_model=3]` table; indices are token IDs;
12303    /// output is `[seq=3, d_model=3]` with the picked rows.
12304    #[test]
12305    fn pipelined_realize_index_select_embedding_lookup() {
12306        let table = fuel_memory::from_slice_cpu(&[
12307            10.0_f32, 11.0, 12.0, // row 0
12308            20.0, 21.0, 22.0, // row 1
12309            30.0, 31.0, 32.0, // row 2
12310            40.0, 41.0, 42.0, // row 3
12311        ]);
12312        let indices = fuel_memory::from_slice_cpu(&[2u32, 0, 2]);
12313        let graph = Arc::new(RwLock::new(Graph::new()));
12314        let (table_id, idx_id, sel_id) = {
12315            let mut g = graph.write().unwrap();
12316            let t = g.push(Node {
12317                op: Op::Const,
12318                inputs: vec![],
12319                shape: Shape::from_dims(&[4, 3]),
12320                dtype: DType::F32,
12321            });
12322            let i = g.push(Node {
12323                op: Op::Const,
12324                inputs: vec![],
12325                shape: Shape::from_dims(&[3]),
12326                dtype: DType::U32,
12327            });
12328            let s = g.push(Node {
12329                op: Op::IndexSelect { dim: 0 },
12330                inputs: vec![t, i],
12331                shape: Shape::from_dims(&[3, 3]),
12332                dtype: DType::F32,
12333            });
12334            g.set_target_backend(s, BackendId::Cpu);
12335            (t, i, s)
12336        };
12337        let mut inputs = StorageCache::new();
12338        inputs.insert(table_id, Arc::new(RwLock::new(table)));
12339        inputs.insert(idx_id, Arc::new(RwLock::new(indices)));
12340        let (result_arc, result_layout) =
12341            PipelinedExecutor::realize(graph, sel_id, inputs).expect("realize");
12342        assert_eq!(result_layout.shape().dims(), &[3, 3]);
12343        let guard = result_arc.read().unwrap();
12344        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12345            panic!("expected Cpu storage");
12346        };
12347        assert_eq!(
12348            c.as_slice::<f32>().unwrap(),
12349            &[30.0, 31.0, 32.0, 10.0, 11.0, 12.0, 30.0, 31.0, 32.0]
12350        );
12351    }
12352
12353    /// E2E: RmsNormLastDim on a 2-row input. Each row's output
12354    /// has unit RMS up to the eps-induced bias.
12355    #[test]
12356    fn pipelined_realize_rms_norm_last_dim() {
12357        let storage = fuel_memory::from_slice_cpu(&[
12358            3.0_f32, 4.0, // row 0: rms = sqrt(12.5)
12359            6.0, 8.0, // row 1: rms = sqrt(50.0) = 5*sqrt(2)
12360        ]);
12361        let graph = Arc::new(RwLock::new(Graph::new()));
12362        let (in_id, op_id) = {
12363            let mut g = graph.write().unwrap();
12364            let in_id = g.push(Node {
12365                op: Op::Const,
12366                inputs: vec![],
12367                shape: Shape::from_dims(&[2, 2]),
12368                dtype: DType::F32,
12369            });
12370            let op_id = g.push(Node {
12371                op: Op::Fused(
12372                    fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM,
12373                    fuel_graph::registry::FusedOpParams::RmsNormLastDim { eps: 0.0 },
12374                ),
12375                inputs: vec![in_id],
12376                shape: Shape::from_dims(&[2, 2]),
12377                dtype: DType::F32,
12378            });
12379            g.set_target_backend(op_id, BackendId::Cpu);
12380            (in_id, op_id)
12381        };
12382        let mut inputs = StorageCache::new();
12383        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12384        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12385        let guard = result_arc.read().unwrap();
12386        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12387            panic!("expected Cpu storage");
12388        };
12389        let result: &[f32] = c.as_slice().unwrap();
12390        // Row 0: rms = sqrt(12.5). Output = [3, 4] / sqrt(12.5).
12391        let rms0 = (12.5_f32).sqrt();
12392        assert!((result[0] - 3.0 / rms0).abs() < 1e-6);
12393        assert!((result[1] - 4.0 / rms0).abs() < 1e-6);
12394        // Row 1: rms = sqrt(50). Output = [6, 8] / sqrt(50).
12395        let rms1 = (50.0_f32).sqrt();
12396        assert!((result[2] - 6.0 / rms1).abs() < 1e-6);
12397        assert!((result[3] - 8.0 / rms1).abs() < 1e-6);
12398    }
12399
12400    /// E2E: LayerNormLastDim — each row's output has zero mean and
12401    /// unit variance.
12402    #[test]
12403    fn pipelined_realize_layer_norm_last_dim() {
12404        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 10.0, 20.0, 30.0]);
12405        let graph = Arc::new(RwLock::new(Graph::new()));
12406        let (in_id, op_id) = {
12407            let mut g = graph.write().unwrap();
12408            let in_id = g.push(Node {
12409                op: Op::Const,
12410                inputs: vec![],
12411                shape: Shape::from_dims(&[2, 3]),
12412                dtype: DType::F32,
12413            });
12414            let op_id = g.push(Node {
12415                op: Op::Fused(
12416                    fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM,
12417                    fuel_graph::registry::FusedOpParams::LayerNormLastDim { eps: 0.0 },
12418                ),
12419                inputs: vec![in_id],
12420                shape: Shape::from_dims(&[2, 3]),
12421                dtype: DType::F32,
12422            });
12423            g.set_target_backend(op_id, BackendId::Cpu);
12424            (in_id, op_id)
12425        };
12426        let mut inputs = StorageCache::new();
12427        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12428        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12429        let guard = result_arc.read().unwrap();
12430        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12431            panic!("expected Cpu storage");
12432        };
12433        let result: &[f32] = c.as_slice().unwrap();
12434        // Each row should have mean ~0 and var ~1.
12435        for row in 0..2 {
12436            let off = row * 3;
12437            let sum: f32 = result[off..off + 3].iter().sum();
12438            let mean = sum / 3.0;
12439            assert!(mean.abs() < 1e-6, "row {row} mean should be 0, got {mean}");
12440            let var: f32 = result[off..off + 3]
12441                .iter()
12442                .map(|v| (v - mean).powi(2))
12443                .sum::<f32>()
12444                / 3.0;
12445            assert!(
12446                (var - 1.0).abs() < 1e-6,
12447                "row {row} var should be 1, got {var}"
12448            );
12449        }
12450    }
12451
12452    /// E2E: SoftmaxLastDim on a 2-row input. Each row should sum
12453    /// to 1; uniform row gives uniform output.
12454    #[test]
12455    fn pipelined_realize_softmax_last_dim() {
12456        // Row 0: [1, 1, 1, 1] → uniform 0.25 each
12457        // Row 1: [0, 0, 0, 100] → effectively a one-hot at position 3
12458        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 100.0]);
12459        let graph = Arc::new(RwLock::new(Graph::new()));
12460        let (in_id, op_id) = {
12461            let mut g = graph.write().unwrap();
12462            let in_id = g.push(Node {
12463                op: Op::Const,
12464                inputs: vec![],
12465                shape: Shape::from_dims(&[2, 4]),
12466                dtype: DType::F32,
12467            });
12468            let op_id = g.push(Node {
12469                op: Op::Fused(
12470                    fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM,
12471                    fuel_graph::registry::FusedOpParams::SoftmaxLastDim,
12472                ),
12473                inputs: vec![in_id],
12474                shape: Shape::from_dims(&[2, 4]),
12475                dtype: DType::F32,
12476            });
12477            g.set_target_backend(op_id, BackendId::Cpu);
12478            (in_id, op_id)
12479        };
12480        let mut inputs = StorageCache::new();
12481        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12482        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12483        let guard = result_arc.read().unwrap();
12484        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12485            panic!("expected Cpu storage");
12486        };
12487        let result: &[f32] = c.as_slice().unwrap();
12488
12489        // Row 0: uniform 0.25
12490        for v in &result[..4] {
12491            assert!((v - 0.25).abs() < 1e-7);
12492        }
12493        // Row 1: positions 0..3 ≈ 0, position 4 (= last column) ≈ 1
12494        // (e^100 dominates).
12495        for v in &result[4..7] {
12496            assert!(
12497                *v < 1e-30,
12498                "row-1 leading positions should be near 0, got {v}"
12499            );
12500        }
12501        assert!(
12502            result[7] > 0.999,
12503            "row-1 last position should dominate, got {}",
12504            result[7]
12505        );
12506        // Each row sums to 1.
12507        let row0_sum: f32 = result[..4].iter().sum();
12508        let row1_sum: f32 = result[4..].iter().sum();
12509        assert!((row0_sum - 1.0).abs() < 1e-6);
12510        assert!((row1_sum - 1.0).abs() < 1e-6);
12511    }
12512
12513    /// E2E: Concat along inner dim — two [2, 3] tensors → [2, 6].
12514    #[test]
12515    fn pipelined_realize_concat_inner_dim() {
12516        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
12517        let b = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0, 9.0, 10.0, 11.0, 12.0]);
12518        let graph = Arc::new(RwLock::new(Graph::new()));
12519        let (a_id, b_id, c_id) = {
12520            let mut g = graph.write().unwrap();
12521            let a = g.push(Node {
12522                op: Op::Const,
12523                inputs: vec![],
12524                shape: Shape::from_dims(&[2, 3]),
12525                dtype: DType::F32,
12526            });
12527            let b = g.push(Node {
12528                op: Op::Const,
12529                inputs: vec![],
12530                shape: Shape::from_dims(&[2, 3]),
12531                dtype: DType::F32,
12532            });
12533            let c = g.push(Node {
12534                op: Op::Concat { dim: 1 },
12535                inputs: vec![a, b],
12536                shape: Shape::from_dims(&[2, 6]),
12537                dtype: DType::F32,
12538            });
12539            g.set_target_backend(c, BackendId::Cpu);
12540            (a, b, c)
12541        };
12542        let mut inputs = StorageCache::new();
12543        inputs.insert(a_id, Arc::new(RwLock::new(a)));
12544        inputs.insert(b_id, Arc::new(RwLock::new(b)));
12545        let (result_arc, result_layout) =
12546            PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12547        assert_eq!(result_layout.shape().dims(), &[2, 6]);
12548        let guard = result_arc.read().unwrap();
12549        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12550            panic!("expected Cpu storage");
12551        };
12552        assert_eq!(
12553            c.as_slice::<f32>().unwrap(),
12554            &[
12555                1.0, 2.0, 3.0, 7.0, 8.0, 9.0, 4.0, 5.0, 6.0, 10.0, 11.0, 12.0
12556            ]
12557        );
12558    }
12559
12560    /// E2E: Concat with three inputs along outer dim — verifies
12561    /// variable-arity input handling through the executor.
12562    #[test]
12563    fn pipelined_realize_concat_three_inputs_outer() {
12564        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
12565        let b = fuel_memory::from_slice_cpu(&[3.0_f32, 4.0]);
12566        let c = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0]);
12567        let graph = Arc::new(RwLock::new(Graph::new()));
12568        let (a_id, b_id, c_id, cat_id) = {
12569            let mut g = graph.write().unwrap();
12570            let a = g.push(Node {
12571                op: Op::Const,
12572                inputs: vec![],
12573                shape: Shape::from_dims(&[2]),
12574                dtype: DType::F32,
12575            });
12576            let b = g.push(Node {
12577                op: Op::Const,
12578                inputs: vec![],
12579                shape: Shape::from_dims(&[2]),
12580                dtype: DType::F32,
12581            });
12582            let c = g.push(Node {
12583                op: Op::Const,
12584                inputs: vec![],
12585                shape: Shape::from_dims(&[2]),
12586                dtype: DType::F32,
12587            });
12588            let cat = g.push(Node {
12589                op: Op::Concat { dim: 0 },
12590                inputs: vec![a, b, c],
12591                shape: Shape::from_dims(&[6]),
12592                dtype: DType::F32,
12593            });
12594            g.set_target_backend(cat, BackendId::Cpu);
12595            (a, b, c, cat)
12596        };
12597        let mut inputs = StorageCache::new();
12598        inputs.insert(a_id, Arc::new(RwLock::new(a)));
12599        inputs.insert(b_id, Arc::new(RwLock::new(b)));
12600        inputs.insert(c_id, Arc::new(RwLock::new(c)));
12601        let (result_arc, _) = PipelinedExecutor::realize(graph, cat_id, inputs).expect("realize");
12602        let guard = result_arc.read().unwrap();
12603        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12604            panic!("expected Cpu storage");
12605        };
12606        assert_eq!(
12607            c.as_slice::<f32>().unwrap(),
12608            &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
12609        );
12610    }
12611
12612    /// E2E: AddScalar — graph emits Op::AddScalar; the executor
12613    /// maps it to OpKind::Affine with mul=1, add=c.
12614    #[test]
12615    fn pipelined_realize_add_scalar() {
12616        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
12617        let graph = Arc::new(RwLock::new(Graph::new()));
12618        let (in_id, op_id) = {
12619            let mut g = graph.write().unwrap();
12620            let in_id = g.push(Node {
12621                op: Op::Const,
12622                inputs: vec![],
12623                shape: Shape::from_dims(&[3]),
12624                dtype: DType::F32,
12625            });
12626            let op_id = g.push(Node {
12627                op: Op::AddScalar(10.0),
12628                inputs: vec![in_id],
12629                shape: Shape::from_dims(&[3]),
12630                dtype: DType::F32,
12631            });
12632            g.set_target_backend(op_id, BackendId::Cpu);
12633            (in_id, op_id)
12634        };
12635        let mut inputs = StorageCache::new();
12636        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12637        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12638        let guard = result_arc.read().unwrap();
12639        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12640            panic!("expected Cpu storage");
12641        };
12642        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 12.0, 13.0]);
12643    }
12644
12645    /// E2E: Clamp — clamp values to [-2, 2].
12646    #[test]
12647    fn pipelined_realize_clamp() {
12648        let storage = fuel_memory::from_slice_cpu(&[-5.0_f32, 0.5, 100.0]);
12649        let graph = Arc::new(RwLock::new(Graph::new()));
12650        let (in_id, op_id) = {
12651            let mut g = graph.write().unwrap();
12652            let in_id = g.push(Node {
12653                op: Op::Const,
12654                inputs: vec![],
12655                shape: Shape::from_dims(&[3]),
12656                dtype: DType::F32,
12657            });
12658            let op_id = g.push(Node {
12659                op: Op::Clamp {
12660                    min: -2.0,
12661                    max: 2.0,
12662                },
12663                inputs: vec![in_id],
12664                shape: Shape::from_dims(&[3]),
12665                dtype: DType::F32,
12666            });
12667            g.set_target_backend(op_id, BackendId::Cpu);
12668            (in_id, op_id)
12669        };
12670        let mut inputs = StorageCache::new();
12671        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12672        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12673        let guard = result_arc.read().unwrap();
12674        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12675            panic!("expected Cpu storage");
12676        };
12677        assert_eq!(c.as_slice::<f32>().unwrap(), &[-2.0, 0.5, 2.0]);
12678    }
12679
12680    /// E2E: Maximum — elementwise tensor max.
12681    #[test]
12682    fn pipelined_realize_maximum_elementwise() {
12683        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, -3.0]);
12684        let rhs_storage = fuel_memory::from_slice_cpu(&[2.0_f32, 1.0, -1.0]);
12685        let graph = Arc::new(RwLock::new(Graph::new()));
12686        let (lhs_id, rhs_id, op_id) = {
12687            let mut g = graph.write().unwrap();
12688            let lhs = g.push(Node {
12689                op: Op::Const,
12690                inputs: vec![],
12691                shape: Shape::from_dims(&[3]),
12692                dtype: DType::F32,
12693            });
12694            let rhs = g.push(Node {
12695                op: Op::Const,
12696                inputs: vec![],
12697                shape: Shape::from_dims(&[3]),
12698                dtype: DType::F32,
12699            });
12700            let op = g.push(Node {
12701                op: Op::Maximum,
12702                inputs: vec![lhs, rhs],
12703                shape: Shape::from_dims(&[3]),
12704                dtype: DType::F32,
12705            });
12706            g.set_target_backend(op, BackendId::Cpu);
12707            (lhs, rhs, op)
12708        };
12709        let mut inputs = StorageCache::new();
12710        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
12711        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
12712        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12713        let guard = result_arc.read().unwrap();
12714        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12715            panic!("expected Cpu storage");
12716        };
12717        assert_eq!(c.as_slice::<f32>().unwrap(), &[2.0, 5.0, -1.0]);
12718    }
12719
12720    /// E2E: Const + Const + Conv2D — the 2×2 sum-kernel test from
12721    /// byte_kernels driven through the pipelined executor.
12722    #[test]
12723    fn pipelined_realize_conv2d_2x2_sum_kernel() {
12724        // x [1, 1, 3, 3]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
12725        // weight [1, 1, 2, 2]: all-ones
12726        // → out [1, 1, 2, 2]: [[12, 16], [24, 28]]
12727        let x_storage =
12728            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
12729        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
12730
12731        let graph = Arc::new(RwLock::new(Graph::new()));
12732        let (x_id, w_id, c_id) = {
12733            let mut g = graph.write().unwrap();
12734            let x = g.push(Node {
12735                op: Op::Const,
12736                inputs: vec![],
12737                shape: Shape::from_dims(&[1, 1, 3, 3]),
12738                dtype: DType::F32,
12739            });
12740            let w = g.push(Node {
12741                op: Op::Const,
12742                inputs: vec![],
12743                shape: Shape::from_dims(&[1, 1, 2, 2]),
12744                dtype: DType::F32,
12745            });
12746            let c = g.push(Node {
12747                op: Op::Fused(
12748                    fuel_graph::registry::FusedOps::CONV2D,
12749                    fuel_graph::registry::FusedOpParams::Conv2D {
12750                        stride: (1, 1),
12751                        padding: (0, 0),
12752                        groups: 1,
12753                    },
12754                ),
12755                inputs: vec![x, w],
12756                shape: Shape::from_dims(&[1, 1, 2, 2]),
12757                dtype: DType::F32,
12758            });
12759            g.set_target_backend(c, BackendId::Cpu);
12760            (x, w, c)
12761        };
12762        let mut inputs = StorageCache::new();
12763        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12764        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12765
12766        let (result_arc, result_layout) =
12767            PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12768        assert_eq!(result_layout.shape().dims(), &[1, 1, 2, 2]);
12769
12770        let guard = result_arc.read().unwrap();
12771        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12772            panic!("expected Cpu storage");
12773        };
12774        assert_eq!(c.as_slice::<f32>().unwrap(), &[12.0, 16.0, 24.0, 28.0]);
12775    }
12776
12777    /// E2E: Conv2D with bias (3 inputs).
12778    #[test]
12779    fn pipelined_realize_conv2d_with_bias() {
12780        let x_storage =
12781            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
12782        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
12783        let bias_storage = fuel_memory::from_slice_cpu(&[100.0_f32]);
12784
12785        let graph = Arc::new(RwLock::new(Graph::new()));
12786        let (x_id, w_id, b_id, c_id) = {
12787            let mut g = graph.write().unwrap();
12788            let x = g.push(Node {
12789                op: Op::Const,
12790                inputs: vec![],
12791                shape: Shape::from_dims(&[1, 1, 3, 3]),
12792                dtype: DType::F32,
12793            });
12794            let w = g.push(Node {
12795                op: Op::Const,
12796                inputs: vec![],
12797                shape: Shape::from_dims(&[1, 1, 2, 2]),
12798                dtype: DType::F32,
12799            });
12800            let b = g.push(Node {
12801                op: Op::Const,
12802                inputs: vec![],
12803                shape: Shape::from_dims(&[1]),
12804                dtype: DType::F32,
12805            });
12806            let c = g.push(Node {
12807                op: Op::Fused(
12808                    fuel_graph::registry::FusedOps::CONV2D,
12809                    fuel_graph::registry::FusedOpParams::Conv2D {
12810                        stride: (1, 1),
12811                        padding: (0, 0),
12812                        groups: 1,
12813                    },
12814                ),
12815                inputs: vec![x, w, b],
12816                shape: Shape::from_dims(&[1, 1, 2, 2]),
12817                dtype: DType::F32,
12818            });
12819            g.set_target_backend(c, BackendId::Cpu);
12820            (x, w, b, c)
12821        };
12822        let mut inputs = StorageCache::new();
12823        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12824        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12825        inputs.insert(b_id, Arc::new(RwLock::new(bias_storage)));
12826
12827        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12828        let guard = result_arc.read().unwrap();
12829        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12830            panic!("expected Cpu storage");
12831        };
12832        assert_eq!(c.as_slice::<f32>().unwrap(), &[112.0, 116.0, 124.0, 128.0]);
12833    }
12834
12835    /// E2E: Conv2D in F64 — same 2x2 sum-kernel test as F32, on doubles.
12836    #[test]
12837    fn pipelined_realize_conv2d_f64() {
12838        let x_storage =
12839            fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
12840        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f64, 1.0, 1.0, 1.0]);
12841
12842        let graph = Arc::new(RwLock::new(Graph::new()));
12843        let (x_id, w_id, c_id) = {
12844            let mut g = graph.write().unwrap();
12845            let x = g.push(Node {
12846                op: Op::Const,
12847                inputs: vec![],
12848                shape: Shape::from_dims(&[1, 1, 3, 3]),
12849                dtype: DType::F64,
12850            });
12851            let w = g.push(Node {
12852                op: Op::Const,
12853                inputs: vec![],
12854                shape: Shape::from_dims(&[1, 1, 2, 2]),
12855                dtype: DType::F64,
12856            });
12857            let c = g.push(Node {
12858                op: Op::Fused(
12859                    fuel_graph::registry::FusedOps::CONV2D,
12860                    fuel_graph::registry::FusedOpParams::Conv2D {
12861                        stride: (1, 1),
12862                        padding: (0, 0),
12863                        groups: 1,
12864                    },
12865                ),
12866                inputs: vec![x, w],
12867                shape: Shape::from_dims(&[1, 1, 2, 2]),
12868                dtype: DType::F64,
12869            });
12870            g.set_target_backend(c, BackendId::Cpu);
12871            (x, w, c)
12872        };
12873        let mut inputs = StorageCache::new();
12874        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12875        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12876        let (result_arc, _) = PipelinedExecutor::realize(graph, c_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::<f64>().unwrap(), &[12.0, 16.0, 24.0, 28.0]);
12882    }
12883
12884    /// E2E: Conv2D in BF16 — f32-accumulator path. Tolerant compare.
12885    #[test]
12886    fn pipelined_realize_conv2d_bf16() {
12887        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]
12888            .iter()
12889            .map(|v| half::bf16::from_f32(*v))
12890            .collect();
12891        let w_data: Vec<half::bf16> = [1.0_f32, 1.0, 1.0, 1.0]
12892            .iter()
12893            .map(|v| half::bf16::from_f32(*v))
12894            .collect();
12895        let x_storage = fuel_memory::from_slice_cpu(&x_data);
12896        let w_storage = fuel_memory::from_slice_cpu(&w_data);
12897
12898        let graph = Arc::new(RwLock::new(Graph::new()));
12899        let (x_id, w_id, c_id) = {
12900            let mut g = graph.write().unwrap();
12901            let x = g.push(Node {
12902                op: Op::Const,
12903                inputs: vec![],
12904                shape: Shape::from_dims(&[1, 1, 3, 3]),
12905                dtype: DType::BF16,
12906            });
12907            let w = g.push(Node {
12908                op: Op::Const,
12909                inputs: vec![],
12910                shape: Shape::from_dims(&[1, 1, 2, 2]),
12911                dtype: DType::BF16,
12912            });
12913            let c = g.push(Node {
12914                op: Op::Fused(
12915                    fuel_graph::registry::FusedOps::CONV2D,
12916                    fuel_graph::registry::FusedOpParams::Conv2D {
12917                        stride: (1, 1),
12918                        padding: (0, 0),
12919                        groups: 1,
12920                    },
12921                ),
12922                inputs: vec![x, w],
12923                shape: Shape::from_dims(&[1, 1, 2, 2]),
12924                dtype: DType::BF16,
12925            });
12926            g.set_target_backend(c, BackendId::Cpu);
12927            (x, w, c)
12928        };
12929        let mut inputs = StorageCache::new();
12930        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12931        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12932        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12933        let guard = result_arc.read().unwrap();
12934        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12935            panic!("expected Cpu storage");
12936        };
12937        let got: Vec<f32> = c
12938            .as_slice::<half::bf16>()
12939            .unwrap()
12940            .iter()
12941            .map(|v| v.to_f32())
12942            .collect();
12943        let want = [12.0_f32, 16.0, 24.0, 28.0];
12944        for (g, w) in got.iter().zip(want.iter()) {
12945            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
12946        }
12947    }
12948
12949    /// E2E: Conv2D in F16 — f32-accumulator path. Tolerant compare.
12950    #[test]
12951    fn pipelined_realize_conv2d_f16() {
12952        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]
12953            .iter()
12954            .map(|v| half::f16::from_f32(*v))
12955            .collect();
12956        let w_data: Vec<half::f16> = [1.0_f32, 1.0, 1.0, 1.0]
12957            .iter()
12958            .map(|v| half::f16::from_f32(*v))
12959            .collect();
12960        let x_storage = fuel_memory::from_slice_cpu(&x_data);
12961        let w_storage = fuel_memory::from_slice_cpu(&w_data);
12962
12963        let graph = Arc::new(RwLock::new(Graph::new()));
12964        let (x_id, w_id, c_id) = {
12965            let mut g = graph.write().unwrap();
12966            let x = g.push(Node {
12967                op: Op::Const,
12968                inputs: vec![],
12969                shape: Shape::from_dims(&[1, 1, 3, 3]),
12970                dtype: DType::F16,
12971            });
12972            let w = g.push(Node {
12973                op: Op::Const,
12974                inputs: vec![],
12975                shape: Shape::from_dims(&[1, 1, 2, 2]),
12976                dtype: DType::F16,
12977            });
12978            let c = g.push(Node {
12979                op: Op::Fused(
12980                    fuel_graph::registry::FusedOps::CONV2D,
12981                    fuel_graph::registry::FusedOpParams::Conv2D {
12982                        stride: (1, 1),
12983                        padding: (0, 0),
12984                        groups: 1,
12985                    },
12986                ),
12987                inputs: vec![x, w],
12988                shape: Shape::from_dims(&[1, 1, 2, 2]),
12989                dtype: DType::F16,
12990            });
12991            g.set_target_backend(c, BackendId::Cpu);
12992            (x, w, c)
12993        };
12994        let mut inputs = StorageCache::new();
12995        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12996        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12997        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12998        let guard = result_arc.read().unwrap();
12999        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13000            panic!("expected Cpu storage");
13001        };
13002        let got: Vec<f32> = c
13003            .as_slice::<half::f16>()
13004            .unwrap()
13005            .iter()
13006            .map(|v| v.to_f32())
13007            .collect();
13008        let want = [12.0_f32, 16.0, 24.0, 28.0];
13009        for (g, w) in got.iter().zip(want.iter()) {
13010            assert!((g - w).abs() < 0.05, "got {got:?} want {want:?}");
13011        }
13012    }
13013
13014    /// E2E: Op::PagedAttn — F32, single-head, B=1, Sq=1.
13015    /// Same setup as the FlashAttn smoke test, but the K/V live in a
13016    /// paged cache that we look up via block_table.
13017    /// Layout:
13018    ///   block_size=2, num_blocks=1, max_blocks_per_seq=1.
13019    ///   k_cache shape [1, 2, 1, 2] = num_blocks × block_size × Hkv × D.
13020    ///   k_cache[block 0, slot 0, h 0] = [1, 0]
13021    ///   k_cache[block 0, slot 1, h 0] = [0, 1]
13022    ///   v_cache values: [10, 0] / [0, 10]
13023    ///   block_table[b=0, logical_block 0] = 0 (physical)
13024    ///   context_lens[0] = 2
13025    ///   q[0, 0, 0] = [2, 0]
13026    /// Causal is implicit (q_pos = ctx_len - Sq + sq = 2 - 1 + 0 = 1, both keys admissible).
13027    /// Same softmax math as FlashAttn → ~[8.808, 1.192].
13028    #[test]
13029    fn pipelined_realize_paged_attn_f32() {
13030        let q = fuel_memory::from_slice_cpu(&[2.0_f32, 0.0]);
13031        let k_cache = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13032        let v_cache = fuel_memory::from_slice_cpu(&[10.0_f32, 0.0, 0.0, 10.0]);
13033        let block_table_u32 = fuel_memory::Storage::new(
13034            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
13035                0_u32,
13036            ])),
13037            DType::U32,
13038        );
13039        let context_lens_u32 = fuel_memory::Storage::new(
13040            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
13041                2_u32,
13042            ])),
13043            DType::U32,
13044        );
13045        let graph = Arc::new(RwLock::new(Graph::new()));
13046        let (q_id, kc_id, vc_id, bt_id, cl_id, op_id) = {
13047            let mut g = graph.write().unwrap();
13048            let q = g.push(Node {
13049                op: Op::Const,
13050                inputs: vec![],
13051                shape: Shape::from_dims(&[1, 1, 1, 2]),
13052                dtype: DType::F32,
13053            });
13054            let kc = g.push(Node {
13055                op: Op::Const,
13056                inputs: vec![],
13057                shape: Shape::from_dims(&[1, 2, 1, 2]),
13058                dtype: DType::F32,
13059            });
13060            let vc = g.push(Node {
13061                op: Op::Const,
13062                inputs: vec![],
13063                shape: Shape::from_dims(&[1, 2, 1, 2]),
13064                dtype: DType::F32,
13065            });
13066            let bt = g.push(Node {
13067                op: Op::Const,
13068                inputs: vec![],
13069                shape: Shape::from_dims(&[1, 1]),
13070                dtype: DType::U32,
13071            });
13072            let cl = g.push(Node {
13073                op: Op::Const,
13074                inputs: vec![],
13075                shape: Shape::from_dims(&[1]),
13076                dtype: DType::U32,
13077            });
13078            let op = g.push(Node {
13079                op: Op::Fused(
13080                    fuel_graph::registry::FusedOps::PAGED_ATTN,
13081                    fuel_graph::registry::FusedOpParams::PagedAttn {
13082                        softmax_scale: 1.0,
13083                        block_size: 2,
13084                        softcap: None,
13085                    },
13086                ),
13087                inputs: vec![q, kc, vc, bt, cl],
13088                shape: Shape::from_dims(&[1, 1, 1, 2]),
13089                dtype: DType::F32,
13090            });
13091            g.set_target_backend(op, BackendId::Cpu);
13092            (q, kc, vc, bt, cl, op)
13093        };
13094        let mut inputs = StorageCache::new();
13095        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13096        inputs.insert(kc_id, Arc::new(RwLock::new(k_cache)));
13097        inputs.insert(vc_id, Arc::new(RwLock::new(v_cache)));
13098        inputs.insert(bt_id, Arc::new(RwLock::new(block_table_u32)));
13099        inputs.insert(cl_id, Arc::new(RwLock::new(context_lens_u32)));
13100        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13101        let guard = result_arc.read().unwrap();
13102        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13103            panic!("expected Cpu storage");
13104        };
13105        let r = c.as_slice::<f32>().unwrap();
13106        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
13107        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
13108        assert!(
13109            (r[0] - 10.0 * expected_p0).abs() < 1e-5,
13110            "row[0]: got {} expected {}",
13111            r[0],
13112            10.0 * expected_p0
13113        );
13114        assert!(
13115            (r[1] - 10.0 * expected_p1).abs() < 1e-5,
13116            "row[1]: got {} expected {}",
13117            r[1],
13118            10.0 * expected_p1
13119        );
13120    }
13121
13122    /// E2E: PagedAttn BF16 — same single-row test, tolerant.
13123    #[test]
13124    fn pipelined_realize_paged_attn_bf16() {
13125        let q_v: Vec<half::bf16> = [2.0_f32, 0.0]
13126            .iter()
13127            .map(|x| half::bf16::from_f32(*x))
13128            .collect();
13129        let kc_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0]
13130            .iter()
13131            .map(|x| half::bf16::from_f32(*x))
13132            .collect();
13133        let vc_v: Vec<half::bf16> = [10.0_f32, 0.0, 0.0, 10.0]
13134            .iter()
13135            .map(|x| half::bf16::from_f32(*x))
13136            .collect();
13137        let q = fuel_memory::from_slice_cpu(&q_v);
13138        let k_cache = fuel_memory::from_slice_cpu(&kc_v);
13139        let v_cache = fuel_memory::from_slice_cpu(&vc_v);
13140        let bt = fuel_memory::Storage::new(
13141            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
13142                0_u32,
13143            ])),
13144            DType::U32,
13145        );
13146        let cl = fuel_memory::Storage::new(
13147            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
13148                2_u32,
13149            ])),
13150            DType::U32,
13151        );
13152        let graph = Arc::new(RwLock::new(Graph::new()));
13153        let (q_id, kc_id, vc_id, bt_id, cl_id, op_id) = {
13154            let mut g = graph.write().unwrap();
13155            let q = g.push(Node {
13156                op: Op::Const,
13157                inputs: vec![],
13158                shape: Shape::from_dims(&[1, 1, 1, 2]),
13159                dtype: DType::BF16,
13160            });
13161            let kc = g.push(Node {
13162                op: Op::Const,
13163                inputs: vec![],
13164                shape: Shape::from_dims(&[1, 2, 1, 2]),
13165                dtype: DType::BF16,
13166            });
13167            let vc = g.push(Node {
13168                op: Op::Const,
13169                inputs: vec![],
13170                shape: Shape::from_dims(&[1, 2, 1, 2]),
13171                dtype: DType::BF16,
13172            });
13173            let bt = g.push(Node {
13174                op: Op::Const,
13175                inputs: vec![],
13176                shape: Shape::from_dims(&[1, 1]),
13177                dtype: DType::U32,
13178            });
13179            let cl = g.push(Node {
13180                op: Op::Const,
13181                inputs: vec![],
13182                shape: Shape::from_dims(&[1]),
13183                dtype: DType::U32,
13184            });
13185            let op = g.push(Node {
13186                op: Op::Fused(
13187                    fuel_graph::registry::FusedOps::PAGED_ATTN,
13188                    fuel_graph::registry::FusedOpParams::PagedAttn {
13189                        softmax_scale: 1.0,
13190                        block_size: 2,
13191                        softcap: None,
13192                    },
13193                ),
13194                inputs: vec![q, kc, vc, bt, cl],
13195                shape: Shape::from_dims(&[1, 1, 1, 2]),
13196                dtype: DType::BF16,
13197            });
13198            g.set_target_backend(op, BackendId::Cpu);
13199            (q, kc, vc, bt, cl, op)
13200        };
13201        let mut inputs = StorageCache::new();
13202        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13203        inputs.insert(kc_id, Arc::new(RwLock::new(k_cache)));
13204        inputs.insert(vc_id, Arc::new(RwLock::new(v_cache)));
13205        inputs.insert(bt_id, Arc::new(RwLock::new(bt)));
13206        inputs.insert(cl_id, Arc::new(RwLock::new(cl)));
13207        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13208        let guard = result_arc.read().unwrap();
13209        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13210            panic!("expected Cpu storage");
13211        };
13212        let got: Vec<f32> = c
13213            .as_slice::<half::bf16>()
13214            .unwrap()
13215            .iter()
13216            .map(|v| v.to_f32())
13217            .collect();
13218        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
13219        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
13220        let want = [10.0 * expected_p0, 10.0 * expected_p1];
13221        for (g, w) in got.iter().zip(want.iter()) {
13222            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
13223        }
13224    }
13225
13226    /// E2E: Op::FlashAttn — F32 single-head, single-batch, no mask.
13227    /// q = [[2.0, 0.0]], k = [[1.0, 0.0], [0.0, 1.0]], v = [[10, 0], [0, 10]]
13228    /// scale = 1.0
13229    /// scores = q · kᵀ = [2.0, 0.0]
13230    /// softmax = [e^2/(e^2+1), 1/(e^2+1)] ≈ [0.8808, 0.1192]
13231    /// out = softmax @ v = [10*0.8808, 10*0.1192] ≈ [8.808, 1.192]
13232    #[test]
13233    fn pipelined_realize_flash_attn_f32() {
13234        // [B=1, H=1, S=1or2, D=2]
13235        let q = fuel_memory::from_slice_cpu(&[2.0_f32, 0.0]);
13236        let k = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13237        let v = fuel_memory::from_slice_cpu(&[10.0_f32, 0.0, 0.0, 10.0]);
13238        let graph = Arc::new(RwLock::new(Graph::new()));
13239        let (q_id, k_id, v_id, op_id) = {
13240            let mut g = graph.write().unwrap();
13241            let q = g.push(Node {
13242                op: Op::Const,
13243                inputs: vec![],
13244                shape: Shape::from_dims(&[1, 1, 1, 2]),
13245                dtype: DType::F32,
13246            });
13247            let k = g.push(Node {
13248                op: Op::Const,
13249                inputs: vec![],
13250                shape: Shape::from_dims(&[1, 1, 2, 2]),
13251                dtype: DType::F32,
13252            });
13253            let v = g.push(Node {
13254                op: Op::Const,
13255                inputs: vec![],
13256                shape: Shape::from_dims(&[1, 1, 2, 2]),
13257                dtype: DType::F32,
13258            });
13259            let op = g.push(Node {
13260                op: Op::Fused(
13261                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13262                    fuel_graph::registry::FusedOpParams::FlashAttn {
13263                        softmax_scale: 1.0,
13264                        causal: false,
13265                        window_size_left: None,
13266                        window_size_right: None,
13267                        softcap: None,
13268                        k_len: None,
13269                    },
13270                ),
13271                inputs: vec![q, k, v],
13272                shape: Shape::from_dims(&[1, 1, 1, 2]),
13273                dtype: DType::F32,
13274            });
13275            g.set_target_backend(op, BackendId::Cpu);
13276            (q, k, v, op)
13277        };
13278        let mut inputs = StorageCache::new();
13279        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13280        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13281        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13282        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13283        let guard = result_arc.read().unwrap();
13284        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13285            panic!("expected Cpu storage");
13286        };
13287        let r = c.as_slice::<f32>().unwrap();
13288        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
13289        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
13290        assert!(
13291            (r[0] - 10.0 * expected_p0).abs() < 1e-5,
13292            "row[0]: got {} expected {}",
13293            r[0],
13294            10.0 * expected_p0
13295        );
13296        assert!(
13297            (r[1] - 10.0 * expected_p1).abs() < 1e-5,
13298            "row[1]: got {} expected {}",
13299            r[1],
13300            10.0 * expected_p1
13301        );
13302    }
13303
13304    /// E2E: FlashAttn with causal mask — second query position
13305    /// attends to both keys (positions 0 and 1), first only attends
13306    /// to key 0 (everything beyond is masked).
13307    #[test]
13308    fn pipelined_realize_flash_attn_causal_f32() {
13309        // q [1,1,2,2]: query 0 = [1, 0], query 1 = [0, 1]
13310        // k [1,1,2,2]: keys = [[1, 0], [0, 1]]
13311        // v [1,1,2,2]: values = [[5, 6], [7, 8]]
13312        // softmax_scale=1, causal:
13313        //   query 0: only key 0 admissible → out = v[0] = [5, 6]
13314        //   query 1: both admissible. scores = q1·k = [0, 1]
13315        //            softmax = [1/(e+1), e/(e+1)]
13316        //            out = scores · v = [(5)/(e+1) + 7e/(e+1), 6/(e+1) + 8e/(e+1)]
13317        let q = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13318        let k = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13319        let v = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0, 7.0, 8.0]);
13320        let graph = Arc::new(RwLock::new(Graph::new()));
13321        let (q_id, k_id, v_id, op_id) = {
13322            let mut g = graph.write().unwrap();
13323            let q = g.push(Node {
13324                op: Op::Const,
13325                inputs: vec![],
13326                shape: Shape::from_dims(&[1, 1, 2, 2]),
13327                dtype: DType::F32,
13328            });
13329            let k = g.push(Node {
13330                op: Op::Const,
13331                inputs: vec![],
13332                shape: Shape::from_dims(&[1, 1, 2, 2]),
13333                dtype: DType::F32,
13334            });
13335            let v = g.push(Node {
13336                op: Op::Const,
13337                inputs: vec![],
13338                shape: Shape::from_dims(&[1, 1, 2, 2]),
13339                dtype: DType::F32,
13340            });
13341            let op = g.push(Node {
13342                op: Op::Fused(
13343                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13344                    fuel_graph::registry::FusedOpParams::FlashAttn {
13345                        softmax_scale: 1.0,
13346                        causal: true,
13347                        window_size_left: None,
13348                        window_size_right: None,
13349                        softcap: None,
13350                        k_len: None,
13351                    },
13352                ),
13353                inputs: vec![q, k, v],
13354                shape: Shape::from_dims(&[1, 1, 2, 2]),
13355                dtype: DType::F32,
13356            });
13357            g.set_target_backend(op, BackendId::Cpu);
13358            (q, k, v, op)
13359        };
13360        let mut inputs = StorageCache::new();
13361        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13362        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13363        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13364        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13365        let guard = result_arc.read().unwrap();
13366        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13367            panic!("expected Cpu storage");
13368        };
13369        let r = c.as_slice::<f32>().unwrap();
13370        // Query 0 sees only key 0 → output = v[0]
13371        assert!((r[0] - 5.0).abs() < 1e-5, "got {}", r[0]);
13372        assert!((r[1] - 6.0).abs() < 1e-5, "got {}", r[1]);
13373        // Query 1 sees both. softmax([0, 1]) = [1/(e+1), e/(e+1)]
13374        let denom = (1.0_f32).exp() + 1.0;
13375        let expected_a = 5.0 / denom + 7.0 * (1.0_f32).exp() / denom;
13376        let expected_b = 6.0 / denom + 8.0 * (1.0_f32).exp() / denom;
13377        assert!(
13378            (r[2] - expected_a).abs() < 1e-5,
13379            "row1[0]: got {} expected {}",
13380            r[2],
13381            expected_a
13382        );
13383        assert!(
13384            (r[3] - expected_b).abs() < 1e-5,
13385            "row1[1]: got {} expected {}",
13386            r[3],
13387            expected_b
13388        );
13389    }
13390
13391    /// E2E: FlashAttn over a fixed-**capacity** K/V with a runtime
13392    /// `k_len` resolved through a `SymEnv` (Phase D symbolic extents).
13393    /// Only the first `k_len` rows are attended; trailing "poison" rows
13394    /// in the capacity buffer are ignored, and the causal mask is
13395    /// bottom-right-aligned at offset `k_len - Sq`. This is flash decode
13396    /// over a persistent KV-cache: K/V are `[.., max_seq, ..]` capacity
13397    /// and the live prefix grows per token.
13398    #[test]
13399    fn pipelined_realize_flash_attn_dynamic_k_len() {
13400        use fuel_ir::{DynScalar, SymId};
13401        // q [1,1,2,2]; K/V capacity [1,1,4,2]; bind k_len = 3 so row 3
13402        // (the "poison" row) is never attended.
13403        let q = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13404        let k = fuel_memory::from_slice_cpu(&[
13405            1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0, 100.0,
13406            100.0, // poison row 3 — must be ignored (k_len=3)
13407        ]);
13408        let v = fuel_memory::from_slice_cpu(&[
13409            5.0_f32, 6.0, 7.0, 8.0, 9.0, 10.0, 999.0,
13410            999.0, // poison row 3 — must be ignored
13411        ]);
13412        let sym = SymId(0);
13413        let graph = Arc::new(RwLock::new(Graph::new()));
13414        let (q_id, k_id, v_id, op_id) = {
13415            let mut g = graph.write().unwrap();
13416            let q = g.push(Node {
13417                op: Op::Const,
13418                inputs: vec![],
13419                shape: Shape::from_dims(&[1, 1, 2, 2]),
13420                dtype: DType::F32,
13421            });
13422            let k = g.push(Node {
13423                op: Op::Const,
13424                inputs: vec![],
13425                shape: Shape::from_dims(&[1, 1, 4, 2]),
13426                dtype: DType::F32,
13427            });
13428            let v = g.push(Node {
13429                op: Op::Const,
13430                inputs: vec![],
13431                shape: Shape::from_dims(&[1, 1, 4, 2]),
13432                dtype: DType::F32,
13433            });
13434            let op = g.push(Node {
13435                op: Op::Fused(
13436                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13437                    fuel_graph::registry::FusedOpParams::FlashAttn {
13438                        softmax_scale: 1.0,
13439                        causal: true,
13440                        window_size_left: None,
13441                        window_size_right: None,
13442                        softcap: None,
13443                        k_len: Some(DynScalar::Sym(sym)),
13444                    },
13445                ),
13446                inputs: vec![q, k, v],
13447                shape: Shape::from_dims(&[1, 1, 2, 2]),
13448                dtype: DType::F32,
13449            });
13450            g.set_target_backend(op, BackendId::Cpu);
13451            (q, k, v, op)
13452        };
13453        let mut inputs = StorageCache::new();
13454        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13455        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13456        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13457        let mut env = SymEnv::new();
13458        env.bind(sym, 3).unwrap();
13459        let (result_arc, _) = PipelinedExecutor::realize_with_env(graph, op_id, inputs, env)
13460            .expect("realize_with_env");
13461        let guard = result_arc.read().unwrap();
13462        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13463            panic!("expected Cpu storage");
13464        };
13465        let r = c.as_slice::<f32>().unwrap();
13466        let e = 1.0_f32.exp();
13467        // causal_offset = k_len - Sq = 3 - 2 = 1.
13468        // Query 0 (abs pos 1): keys {0,1}. scores [1,0] → softmax [e,1]/(e+1).
13469        let d0 = e + 1.0;
13470        let e0x = (5.0 * e + 7.0) / d0;
13471        let e0y = (6.0 * e + 8.0) / d0;
13472        // Query 1 (abs pos 2): keys {0,1,2}. scores [0,1,1] → [1,e,e]/(1+2e).
13473        let d1 = 1.0 + 2.0 * e;
13474        let e1x = (5.0 + 7.0 * e + 9.0 * e) / d1;
13475        let e1y = (6.0 + 8.0 * e + 10.0 * e) / d1;
13476        for (got, want) in r.iter().zip([e0x, e0y, e1x, e1y].iter()) {
13477            assert!(
13478                (got - want).abs() < 1e-4,
13479                "flash dyn k_len: got {got}, want {want} (full output {r:?}); \
13480                 a poison-contaminated value means the capacity rows past k_len leaked in",
13481            );
13482        }
13483    }
13484
13485    /// A flash `k_len` symbol unbound in the `SymEnv` surfaces a typed
13486    /// error at realize (never a panic).
13487    #[test]
13488    fn pipelined_realize_flash_attn_dynamic_k_len_unbound_errors() {
13489        use fuel_ir::{DynScalar, SymId};
13490        let q = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13491        let k = fuel_memory::from_slice_cpu(&[0.0_f32; 16]);
13492        let v = fuel_memory::from_slice_cpu(&[0.0_f32; 16]);
13493        let graph = Arc::new(RwLock::new(Graph::new()));
13494        let (q_id, k_id, v_id, op_id) = {
13495            let mut g = graph.write().unwrap();
13496            let q = g.push(Node {
13497                op: Op::Const,
13498                inputs: vec![],
13499                shape: Shape::from_dims(&[1, 1, 2, 2]),
13500                dtype: DType::F32,
13501            });
13502            let k = g.push(Node {
13503                op: Op::Const,
13504                inputs: vec![],
13505                shape: Shape::from_dims(&[1, 1, 4, 2]),
13506                dtype: DType::F32,
13507            });
13508            let v = g.push(Node {
13509                op: Op::Const,
13510                inputs: vec![],
13511                shape: Shape::from_dims(&[1, 1, 4, 2]),
13512                dtype: DType::F32,
13513            });
13514            let op = g.push(Node {
13515                op: Op::Fused(
13516                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13517                    fuel_graph::registry::FusedOpParams::FlashAttn {
13518                        softmax_scale: 1.0,
13519                        causal: true,
13520                        window_size_left: None,
13521                        window_size_right: None,
13522                        softcap: None,
13523                        k_len: Some(DynScalar::Sym(SymId(0))),
13524                    },
13525                ),
13526                inputs: vec![q, k, v],
13527                shape: Shape::from_dims(&[1, 1, 2, 2]),
13528                dtype: DType::F32,
13529            });
13530            g.set_target_backend(op, BackendId::Cpu);
13531            (q, k, v, op)
13532        };
13533        let mut inputs = StorageCache::new();
13534        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13535        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13536        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13537        // Empty env — the k_len symbol is unbound.
13538        let result = PipelinedExecutor::realize_with_env(graph, op_id, inputs, SymEnv::new());
13539        assert!(
13540            result.is_err(),
13541            "unbound flash k_len symbol must surface a typed error"
13542        );
13543    }
13544
13545    /// E2E: FlashAttn BF16 — same single-row test as f32, tolerant.
13546    #[test]
13547    fn pipelined_realize_flash_attn_bf16() {
13548        let q_v: Vec<half::bf16> = [2.0_f32, 0.0]
13549            .iter()
13550            .map(|x| half::bf16::from_f32(*x))
13551            .collect();
13552        let k_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0]
13553            .iter()
13554            .map(|x| half::bf16::from_f32(*x))
13555            .collect();
13556        let v_v: Vec<half::bf16> = [10.0_f32, 0.0, 0.0, 10.0]
13557            .iter()
13558            .map(|x| half::bf16::from_f32(*x))
13559            .collect();
13560        let q = fuel_memory::from_slice_cpu(&q_v);
13561        let k = fuel_memory::from_slice_cpu(&k_v);
13562        let v = fuel_memory::from_slice_cpu(&v_v);
13563        let graph = Arc::new(RwLock::new(Graph::new()));
13564        let (q_id, k_id, v_id, op_id) = {
13565            let mut g = graph.write().unwrap();
13566            let q = g.push(Node {
13567                op: Op::Const,
13568                inputs: vec![],
13569                shape: Shape::from_dims(&[1, 1, 1, 2]),
13570                dtype: DType::BF16,
13571            });
13572            let k = g.push(Node {
13573                op: Op::Const,
13574                inputs: vec![],
13575                shape: Shape::from_dims(&[1, 1, 2, 2]),
13576                dtype: DType::BF16,
13577            });
13578            let v = g.push(Node {
13579                op: Op::Const,
13580                inputs: vec![],
13581                shape: Shape::from_dims(&[1, 1, 2, 2]),
13582                dtype: DType::BF16,
13583            });
13584            let op = g.push(Node {
13585                op: Op::Fused(
13586                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13587                    fuel_graph::registry::FusedOpParams::FlashAttn {
13588                        softmax_scale: 1.0,
13589                        causal: false,
13590                        window_size_left: None,
13591                        window_size_right: None,
13592                        softcap: None,
13593                        k_len: None,
13594                    },
13595                ),
13596                inputs: vec![q, k, v],
13597                shape: Shape::from_dims(&[1, 1, 1, 2]),
13598                dtype: DType::BF16,
13599            });
13600            g.set_target_backend(op, BackendId::Cpu);
13601            (q, k, v, op)
13602        };
13603        let mut inputs = StorageCache::new();
13604        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13605        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13606        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13607        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13608        let guard = result_arc.read().unwrap();
13609        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13610            panic!("expected Cpu storage");
13611        };
13612        let got: Vec<f32> = c
13613            .as_slice::<half::bf16>()
13614            .unwrap()
13615            .iter()
13616            .map(|v| v.to_f32())
13617            .collect();
13618        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
13619        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
13620        let want = [10.0 * expected_p0, 10.0 * expected_p1];
13621        for (g, w) in got.iter().zip(want.iter()) {
13622            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
13623        }
13624    }
13625
13626    /// E2E: Op::FusedLinear — F32. a[1,2,3] @ b[1,3,2] + bias[2].
13627    /// a = [[[1,2,3],[4,5,6]]], b = [[[1,0],[0,1],[1,1]]], bias=[10,20]
13628    /// matmul = [[1+0+3, 0+2+3], [4+0+6, 0+5+6]] = [[4, 5], [10, 11]]
13629    /// + bias = [[14, 25], [20, 31]]
13630    #[test]
13631    fn pipelined_realize_fused_linear_f32() {
13632        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
13633        let b = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0]);
13634        let bias = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
13635        let graph = Arc::new(RwLock::new(Graph::new()));
13636        let (a_id, b_id, bias_id, op_id) = {
13637            let mut g = graph.write().unwrap();
13638            let a = g.push(Node {
13639                op: Op::Const,
13640                inputs: vec![],
13641                shape: Shape::from_dims(&[1, 2, 3]),
13642                dtype: DType::F32,
13643            });
13644            let b = g.push(Node {
13645                op: Op::Const,
13646                inputs: vec![],
13647                shape: Shape::from_dims(&[1, 3, 2]),
13648                dtype: DType::F32,
13649            });
13650            let bias = g.push(Node {
13651                op: Op::Const,
13652                inputs: vec![],
13653                shape: Shape::from_dims(&[2]),
13654                dtype: DType::F32,
13655            });
13656            let op = g.push(Node {
13657                op: Op::Fused(
13658                    fuel_graph::registry::FusedOps::FUSED_LINEAR,
13659                    fuel_graph::registry::FusedOpParams::FusedLinear,
13660                ),
13661                inputs: vec![a, b, bias],
13662                shape: Shape::from_dims(&[1, 2, 2]),
13663                dtype: DType::F32,
13664            });
13665            g.set_target_backend(op, BackendId::Cpu);
13666            (a, b, bias, op)
13667        };
13668        let mut inputs = StorageCache::new();
13669        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13670        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13671        inputs.insert(bias_id, Arc::new(RwLock::new(bias)));
13672        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13673        let guard = result_arc.read().unwrap();
13674        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13675            panic!("expected Cpu storage");
13676        };
13677        assert_eq!(c.as_slice::<f32>().unwrap(), &[14.0, 25.0, 20.0, 31.0]);
13678    }
13679
13680    /// E2E: FusedLinear F64 — same shape test on doubles.
13681    #[test]
13682    fn pipelined_realize_fused_linear_f64() {
13683        let a = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
13684        let b = fuel_memory::from_slice_cpu(&[1.0_f64, 0.0, 0.0, 1.0, 1.0, 1.0]);
13685        let bias = fuel_memory::from_slice_cpu(&[10.0_f64, 20.0]);
13686        let graph = Arc::new(RwLock::new(Graph::new()));
13687        let (a_id, b_id, bias_id, op_id) = {
13688            let mut g = graph.write().unwrap();
13689            let a = g.push(Node {
13690                op: Op::Const,
13691                inputs: vec![],
13692                shape: Shape::from_dims(&[1, 2, 3]),
13693                dtype: DType::F64,
13694            });
13695            let b = g.push(Node {
13696                op: Op::Const,
13697                inputs: vec![],
13698                shape: Shape::from_dims(&[1, 3, 2]),
13699                dtype: DType::F64,
13700            });
13701            let bias = g.push(Node {
13702                op: Op::Const,
13703                inputs: vec![],
13704                shape: Shape::from_dims(&[2]),
13705                dtype: DType::F64,
13706            });
13707            let op = g.push(Node {
13708                op: Op::Fused(
13709                    fuel_graph::registry::FusedOps::FUSED_LINEAR,
13710                    fuel_graph::registry::FusedOpParams::FusedLinear,
13711                ),
13712                inputs: vec![a, b, bias],
13713                shape: Shape::from_dims(&[1, 2, 2]),
13714                dtype: DType::F64,
13715            });
13716            g.set_target_backend(op, BackendId::Cpu);
13717            (a, b, bias, op)
13718        };
13719        let mut inputs = StorageCache::new();
13720        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13721        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13722        inputs.insert(bias_id, Arc::new(RwLock::new(bias)));
13723        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13724        let guard = result_arc.read().unwrap();
13725        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13726            panic!("expected Cpu storage");
13727        };
13728        assert_eq!(c.as_slice::<f64>().unwrap(), &[14.0, 25.0, 20.0, 31.0]);
13729    }
13730
13731    /// E2E: FusedLinear BF16 — tolerant compare.
13732    #[test]
13733    fn pipelined_realize_fused_linear_bf16() {
13734        let a_v: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]
13735            .iter()
13736            .map(|x| half::bf16::from_f32(*x))
13737            .collect();
13738        let b_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0]
13739            .iter()
13740            .map(|x| half::bf16::from_f32(*x))
13741            .collect();
13742        let bias_v: Vec<half::bf16> = [10.0_f32, 20.0]
13743            .iter()
13744            .map(|x| half::bf16::from_f32(*x))
13745            .collect();
13746        let a = fuel_memory::from_slice_cpu(&a_v);
13747        let b = fuel_memory::from_slice_cpu(&b_v);
13748        let bias = fuel_memory::from_slice_cpu(&bias_v);
13749        let graph = Arc::new(RwLock::new(Graph::new()));
13750        let (a_id, b_id, bias_id, op_id) = {
13751            let mut g = graph.write().unwrap();
13752            let a = g.push(Node {
13753                op: Op::Const,
13754                inputs: vec![],
13755                shape: Shape::from_dims(&[1, 2, 3]),
13756                dtype: DType::BF16,
13757            });
13758            let b = g.push(Node {
13759                op: Op::Const,
13760                inputs: vec![],
13761                shape: Shape::from_dims(&[1, 3, 2]),
13762                dtype: DType::BF16,
13763            });
13764            let bias = g.push(Node {
13765                op: Op::Const,
13766                inputs: vec![],
13767                shape: Shape::from_dims(&[2]),
13768                dtype: DType::BF16,
13769            });
13770            let op = g.push(Node {
13771                op: Op::Fused(
13772                    fuel_graph::registry::FusedOps::FUSED_LINEAR,
13773                    fuel_graph::registry::FusedOpParams::FusedLinear,
13774                ),
13775                inputs: vec![a, b, bias],
13776                shape: Shape::from_dims(&[1, 2, 2]),
13777                dtype: DType::BF16,
13778            });
13779            g.set_target_backend(op, BackendId::Cpu);
13780            (a, b, bias, op)
13781        };
13782        let mut inputs = StorageCache::new();
13783        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13784        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13785        inputs.insert(bias_id, Arc::new(RwLock::new(bias)));
13786        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13787        let guard = result_arc.read().unwrap();
13788        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13789            panic!("expected Cpu storage");
13790        };
13791        let got: Vec<f32> = c
13792            .as_slice::<half::bf16>()
13793            .unwrap()
13794            .iter()
13795            .map(|v| v.to_f32())
13796            .collect();
13797        let want = [14.0_f32, 25.0, 20.0, 31.0];
13798        for (g, w) in got.iter().zip(want.iter()) {
13799            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
13800        }
13801    }
13802
13803    /// E2E: Op::ReduceSumTo — sum the leading axis of a [2,3] tensor.
13804    /// Input [[1,2,3],[4,5,6]] → output [5,7,9].
13805    #[test]
13806    fn pipelined_realize_reduce_sum_to_f32_drops_leading_axis() {
13807        let v = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
13808        let graph = Arc::new(RwLock::new(Graph::new()));
13809        let (in_id, op_id) = {
13810            let mut g = graph.write().unwrap();
13811            let in_id = g.push(Node {
13812                op: Op::Const,
13813                inputs: vec![],
13814                shape: Shape::from_dims(&[2, 3]),
13815                dtype: DType::F32,
13816            });
13817            let op_id = g.push(Node {
13818                op: Op::ReduceSumTo(Shape::from_dims(&[3])),
13819                inputs: vec![in_id],
13820                shape: Shape::from_dims(&[3]),
13821                dtype: DType::F32,
13822            });
13823            g.set_target_backend(op_id, BackendId::Cpu);
13824            (in_id, op_id)
13825        };
13826        let mut inputs = StorageCache::new();
13827        inputs.insert(in_id, Arc::new(RwLock::new(v)));
13828        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13829        let guard = result_arc.read().unwrap();
13830        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13831            panic!("expected Cpu storage");
13832        };
13833        assert_eq!(c.as_slice::<f32>().unwrap(), &[5.0, 7.0, 9.0]);
13834    }
13835
13836    /// E2E: Op::ReduceSumTo — keep-dim with 1 in the middle.
13837    /// Input [2,3,4] → [2,1,4] sums along dim 1.
13838    #[test]
13839    fn pipelined_realize_reduce_sum_to_f32_keepdim_middle() {
13840        // [2,3,4]: layer 0 = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
13841        //          layer 1 = [[13..16],[17..20],[21..24]]
13842        let mut v: Vec<f32> = (1..=24).map(|x| x as f32).collect();
13843        let _ = &mut v;
13844        let s = fuel_memory::from_slice_cpu(&v);
13845        let graph = Arc::new(RwLock::new(Graph::new()));
13846        let (in_id, op_id) = {
13847            let mut g = graph.write().unwrap();
13848            let in_id = g.push(Node {
13849                op: Op::Const,
13850                inputs: vec![],
13851                shape: Shape::from_dims(&[2, 3, 4]),
13852                dtype: DType::F32,
13853            });
13854            let op_id = g.push(Node {
13855                op: Op::ReduceSumTo(Shape::from_dims(&[2, 1, 4])),
13856                inputs: vec![in_id],
13857                shape: Shape::from_dims(&[2, 1, 4]),
13858                dtype: DType::F32,
13859            });
13860            g.set_target_backend(op_id, BackendId::Cpu);
13861            (in_id, op_id)
13862        };
13863        let mut inputs = StorageCache::new();
13864        inputs.insert(in_id, Arc::new(RwLock::new(s)));
13865        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13866        let guard = result_arc.read().unwrap();
13867        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13868            panic!("expected Cpu storage");
13869        };
13870        // layer0 dim1-sum: col j = 1+5+9, 2+6+10, 3+7+11, 4+8+12 = [15,18,21,24]
13871        // layer1 dim1-sum: col j = 13+17+21, 14+18+22, 15+19+23, 16+20+24 = [51,54,57,60]
13872        assert_eq!(
13873            c.as_slice::<f32>().unwrap(),
13874            &[15.0, 18.0, 21.0, 24.0, 51.0, 54.0, 57.0, 60.0],
13875        );
13876    }
13877
13878    /// E2E: ReduceSumTo F64 — same drop-leading-axis test on doubles.
13879    #[test]
13880    fn pipelined_realize_reduce_sum_to_f64() {
13881        let v = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
13882        let graph = Arc::new(RwLock::new(Graph::new()));
13883        let (in_id, op_id) = {
13884            let mut g = graph.write().unwrap();
13885            let in_id = g.push(Node {
13886                op: Op::Const,
13887                inputs: vec![],
13888                shape: Shape::from_dims(&[2, 3]),
13889                dtype: DType::F64,
13890            });
13891            let op_id = g.push(Node {
13892                op: Op::ReduceSumTo(Shape::from_dims(&[3])),
13893                inputs: vec![in_id],
13894                shape: Shape::from_dims(&[3]),
13895                dtype: DType::F64,
13896            });
13897            g.set_target_backend(op_id, BackendId::Cpu);
13898            (in_id, op_id)
13899        };
13900        let mut inputs = StorageCache::new();
13901        inputs.insert(in_id, Arc::new(RwLock::new(v)));
13902        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13903        let guard = result_arc.read().unwrap();
13904        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13905            panic!("expected Cpu storage");
13906        };
13907        assert_eq!(c.as_slice::<f64>().unwrap(), &[5.0, 7.0, 9.0]);
13908    }
13909
13910    /// E2E: Op::ReduceMaxTo F32 — drop the leading axis with max-reduce.
13911    #[test]
13912    fn pipelined_realize_reduce_max_to_f32_drops_leading_axis() {
13913        // Input [2,3]: row 0 = [1, 7, 3], row 1 = [4, 2, 6]. Max along
13914        // dim 0: [4, 7, 6].
13915        let v = fuel_memory::from_slice_cpu(&[1.0_f32, 7.0, 3.0, 4.0, 2.0, 6.0]);
13916        let graph = Arc::new(RwLock::new(Graph::new()));
13917        let (in_id, op_id) = {
13918            let mut g = graph.write().unwrap();
13919            let in_id = g.push(Node {
13920                op: Op::Const,
13921                inputs: vec![],
13922                shape: Shape::from_dims(&[2, 3]),
13923                dtype: DType::F32,
13924            });
13925            let op_id = g.push(Node {
13926                op: Op::ReduceMaxTo(Shape::from_dims(&[3])),
13927                inputs: vec![in_id],
13928                shape: Shape::from_dims(&[3]),
13929                dtype: DType::F32,
13930            });
13931            g.set_target_backend(op_id, BackendId::Cpu);
13932            (in_id, op_id)
13933        };
13934        let mut inputs = StorageCache::new();
13935        inputs.insert(in_id, Arc::new(RwLock::new(v)));
13936        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13937        let guard = result_arc.read().unwrap();
13938        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13939            panic!("expected Cpu storage");
13940        };
13941        assert_eq!(c.as_slice::<f32>().unwrap(), &[4.0, 7.0, 6.0]);
13942    }
13943
13944    /// E2E: Op::ReduceMaxTo F32 — keep-dim with 1 in the trailing axis.
13945    /// Mirrors the SoftmaxLastDim lowering's max-side shape: input
13946    /// [..., last] → [..., 1].
13947    #[test]
13948    fn pipelined_realize_reduce_max_to_f32_keepdim_trailing() {
13949        // Input [2, 3]: row maxes = [3, 6].
13950        let v = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
13951        let graph = Arc::new(RwLock::new(Graph::new()));
13952        let (in_id, op_id) = {
13953            let mut g = graph.write().unwrap();
13954            let in_id = g.push(Node {
13955                op: Op::Const,
13956                inputs: vec![],
13957                shape: Shape::from_dims(&[2, 3]),
13958                dtype: DType::F32,
13959            });
13960            let op_id = g.push(Node {
13961                op: Op::ReduceMaxTo(Shape::from_dims(&[2, 1])),
13962                inputs: vec![in_id],
13963                shape: Shape::from_dims(&[2, 1]),
13964                dtype: DType::F32,
13965            });
13966            g.set_target_backend(op_id, BackendId::Cpu);
13967            (in_id, op_id)
13968        };
13969        let mut inputs = StorageCache::new();
13970        inputs.insert(in_id, Arc::new(RwLock::new(v)));
13971        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13972        let guard = result_arc.read().unwrap();
13973        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13974            panic!("expected Cpu storage");
13975        };
13976        assert_eq!(c.as_slice::<f32>().unwrap(), &[3.0, 6.0]);
13977    }
13978
13979    /// E2E: ReduceSumTo BF16 — tolerant compare via f32-acc.
13980    #[test]
13981    fn pipelined_realize_reduce_sum_to_bf16() {
13982        let v: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]
13983            .iter()
13984            .map(|x| half::bf16::from_f32(*x))
13985            .collect();
13986        let s = fuel_memory::from_slice_cpu(&v);
13987        let graph = Arc::new(RwLock::new(Graph::new()));
13988        let (in_id, op_id) = {
13989            let mut g = graph.write().unwrap();
13990            let in_id = g.push(Node {
13991                op: Op::Const,
13992                inputs: vec![],
13993                shape: Shape::from_dims(&[2, 3]),
13994                dtype: DType::BF16,
13995            });
13996            let op_id = g.push(Node {
13997                op: Op::ReduceSumTo(Shape::from_dims(&[3])),
13998                inputs: vec![in_id],
13999                shape: Shape::from_dims(&[3]),
14000                dtype: DType::BF16,
14001            });
14002            g.set_target_backend(op_id, BackendId::Cpu);
14003            (in_id, op_id)
14004        };
14005        let mut inputs = StorageCache::new();
14006        inputs.insert(in_id, Arc::new(RwLock::new(s)));
14007        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14008        let guard = result_arc.read().unwrap();
14009        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14010            panic!("expected Cpu storage");
14011        };
14012        let got: Vec<f32> = c
14013            .as_slice::<half::bf16>()
14014            .unwrap()
14015            .iter()
14016            .map(|v| v.to_f32())
14017            .collect();
14018        let want = [5.0_f32, 7.0, 9.0];
14019        for (g, w) in got.iter().zip(want.iter()) {
14020            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
14021        }
14022    }
14023
14024    /// E2E: Op::ConvTranspose2D — F32 spread test.
14025    /// x = [[1, 2], [3, 4]] shape [1,1,2,2], all-ones kernel
14026    /// shape [1,1,2,2], stride=1, padding=0, dilation=1, no bias.
14027    /// Expected output (3x3):
14028    ///   [[1,  3, 2],
14029    ///    [4, 10, 6],
14030    ///    [3,  7, 4]]
14031    #[test]
14032    fn pipelined_realize_conv_transpose2d_f32() {
14033        let x_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
14034        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
14035        let graph = Arc::new(RwLock::new(Graph::new()));
14036        let (x_id, w_id, c_id) = {
14037            let mut g = graph.write().unwrap();
14038            let x = g.push(Node {
14039                op: Op::Const,
14040                inputs: vec![],
14041                shape: Shape::from_dims(&[1, 1, 2, 2]),
14042                dtype: DType::F32,
14043            });
14044            let w = g.push(Node {
14045                op: Op::Const,
14046                inputs: vec![],
14047                shape: Shape::from_dims(&[1, 1, 2, 2]),
14048                dtype: DType::F32,
14049            });
14050            let c = g.push(Node {
14051                op: Op::Fused(
14052                    fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D,
14053                    fuel_graph::registry::FusedOpParams::ConvTranspose2D {
14054                        stride: (1, 1),
14055                        padding: (0, 0),
14056                        output_padding: (0, 0),
14057                        dilation: (1, 1),
14058                        groups: 1,
14059                    },
14060                ),
14061                inputs: vec![x, w],
14062                shape: Shape::from_dims(&[1, 1, 3, 3]),
14063                dtype: DType::F32,
14064            });
14065            g.set_target_backend(c, BackendId::Cpu);
14066            (x, w, c)
14067        };
14068        let mut inputs = StorageCache::new();
14069        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
14070        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
14071        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
14072        let guard = result_arc.read().unwrap();
14073        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14074            panic!("expected Cpu storage");
14075        };
14076        assert_eq!(
14077            c.as_slice::<f32>().unwrap(),
14078            &[1.0, 3.0, 2.0, 4.0, 10.0, 6.0, 3.0, 7.0, 4.0],
14079        );
14080    }
14081
14082    /// E2E: ConvTranspose2D F64 — same shape test.
14083    #[test]
14084    fn pipelined_realize_conv_transpose2d_f64() {
14085        let x_storage = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0]);
14086        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f64, 1.0, 1.0, 1.0]);
14087        let graph = Arc::new(RwLock::new(Graph::new()));
14088        let (x_id, w_id, c_id) = {
14089            let mut g = graph.write().unwrap();
14090            let x = g.push(Node {
14091                op: Op::Const,
14092                inputs: vec![],
14093                shape: Shape::from_dims(&[1, 1, 2, 2]),
14094                dtype: DType::F64,
14095            });
14096            let w = g.push(Node {
14097                op: Op::Const,
14098                inputs: vec![],
14099                shape: Shape::from_dims(&[1, 1, 2, 2]),
14100                dtype: DType::F64,
14101            });
14102            let c = g.push(Node {
14103                op: Op::Fused(
14104                    fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D,
14105                    fuel_graph::registry::FusedOpParams::ConvTranspose2D {
14106                        stride: (1, 1),
14107                        padding: (0, 0),
14108                        output_padding: (0, 0),
14109                        dilation: (1, 1),
14110                        groups: 1,
14111                    },
14112                ),
14113                inputs: vec![x, w],
14114                shape: Shape::from_dims(&[1, 1, 3, 3]),
14115                dtype: DType::F64,
14116            });
14117            g.set_target_backend(c, BackendId::Cpu);
14118            (x, w, c)
14119        };
14120        let mut inputs = StorageCache::new();
14121        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
14122        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
14123        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
14124        let guard = result_arc.read().unwrap();
14125        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14126            panic!("expected Cpu storage");
14127        };
14128        assert_eq!(
14129            c.as_slice::<f64>().unwrap(),
14130            &[1.0, 3.0, 2.0, 4.0, 10.0, 6.0, 3.0, 7.0, 4.0],
14131        );
14132    }
14133
14134    /// E2E: ConvTranspose2D BF16 — tolerant compare via f32-acc.
14135    #[test]
14136    fn pipelined_realize_conv_transpose2d_bf16() {
14137        let x: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0]
14138            .iter()
14139            .map(|v| half::bf16::from_f32(*v))
14140            .collect();
14141        let w: Vec<half::bf16> = [1.0_f32, 1.0, 1.0, 1.0]
14142            .iter()
14143            .map(|v| half::bf16::from_f32(*v))
14144            .collect();
14145        let x_storage = fuel_memory::from_slice_cpu(&x);
14146        let w_storage = fuel_memory::from_slice_cpu(&w);
14147        let graph = Arc::new(RwLock::new(Graph::new()));
14148        let (x_id, w_id, c_id) = {
14149            let mut g = graph.write().unwrap();
14150            let x = g.push(Node {
14151                op: Op::Const,
14152                inputs: vec![],
14153                shape: Shape::from_dims(&[1, 1, 2, 2]),
14154                dtype: DType::BF16,
14155            });
14156            let w = g.push(Node {
14157                op: Op::Const,
14158                inputs: vec![],
14159                shape: Shape::from_dims(&[1, 1, 2, 2]),
14160                dtype: DType::BF16,
14161            });
14162            let c = g.push(Node {
14163                op: Op::Fused(
14164                    fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D,
14165                    fuel_graph::registry::FusedOpParams::ConvTranspose2D {
14166                        stride: (1, 1),
14167                        padding: (0, 0),
14168                        output_padding: (0, 0),
14169                        dilation: (1, 1),
14170                        groups: 1,
14171                    },
14172                ),
14173                inputs: vec![x, w],
14174                shape: Shape::from_dims(&[1, 1, 3, 3]),
14175                dtype: DType::BF16,
14176            });
14177            g.set_target_backend(c, BackendId::Cpu);
14178            (x, w, c)
14179        };
14180        let mut inputs = StorageCache::new();
14181        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
14182        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
14183        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
14184        let guard = result_arc.read().unwrap();
14185        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14186            panic!("expected Cpu storage");
14187        };
14188        let got: Vec<f32> = c
14189            .as_slice::<half::bf16>()
14190            .unwrap()
14191            .iter()
14192            .map(|v| v.to_f32())
14193            .collect();
14194        let want = [1.0_f32, 3.0, 2.0, 4.0, 10.0, 6.0, 3.0, 7.0, 4.0];
14195        for (g, w) in got.iter().zip(want.iter()) {
14196            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
14197        }
14198    }
14199
14200    /// E2E: GQA-style matmul through the pipelined executor.
14201    /// lhs has 4 batch heads, rhs has 2; each rhs head is shared
14202    /// by 2 lhs heads. Output's batch dim follows lhs (4 heads).
14203    #[test]
14204    fn pipelined_realize_matmul_gqa() {
14205        // lhs [4, 1, 2]: heads 0..3 are [[1,2]], [[3,4]], [[5,6]], [[7,8]]
14206        // rhs [2, 2, 1]: heads 0,1 are [[1],[0]], [[0],[1]]
14207        // Expected out [4, 1, 1]: [[1]], [[3]], [[6]], [[8]]
14208        let lhs_storage =
14209            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]);
14210        let rhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
14211
14212        let graph = Arc::new(RwLock::new(Graph::new()));
14213        let (lhs_id, rhs_id, mm_id) = {
14214            let mut g = graph.write().unwrap();
14215            let lhs = g.push(Node {
14216                op: Op::Const,
14217                inputs: vec![],
14218                shape: Shape::from_dims(&[4, 1, 2]),
14219                dtype: DType::F32,
14220            });
14221            let rhs = g.push(Node {
14222                op: Op::Const,
14223                inputs: vec![],
14224                shape: Shape::from_dims(&[2, 2, 1]),
14225                dtype: DType::F32,
14226            });
14227            let mm = g.push(Node {
14228                op: Op::MatMul,
14229                inputs: vec![lhs, rhs],
14230                shape: Shape::from_dims(&[4, 1, 1]),
14231                dtype: DType::F32,
14232            });
14233            g.set_target_backend(mm, BackendId::Cpu);
14234            (lhs, rhs, mm)
14235        };
14236        let mut inputs = StorageCache::new();
14237        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
14238        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
14239
14240        let (result_arc, result_layout) =
14241            PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
14242        assert_eq!(result_layout.shape().dims(), &[4, 1, 1]);
14243
14244        let guard = result_arc.read().unwrap();
14245        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14246            panic!("expected Cpu storage");
14247        };
14248        assert_eq!(c.as_slice::<f32>().unwrap(), &[1.0, 3.0, 6.0, 8.0]);
14249    }
14250
14251    /// E2E: matmul with a transposed rhs — proves stage 3+4
14252    /// integration carries through the matmul path. The transpose
14253    /// is metadata-only; auto-Contiguize materializes the strided
14254    /// rhs before the matmul kernel sees it.
14255    #[test]
14256    fn pipelined_realize_matmul_with_transposed_rhs() {
14257        // lhs [[1, 2], [3, 4]], rhs original [[5, 6], [7, 8]]
14258        // rhs.T = [[5, 7], [6, 8]]
14259        // lhs @ rhs.T = [[1*5+2*6, 1*7+2*8], [3*5+4*6, 3*7+4*8]]
14260        //             = [[17, 23], [39, 53]]
14261        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
14262        let rhs_storage = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0, 7.0, 8.0]);
14263
14264        let graph = Arc::new(RwLock::new(Graph::new()));
14265        let (lhs_id, rhs_id, t_id, mm_id) = {
14266            let mut g = graph.write().unwrap();
14267            let lhs = g.push(Node {
14268                op: Op::Const,
14269                inputs: vec![],
14270                shape: Shape::from_dims(&[2, 2]),
14271                dtype: DType::F32,
14272            });
14273            let rhs = g.push(Node {
14274                op: Op::Const,
14275                inputs: vec![],
14276                shape: Shape::from_dims(&[2, 2]),
14277                dtype: DType::F32,
14278            });
14279            let t = g.push(Node {
14280                op: Op::Transpose,
14281                inputs: vec![rhs],
14282                shape: Shape::from_dims(&[2, 2]),
14283                dtype: DType::F32,
14284            });
14285            let mm = g.push(Node {
14286                op: Op::MatMul,
14287                inputs: vec![lhs, t],
14288                shape: Shape::from_dims(&[2, 2]),
14289                dtype: DType::F32,
14290            });
14291            g.set_target_backend(mm, BackendId::Cpu);
14292            (lhs, rhs, t, mm)
14293        };
14294        let _ = t_id;
14295        let mut inputs = StorageCache::new();
14296        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
14297        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
14298
14299        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
14300        let guard = result_arc.read().unwrap();
14301        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14302            panic!("expected Cpu storage");
14303        };
14304        assert_eq!(c.as_slice::<f32>().unwrap(), &[17.0, 23.0, 39.0, 53.0]);
14305    }
14306
14307    /// E2E: Const + Reshape — contiguous-input reshape is zero
14308    /// copy. The output Storage Arc is the input Arc; the layout
14309    /// is contiguous in the new shape.
14310    #[test]
14311    fn pipelined_realize_reshape_zero_copy_when_contiguous() {
14312        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14313        let graph = Arc::new(RwLock::new(Graph::new()));
14314        let (in_id, r_id) = {
14315            let mut g = graph.write().unwrap();
14316            let in_id = g.push(Node {
14317                op: Op::Const,
14318                inputs: vec![],
14319                shape: Shape::from_dims(&[2, 3]),
14320                dtype: DType::F32,
14321            });
14322            let r_id = g.push(Node {
14323                op: Op::Reshape(Shape::from_dims(&[3, 2])),
14324                inputs: vec![in_id],
14325                shape: Shape::from_dims(&[3, 2]),
14326                dtype: DType::F32,
14327            });
14328            (in_id, r_id)
14329        };
14330        let mut inputs = StorageCache::new();
14331        let in_arc = Arc::new(RwLock::new(storage));
14332        inputs.insert(in_id, Arc::clone(&in_arc));
14333
14334        let (result_arc, result_layout) =
14335            PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
14336
14337        // Zero copy — same Arc.
14338        assert!(
14339            Arc::ptr_eq(&result_arc, &in_arc),
14340            "contiguous reshape must zero-copy"
14341        );
14342        assert_eq!(result_layout.shape().dims(), &[3, 2]);
14343        assert!(result_layout.is_contiguous());
14344
14345        // Bytes are unchanged; just reinterpreted as [3, 2].
14346        let guard = result_arc.read().unwrap();
14347        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14348            panic!("expected Cpu storage");
14349        };
14350        assert_eq!(
14351            c.as_slice::<f32>().unwrap(),
14352            &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
14353        );
14354    }
14355
14356    /// E2E: Const + Transpose + Reshape — reshape on a strided
14357    /// input auto-contiguizes the bytes. Output Arc is fresh
14358    /// (NOT the input Arc); the bytes are the materialized
14359    /// transposed layout.
14360    #[test]
14361    fn pipelined_realize_reshape_materializes_when_strided() {
14362        // shape [2, 3]: 1 2 3 / 4 5 6
14363        // Transpose → [3, 2] strided
14364        // Reshape → [6] (forces materialization)
14365        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14366        let graph = Arc::new(RwLock::new(Graph::new()));
14367        let (in_id, t_id, r_id) = {
14368            let mut g = graph.write().unwrap();
14369            let in_id = g.push(Node {
14370                op: Op::Const,
14371                inputs: vec![],
14372                shape: Shape::from_dims(&[2, 3]),
14373                dtype: DType::F32,
14374            });
14375            let t_id = g.push(Node {
14376                op: Op::Transpose,
14377                inputs: vec![in_id],
14378                shape: Shape::from_dims(&[3, 2]),
14379                dtype: DType::F32,
14380            });
14381            let r_id = g.push(Node {
14382                op: Op::Reshape(Shape::from_dims(&[6])),
14383                inputs: vec![t_id],
14384                shape: Shape::from_dims(&[6]),
14385                dtype: DType::F32,
14386            });
14387            (in_id, t_id, r_id)
14388        };
14389        let _ = t_id;
14390        let mut inputs = StorageCache::new();
14391        let in_arc = Arc::new(RwLock::new(storage));
14392        inputs.insert(in_id, Arc::clone(&in_arc));
14393
14394        let (result_arc, result_layout) =
14395            PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
14396
14397        // Fresh Arc — auto-contiguize allocated new bytes.
14398        assert!(!Arc::ptr_eq(&result_arc, &in_arc));
14399        assert_eq!(result_layout.shape().dims(), &[6]);
14400        assert!(result_layout.is_contiguous());
14401
14402        // Materialized transposed bytes flattened: [1, 4, 2, 5, 3, 6].
14403        let guard = result_arc.read().unwrap();
14404        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14405            panic!("expected Cpu storage");
14406        };
14407        assert_eq!(
14408            c.as_slice::<f32>().unwrap(),
14409            &[1.0, 4.0, 2.0, 5.0, 3.0, 6.0]
14410        );
14411    }
14412
14413    /// E2E: Const + Transpose + SumDim — exercises stage 3
14414    /// (metadata-only Transpose, strided intermediate Layout) +
14415    /// stage 4 (auto-Contiguize before reduce kernel) end-to-end.
14416    /// The transpose makes the intermediate non-contiguous; the
14417    /// reduce wrapper would have failed in stage 2; with stage 4's
14418    /// auto-Contiguize, the kernel sees the materialized contiguous
14419    /// transposed bytes and produces the right answer.
14420    #[test]
14421    fn pipelined_realize_transpose_then_sum_dim_e2e() {
14422        // shape [2, 3]: rows are [1, 2, 3], [4, 5, 6]
14423        // After transpose: shape [3, 2], rows are [1, 4], [2, 5], [3, 6]
14424        // After SumDim(1): shape [3], values [5, 7, 9]
14425        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14426        let graph = Arc::new(RwLock::new(Graph::new()));
14427        let (in_id, t_id, sum_id) = {
14428            let mut g = graph.write().unwrap();
14429            let in_id = g.push(Node {
14430                op: Op::Const,
14431                inputs: vec![],
14432                shape: Shape::from_dims(&[2, 3]),
14433                dtype: DType::F32,
14434            });
14435            let t_id = g.push(Node {
14436                op: Op::Transpose,
14437                inputs: vec![in_id],
14438                shape: Shape::from_dims(&[3, 2]),
14439                dtype: DType::F32,
14440            });
14441            let sum_id = g.push(Node {
14442                op: Op::SumDim(1),
14443                inputs: vec![t_id],
14444                shape: Shape::from_dims(&[3]),
14445                dtype: DType::F32,
14446            });
14447            // Only the reduce kernel runs on the backend; the
14448            // transpose is metadata-only and doesn't need a target.
14449            g.set_target_backend(sum_id, BackendId::Cpu);
14450            (in_id, t_id, sum_id)
14451        };
14452        let _ = t_id;
14453        let mut inputs = StorageCache::new();
14454        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14455
14456        let (result_arc, result_layout) =
14457            PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
14458
14459        // The reduce output is contiguous (kernel-produced).
14460        assert_eq!(result_layout.shape().dims(), &[3]);
14461        assert!(result_layout.is_contiguous());
14462
14463        let guard = result_arc.read().unwrap();
14464        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14465            panic!("expected Cpu storage");
14466        };
14467        let typed: &[f32] = c.as_slice().unwrap();
14468        assert_eq!(typed, &[5.0, 7.0, 9.0]);
14469    }
14470
14471    /// E2E: Const + BroadcastTo + Add — broadcast intermediate
14472    /// auto-contiguizes for the Add kernel; the result is the
14473    /// expected sum.
14474    #[test]
14475    fn pipelined_realize_broadcast_then_add_e2e() {
14476        // shape [3]: [10, 20, 30]
14477        // BroadcastTo [2, 3]: [[10, 20, 30], [10, 20, 30]]
14478        // Plus shape [2, 3]: [[1, 2, 3], [4, 5, 6]]
14479        // Result: [[11, 22, 33], [14, 25, 36]]
14480        let bc_input = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
14481        let plus_input = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14482        let graph = Arc::new(RwLock::new(Graph::new()));
14483        let (bc_in_id, plus_in_id, b_id, add_id) = {
14484            let mut g = graph.write().unwrap();
14485            let bc_in = g.push(Node {
14486                op: Op::Const,
14487                inputs: vec![],
14488                shape: Shape::from_dims(&[3]),
14489                dtype: DType::F32,
14490            });
14491            let plus_in = g.push(Node {
14492                op: Op::Const,
14493                inputs: vec![],
14494                shape: Shape::from_dims(&[2, 3]),
14495                dtype: DType::F32,
14496            });
14497            let b = g.push(Node {
14498                op: Op::BroadcastTo(Shape::from_dims(&[2, 3])),
14499                inputs: vec![bc_in],
14500                shape: Shape::from_dims(&[2, 3]),
14501                dtype: DType::F32,
14502            });
14503            let add = g.push(Node {
14504                op: Op::Add,
14505                inputs: vec![b, plus_in],
14506                shape: Shape::from_dims(&[2, 3]),
14507                dtype: DType::F32,
14508            });
14509            g.set_target_backend(add, BackendId::Cpu);
14510            (bc_in, plus_in, b, add)
14511        };
14512        let _ = b_id;
14513        let mut inputs = StorageCache::new();
14514        inputs.insert(bc_in_id, Arc::new(RwLock::new(bc_input)));
14515        inputs.insert(plus_in_id, Arc::new(RwLock::new(plus_input)));
14516
14517        let (result_arc, _result_layout) =
14518            PipelinedExecutor::realize(graph, add_id, inputs).expect("realize");
14519        let guard = result_arc.read().unwrap();
14520        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14521            panic!("expected Cpu storage");
14522        };
14523        let typed: &[f32] = c.as_slice().unwrap();
14524        assert_eq!(typed, &[11.0, 22.0, 33.0, 14.0, 25.0, 36.0]);
14525    }
14526
14527    /// E2E: Const + SumDim — verifies that `OpParams::Reduce`
14528    /// flows from the graph (input shape via `op_to_op_params`)
14529    /// through compile_one and reaches the reduce kernel.
14530    #[test]
14531    fn pipelined_realize_sum_dim() {
14532        // shape [2, 3]; reduce dim 1 → output shape [2]
14533        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14534        let graph = Arc::new(RwLock::new(Graph::new()));
14535        let (in_id, sum_id) = {
14536            let mut g = graph.write().unwrap();
14537            let in_id = g.push(Node {
14538                op: Op::Const,
14539                inputs: vec![],
14540                shape: Shape::from_dims(&[2, 3]),
14541                dtype: DType::F32,
14542            });
14543            let sum_id = g.push(Node {
14544                op: Op::SumDim(1),
14545                inputs: vec![in_id],
14546                shape: Shape::from_dims(&[2]),
14547                dtype: DType::F32,
14548            });
14549            g.set_target_backend(sum_id, BackendId::Cpu);
14550            (in_id, sum_id)
14551        };
14552        let mut inputs = StorageCache::new();
14553        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14554
14555        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
14556        let guard = result_arc.read().unwrap();
14557        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14558            let typed: &[f32] = c.as_slice().unwrap();
14559            assert_eq!(typed, &[6.0, 15.0]);
14560        }
14561    }
14562
14563    /// E2E: SumAll on a rank-3 input, exercising the all-dims branch
14564    /// of `op_to_op_params` (every dim reduced, rank-0 output).
14565    #[test]
14566    fn pipelined_realize_sum_all_rank3() {
14567        let data: Vec<f32> = (1..=24).map(|x| x as f32).collect();
14568        let storage = fuel_memory::from_slice_cpu(&data);
14569        let graph = Arc::new(RwLock::new(Graph::new()));
14570        let (in_id, sum_id) = {
14571            let mut g = graph.write().unwrap();
14572            let in_id = g.push(Node {
14573                op: Op::Const,
14574                inputs: vec![],
14575                shape: Shape::from_dims(&[2, 3, 4]),
14576                dtype: DType::F32,
14577            });
14578            let sum_id = g.push(Node {
14579                op: Op::SumAll,
14580                inputs: vec![in_id],
14581                shape: Shape::from_dims(&[]),
14582                dtype: DType::F32,
14583            });
14584            g.set_target_backend(sum_id, BackendId::Cpu);
14585            (in_id, sum_id)
14586        };
14587        let mut inputs = StorageCache::new();
14588        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14589
14590        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
14591        let guard = result_arc.read().unwrap();
14592        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14593            let typed: &[f32] = c.as_slice().unwrap();
14594            // 1 + 2 + ... + 24 = 300
14595            assert_eq!(typed, &[300.0]);
14596        }
14597    }
14598
14599    /// E2E: MaxDim + MeanDim chained — verifies all four reduce
14600    /// OpKinds reach their wrappers via the OpParams plumbing.
14601    #[test]
14602    fn pipelined_realize_max_then_mean() {
14603        // shape [2, 3], MaxDim(1) → [2], MeanDim(0) → []
14604        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 9.0, 3.0, 4.0, 2.0, 8.0]);
14605        let graph = Arc::new(RwLock::new(Graph::new()));
14606        let (in_id, mean_id) = {
14607            let mut g = graph.write().unwrap();
14608            let in_id = g.push(Node {
14609                op: Op::Const,
14610                inputs: vec![],
14611                shape: Shape::from_dims(&[2, 3]),
14612                dtype: DType::F32,
14613            });
14614            let max_id = g.push(Node {
14615                op: Op::MaxDim(1),
14616                inputs: vec![in_id],
14617                shape: Shape::from_dims(&[2]),
14618                dtype: DType::F32,
14619            });
14620            let mean_id = g.push(Node {
14621                op: Op::MeanDim(0),
14622                inputs: vec![max_id],
14623                shape: Shape::from_dims(&[]),
14624                dtype: DType::F32,
14625            });
14626            g.set_target_backend(max_id, BackendId::Cpu);
14627            g.set_target_backend(mean_id, BackendId::Cpu);
14628            (in_id, mean_id)
14629        };
14630        let mut inputs = StorageCache::new();
14631        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14632
14633        let (result_arc, _) = PipelinedExecutor::realize(graph, mean_id, inputs).expect("realize");
14634        let guard = result_arc.read().unwrap();
14635        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14636            let typed: &[f32] = c.as_slice().unwrap();
14637            // MaxDim(1) on [[1,9,3],[4,2,8]] = [9, 8]; MeanDim(0) = 8.5
14638            assert_eq!(typed, &[8.5]);
14639        }
14640    }
14641
14642    /// E2E: Sigmoid + Silu — exercises two of the more compositional
14643    /// new unary kernels through the pipelined executor. Verifies
14644    /// the additional `op_to_op_kind` mappings reach the right
14645    /// dispatch wrappers.
14646    #[test]
14647    fn pipelined_realize_sigmoid_then_silu() {
14648        let storage = fuel_memory::from_slice_cpu(&[0.0_f32, 1.0, -1.0]);
14649        let graph = Arc::new(RwLock::new(Graph::new()));
14650        let (in_id, sig_id, silu_id) = {
14651            let mut g = graph.write().unwrap();
14652            let in_id = g.push(Node {
14653                op: Op::Const,
14654                inputs: vec![],
14655                shape: Shape::from_dims(&[3]),
14656                dtype: DType::F32,
14657            });
14658            let sig_id = g.push(Node {
14659                op: Op::Sigmoid,
14660                inputs: vec![in_id],
14661                shape: Shape::from_dims(&[3]),
14662                dtype: DType::F32,
14663            });
14664            // Silu of the sigmoid output — chains to confirm cache flow.
14665            let silu_id = g.push(Node {
14666                op: Op::Silu,
14667                inputs: vec![sig_id],
14668                shape: Shape::from_dims(&[3]),
14669                dtype: DType::F32,
14670            });
14671            g.set_target_backend(sig_id, BackendId::Cpu);
14672            g.set_target_backend(silu_id, BackendId::Cpu);
14673            (in_id, sig_id, silu_id)
14674        };
14675        let _ = sig_id;
14676        let mut inputs = StorageCache::new();
14677        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14678
14679        let (result_arc, _) = PipelinedExecutor::realize(graph, silu_id, inputs).expect("realize");
14680        let guard = result_arc.read().unwrap();
14681        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14682            let typed: &[f32] = c.as_slice().unwrap();
14683            // sigmoid(0) = 0.5; silu(0.5) = 0.5 * sigmoid(0.5) ≈ 0.3112
14684            assert!((typed[0] - 0.5 * (1.0 / (1.0 + (-0.5_f32).exp()))).abs() < 1e-6);
14685        }
14686    }
14687
14688    /// E2E: chained unary ops — Const + Sqr + Sqrt should be a noop
14689    /// for non-negative inputs. Exercises the cache reuse path.
14690    #[test]
14691    fn pipelined_realize_chained_unary_sqr_then_sqrt() {
14692        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 4.0, 9.0]);
14693        let graph = Arc::new(RwLock::new(Graph::new()));
14694        let (in_id, sqrt_id) = {
14695            let mut g = graph.write().unwrap();
14696            let in_id = g.push(Node {
14697                op: Op::Const,
14698                inputs: vec![],
14699                shape: Shape::from_dims(&[3]),
14700                dtype: DType::F32,
14701            });
14702            let sqr_id = g.push(Node {
14703                op: Op::Sqr,
14704                inputs: vec![in_id],
14705                shape: Shape::from_dims(&[3]),
14706                dtype: DType::F32,
14707            });
14708            let sqrt_id = g.push(Node {
14709                op: Op::Sqrt,
14710                inputs: vec![sqr_id],
14711                shape: Shape::from_dims(&[3]),
14712                dtype: DType::F32,
14713            });
14714            g.set_target_backend(sqr_id, BackendId::Cpu);
14715            g.set_target_backend(sqrt_id, BackendId::Cpu);
14716            (in_id, sqrt_id)
14717        };
14718        let mut inputs = StorageCache::new();
14719        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14720
14721        let (result_arc, _) = PipelinedExecutor::realize(graph, sqrt_id, inputs).expect("realize");
14722        let guard = result_arc.read().unwrap();
14723        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14724            let typed: &[f32] = c.as_slice().unwrap();
14725            // sqrt(sqr(x)) == |x| == x for non-negative inputs.
14726            assert_eq!(typed, &[1.0, 4.0, 9.0]);
14727        }
14728    }
14729
14730    /// Multi-stage pipelined: Const + Const + Add + Add (chain of
14731    /// two adds). Tests that work items are processed in topo order
14732    /// and intermediate results are cached and reused.
14733    #[test]
14734    fn pipelined_realize_chained_adds() {
14735        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
14736        let b_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
14737        let c_storage = fuel_memory::from_slice_cpu(&[100.0_f32, 200.0]);
14738
14739        let graph = Arc::new(RwLock::new(Graph::new()));
14740        let (a_id, b_id, c_id, ab_id, abc_id) = {
14741            let mut g = graph.write().unwrap();
14742            let a = g.push(Node {
14743                op: Op::Const,
14744                inputs: vec![],
14745                shape: Shape::from_dims(&[2]),
14746                dtype: DType::F32,
14747            });
14748            let b = g.push(Node {
14749                op: Op::Const,
14750                inputs: vec![],
14751                shape: Shape::from_dims(&[2]),
14752                dtype: DType::F32,
14753            });
14754            let c = g.push(Node {
14755                op: Op::Const,
14756                inputs: vec![],
14757                shape: Shape::from_dims(&[2]),
14758                dtype: DType::F32,
14759            });
14760            let ab = g.push(Node {
14761                op: Op::Add,
14762                inputs: vec![a, b],
14763                shape: Shape::from_dims(&[2]),
14764                dtype: DType::F32,
14765            });
14766            let abc = g.push(Node {
14767                op: Op::Add,
14768                inputs: vec![ab, c],
14769                shape: Shape::from_dims(&[2]),
14770                dtype: DType::F32,
14771            });
14772            g.set_target_backend(ab, BackendId::Cpu);
14773            g.set_target_backend(abc, BackendId::Cpu);
14774            (a, b, c, ab, abc)
14775        };
14776
14777        let mut inputs = StorageCache::new();
14778        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
14779        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
14780        inputs.insert(c_id, Arc::new(RwLock::new(c_storage)));
14781
14782        let (result_arc, _) = PipelinedExecutor::realize(graph, abc_id, inputs).expect("realize");
14783        // Suppress unused warning for the intermediate id.
14784        let _ = ab_id;
14785
14786        let guard = result_arc.read().unwrap();
14787        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14788            let typed: &[f32] = c.as_slice().unwrap();
14789            // (1+10) + 100 = 111;  (2+20) + 200 = 222.
14790            assert_eq!(typed, &[111.0, 222.0]);
14791        }
14792    }
14793
14794    /// E2E: triu(diagonal=0) on a 3×3 matrix.
14795    /// Input:  [1 2 3 / 4 5 6 / 7 8 9]
14796    /// Output: [1 2 3 / 0 5 6 / 0 0 9]
14797    #[test]
14798    fn pipelined_realize_triu_3x3_diag0() {
14799        let storage =
14800            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
14801        let graph = Arc::new(RwLock::new(Graph::new()));
14802        let (in_id, out_id) = {
14803            let mut g = graph.write().unwrap();
14804            let in_id = g.push(Node {
14805                op: Op::Const,
14806                inputs: vec![],
14807                shape: Shape::from_dims(&[3, 3]),
14808                dtype: DType::F32,
14809            });
14810            let out_id = g.push(Node {
14811                op: Op::Triu { diagonal: 0 },
14812                inputs: vec![in_id],
14813                shape: Shape::from_dims(&[3, 3]),
14814                dtype: DType::F32,
14815            });
14816            g.set_target_backend(out_id, BackendId::Cpu);
14817            (in_id, out_id)
14818        };
14819        let mut inputs = StorageCache::new();
14820        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14821        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
14822        let guard = result_arc.read().unwrap();
14823        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14824            panic!("expected Cpu storage");
14825        };
14826        let out: &[f32] = c.as_slice().unwrap();
14827        assert_eq!(out, &[1.0, 2.0, 3.0, 0.0, 5.0, 6.0, 0.0, 0.0, 9.0,]);
14828    }
14829
14830    /// E2E: tril(diagonal=0) on a 3×3 matrix — the canonical causal mask.
14831    /// Output: [1 0 0 / 4 5 0 / 7 8 9]
14832    #[test]
14833    fn pipelined_realize_tril_3x3_diag0_causal_mask() {
14834        let storage =
14835            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
14836        let graph = Arc::new(RwLock::new(Graph::new()));
14837        let (in_id, out_id) = {
14838            let mut g = graph.write().unwrap();
14839            let in_id = g.push(Node {
14840                op: Op::Const,
14841                inputs: vec![],
14842                shape: Shape::from_dims(&[3, 3]),
14843                dtype: DType::F32,
14844            });
14845            let out_id = g.push(Node {
14846                op: Op::Tril { diagonal: 0 },
14847                inputs: vec![in_id],
14848                shape: Shape::from_dims(&[3, 3]),
14849                dtype: DType::F32,
14850            });
14851            g.set_target_backend(out_id, BackendId::Cpu);
14852            (in_id, out_id)
14853        };
14854        let mut inputs = StorageCache::new();
14855        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14856        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
14857        let guard = result_arc.read().unwrap();
14858        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14859            panic!("expected Cpu storage");
14860        };
14861        let out: &[f32] = c.as_slice().unwrap();
14862        assert_eq!(out, &[1.0, 0.0, 0.0, 4.0, 5.0, 0.0, 7.0, 8.0, 9.0,]);
14863    }
14864
14865    /// E2E: log_softmax over a 2×3 input. Rows are [1,2,3] and [3,2,1].
14866    /// log_softmax(row) = row - max - log(sum exp(row - max)).
14867    /// Row 0: max=3, exp(-2)+exp(-1)+exp(0) = 0.135+0.368+1.0 = 1.503;
14868    ///        log(1.503) ≈ 0.4076; out = [1-3-0.4076, 2-3-0.4076, 3-3-0.4076]
14869    ///                              = [-2.4076, -1.4076, -0.4076]
14870    /// Row 1 is row 0 reversed: [-0.4076, -1.4076, -2.4076].
14871    #[test]
14872    fn pipelined_realize_log_softmax_last_dim() {
14873        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 3.0, 2.0, 1.0]);
14874        let graph = Arc::new(RwLock::new(Graph::new()));
14875        let (in_id, out_id) = {
14876            let mut g = graph.write().unwrap();
14877            let in_id = g.push(Node {
14878                op: Op::Const,
14879                inputs: vec![],
14880                shape: Shape::from_dims(&[2, 3]),
14881                dtype: DType::F32,
14882            });
14883            let out_id = g.push(Node {
14884                op: Op::LogSoftmaxLastDim,
14885                inputs: vec![in_id],
14886                shape: Shape::from_dims(&[2, 3]),
14887                dtype: DType::F32,
14888            });
14889            g.set_target_backend(out_id, BackendId::Cpu);
14890            (in_id, out_id)
14891        };
14892        let mut inputs = StorageCache::new();
14893        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14894        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
14895        let guard = result_arc.read().unwrap();
14896        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14897            panic!("expected Cpu storage");
14898        };
14899        let out: &[f32] = c.as_slice().unwrap();
14900        let expected = [
14901            -2.407_606,
14902            -1.4076059,
14903            -0.40760595_f32,
14904            -0.40760595,
14905            -1.4076059,
14906            -2.407_606,
14907        ];
14908        for (a, b) in out.iter().zip(expected.iter()) {
14909            assert!((a - b).abs() < 1e-5, "log_softmax mismatch: {a} vs {b}");
14910        }
14911        // The exp() of the output should sum to 1 per row.
14912        for row in out.chunks(3) {
14913            let sum: f32 = row.iter().map(|x| x.exp()).sum();
14914            assert!(
14915                (sum - 1.0).abs() < 1e-5,
14916                "softmax(log_softmax) row sum != 1: {sum}"
14917            );
14918        }
14919    }
14920
14921    // --- side-effect roots + destructive cleanup (9c Phase B) -----
14922
14923    /// Side-effect roots get merged into the realize walk even when
14924    /// not reachable from the user's targets. The production trigger
14925    /// is `Op::Release` (emitted by `ResidencyEvictionRule`); this
14926    /// test uses that exact shape.
14927    ///
14928    /// Graph: Const(a) + Const(b) → Add (user target); separate
14929    /// Const(c) → Release(c) (side-effect root, not reachable from
14930    /// Add). After realize_many on `[add]`, the Add should be in the
14931    /// output AND the Release should have fired (verified by the
14932    /// fact that realize succeeded — Op::Release in the walk used to
14933    /// fail compilation pre-Phase B+).
14934    #[test]
14935    fn pipelined_realize_merges_op_release_side_effect_root() {
14936        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
14937        let b = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
14938        let c = fuel_memory::from_slice_cpu(&[100.0_f32, 200.0]);
14939        let graph = Arc::new(RwLock::new(Graph::new()));
14940        let (a_id, b_id, c_id, add_id, release_id) = {
14941            let mut g = graph.write().unwrap();
14942            let a = g.push(Node {
14943                op: Op::Const,
14944                inputs: vec![],
14945                shape: Shape::from_dims(&[2]),
14946                dtype: DType::F32,
14947            });
14948            let b = g.push(Node {
14949                op: Op::Const,
14950                inputs: vec![],
14951                shape: Shape::from_dims(&[2]),
14952                dtype: DType::F32,
14953            });
14954            // c is NOT reachable from add; its Release IS marked as
14955            // a side-effect root.
14956            let c = g.push(Node {
14957                op: Op::Const,
14958                inputs: vec![],
14959                shape: Shape::from_dims(&[2]),
14960                dtype: DType::F32,
14961            });
14962            let add = g.push(Node {
14963                op: Op::Add,
14964                inputs: vec![a, b],
14965                shape: Shape::from_dims(&[2]),
14966                dtype: DType::F32,
14967            });
14968            // Production shape: Op::Release on c, marked as
14969            // side-effect root so it fires even though no graph
14970            // node reads its output.
14971            let release = g.push(Node {
14972                op: Op::Release,
14973                inputs: vec![c],
14974                shape: Shape::from_dims(&[0]),
14975                dtype: DType::F32,
14976            });
14977            g.set_target_backend(add, BackendId::Cpu);
14978            g.set_target_backend(release, BackendId::Cpu);
14979            g.add_side_effect_root(release);
14980            (a, b, c, add, release)
14981        };
14982        let mut inputs = StorageCache::new();
14983        inputs.insert(a_id, Arc::new(RwLock::new(a)));
14984        inputs.insert(b_id, Arc::new(RwLock::new(b)));
14985        let c_arc = Arc::new(RwLock::new(c));
14986        let c_arc_external = Arc::clone(&c_arc);
14987        inputs.insert(c_id, c_arc);
14988
14989        // Only `add` is requested. The Release on c is a side-effect
14990        // root that must still fire.
14991        let out = PipelinedExecutor::realize_many(graph, &[add_id], inputs).expect("realize_many");
14992        assert_eq!(out.len(), 1);
14993        let add_guard = out[0].0.read().unwrap();
14994        let fuel_memory::BackendStorage::Cpu(arr) = &add_guard.inner else {
14995            panic!()
14996        };
14997        assert_eq!(arr.as_slice::<f32>().unwrap(), &[11.0, 22.0]);
14998
14999        // The Release's destructive_input cleanup dropped the
15000        // cache's Arc to c. The only Arc to c that survives is the
15001        // external one this test holds — confirms the eviction
15002        // actually freed the cache's reference.
15003        assert_eq!(
15004            Arc::strong_count(&c_arc_external),
15005            1,
15006            "Op::Release should evict the cache's Arc to its source; \
15007             only the test's external clone should remain",
15008        );
15009        let _ = release_id;
15010    }
15011
15012    /// `compile_one` emits a `WorkItemKind::ReleaseMarker` for
15013    /// `Op::Release` with `destructive_input = Some(0)`. Verify
15014    /// the WorkItem shape via a direct compile_one call.
15015    #[test]
15016    fn compile_one_emits_release_marker_with_destructive_input() {
15017        let graph_rc = Arc::new(RwLock::new(Graph::new()));
15018        let (src_id, release_id) = {
15019            let mut g = graph_rc.write().unwrap();
15020            let src = g.push(Node {
15021                op: Op::Const,
15022                inputs: vec![],
15023                shape: Shape::from_dims(&[2]),
15024                dtype: DType::F32,
15025            });
15026            let release = g.push(Node {
15027                op: Op::Release,
15028                inputs: vec![src],
15029                shape: Shape::from_dims(&[0]),
15030                dtype: DType::F32,
15031            });
15032            g.set_target_backend(release, BackendId::Cpu);
15033            (src, release)
15034        };
15035        let g = graph_rc.read().unwrap();
15036        let bindings = crate::dispatch::global_bindings();
15037        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
15038        let item = compile_one(
15039            &g,
15040            release_id,
15041            &mut layout_cache,
15042            &bindings,
15043            &SymEnv::default(),
15044        )
15045        .expect("compile_one Op::Release");
15046        assert!(matches!(item.kind, WorkItemKind::ReleaseMarker));
15047        assert_eq!(item.destructive_input, Some(0));
15048        assert_eq!(item.inputs, vec![src_id]);
15049        assert_eq!(
15050            item.elem_count, 0,
15051            "Release output is the zero-element marker"
15052        );
15053    }
15054
15055    // --- Op::Move (executor-unification Session 1, gap 13) --------
15056
15057    /// `compile_one` emits a `WorkItemKind::Move` for `Op::Move` with
15058    /// `destructive_input = Some(0)` and a resolved transfer kernel
15059    /// (binding-table lookup at `(OpKind::Copy, [dt, dt], source
15060    /// backend)` — Move shares Op::Copy's data-movement kernel).
15061    #[test]
15062    fn compile_one_emits_move_with_destructive_input() {
15063        let graph_rc = Arc::new(RwLock::new(Graph::new()));
15064        let (src_id, move_id) = {
15065            let mut g = graph_rc.write().unwrap();
15066            let src = g.push(Node {
15067                op: Op::Const,
15068                inputs: vec![],
15069                shape: Shape::from_dims(&[2]),
15070                dtype: DType::F32,
15071            });
15072            let mv = g.push(Node {
15073                op: Op::Move {
15074                    target: DeviceLocation::Cpu,
15075                },
15076                inputs: vec![src],
15077                shape: Shape::from_dims(&[2]),
15078                dtype: DType::F32,
15079            });
15080            g.set_target_backend(mv, BackendId::Cpu);
15081            (src, mv)
15082        };
15083        let g = graph_rc.read().unwrap();
15084        let bindings = crate::dispatch::global_bindings();
15085        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
15086        let item = compile_one(
15087            &g,
15088            move_id,
15089            &mut layout_cache,
15090            &bindings,
15091            &SymEnv::default(),
15092        )
15093        .expect("compile_one Op::Move");
15094        assert!(matches!(
15095            item.kind,
15096            WorkItemKind::Move {
15097                target_location: DeviceLocation::Cpu
15098            },
15099        ));
15100        assert_eq!(item.destructive_input, Some(0), "Move destroys its source");
15101        assert_eq!(item.inputs, vec![src_id]);
15102        assert!(
15103            item.compiled.is_some(),
15104            "Move resolves a transfer kernel at (OpKind::Copy, [dt, dt], source backend)",
15105        );
15106    }
15107
15108    // --- runtime fused op (JIT-adopted Tier-2 kernel) --------------
15109
15110    /// `compile_one` resolves an `Op::Fused(fid, Runtime)` node with
15111    /// `fid.is_runtime()` from the runtime-kernel sidecar (never the
15112    /// binding table): `WorkItemKind::Kernel`, `compiled.op ==
15113    /// OpKind::RuntimeFused`, and the kernel pointer is exactly the one
15114    /// `adopt_runtime_fused` bound.
15115    #[test]
15116    fn compile_one_resolves_runtime_fused_from_the_sidecar() {
15117        fn sentinel_kernel(
15118            _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
15119            _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
15120            _layouts: &[Layout],
15121            _params: &crate::kernel::OpParams,
15122        ) -> Result<()> {
15123            Ok(())
15124        }
15125        // A region shape unique to this test (process-global sidecar; see
15126        // runtime_fused_pathfinder's tests for the collision rationale).
15127        let region = fuel_graph::jit::PatternNode::Op {
15128            op: fuel_graph::jit::OpTag::Exp,
15129            attrs: fuel_graph::jit::OpAttrs::default(),
15130            operands: vec![fuel_graph::jit::PatternNode::Op {
15131                op: fuel_graph::jit::OpTag::Sub,
15132                attrs: fuel_graph::jit::OpAttrs::default(),
15133                operands: vec![
15134                    fuel_graph::jit::PatternNode::Bind { index: 0 },
15135                    fuel_graph::jit::PatternNode::Bind { index: 1 },
15136                ],
15137            }],
15138        };
15139        let rid = crate::runtime_fused_kernels::adopt_runtime_fused(
15140            "test::compile_one::exp_sub",
15141            region,
15142            sentinel_kernel as crate::kernel::KernelRef,
15143            vec![DType::F32, DType::F32, DType::F32],
15144            BackendId::Cpu,
15145        )
15146        .expect("registrable region");
15147
15148        let graph_rc = Arc::new(RwLock::new(Graph::new()));
15149        let fused_id = {
15150            let mut g = graph_rc.write().unwrap();
15151            let s = Shape::from_dims(&[4]);
15152            let a = g.push(Node {
15153                op: Op::Const,
15154                inputs: vec![],
15155                shape: s.clone(),
15156                dtype: DType::F32,
15157            });
15158            let b = g.push(Node {
15159                op: Op::Const,
15160                inputs: vec![],
15161                shape: s.clone(),
15162                dtype: DType::F32,
15163            });
15164            let fused = g.push(Node {
15165                op: Op::Fused(
15166                    rid,
15167                    fuel_graph::registry::FusedOpParams::Runtime {
15168                        scalars: Vec::new(),
15169                    },
15170                ),
15171                inputs: vec![a, b],
15172                shape: s,
15173                dtype: DType::F32,
15174            });
15175            // The arm emitter pins the backend; mirror that here.
15176            g.set_target_backend(fused, BackendId::Cpu);
15177            fused
15178        };
15179        let g = graph_rc.read().unwrap();
15180        let bindings = crate::dispatch::global_bindings();
15181        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
15182        let item = compile_one(
15183            &g,
15184            fused_id,
15185            &mut layout_cache,
15186            &bindings,
15187            &SymEnv::default(),
15188        )
15189        .expect("compile_one runtime fused op");
15190        assert!(matches!(item.kind, WorkItemKind::Kernel));
15191        let compiled = item.compiled.expect("resolved a kernel");
15192        assert_eq!(compiled.op, fuel_ir::dispatch::OpKind::RuntimeFused);
15193        assert_eq!(compiled.backend, BackendId::Cpu);
15194        assert!(
15195            std::ptr::fn_addr_eq(compiled.kernel, sentinel_kernel as crate::kernel::KernelRef),
15196            "the kernel pointer is exactly the adopted one",
15197        );
15198        assert!(
15199            layout_cache.contains_key(&fused_id),
15200            "output layout cached for consumers"
15201        );
15202    }
15203
15204    /// The dtype belt-and-suspenders guard: an `Op::Fused(runtime)` node
15205    /// whose per-operand dtypes disagree with the adopted kernel's tuple is
15206    /// a typed error, not a silent wrong-kernel dispatch.
15207    #[test]
15208    fn compile_one_rejects_runtime_fused_dtype_mismatch() {
15209        fn noop_kernel(
15210            _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
15211            _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
15212            _layouts: &[Layout],
15213            _params: &crate::kernel::OpParams,
15214        ) -> Result<()> {
15215            Ok(())
15216        }
15217        let region = fuel_graph::jit::PatternNode::Op {
15218            op: fuel_graph::jit::OpTag::Log,
15219            attrs: fuel_graph::jit::OpAttrs::default(),
15220            operands: vec![fuel_graph::jit::PatternNode::Op {
15221                op: fuel_graph::jit::OpTag::Maximum,
15222                attrs: fuel_graph::jit::OpAttrs::default(),
15223                operands: vec![
15224                    fuel_graph::jit::PatternNode::Bind { index: 0 },
15225                    fuel_graph::jit::PatternNode::Bind { index: 1 },
15226                ],
15227            }],
15228        };
15229        // Adopted for F32 operands…
15230        let rid = crate::runtime_fused_kernels::adopt_runtime_fused(
15231            "test::compile_one::log_maximum",
15232            region,
15233            noop_kernel as crate::kernel::KernelRef,
15234            vec![DType::F32, DType::F32, DType::F32],
15235            BackendId::Cpu,
15236        )
15237        .expect("registrable region");
15238
15239        let graph_rc = Arc::new(RwLock::new(Graph::new()));
15240        let fused_id = {
15241            let mut g = graph_rc.write().unwrap();
15242            let s = Shape::from_dims(&[4]);
15243            // …but the node's operands are F64.
15244            let a = g.push(Node {
15245                op: Op::Const,
15246                inputs: vec![],
15247                shape: s.clone(),
15248                dtype: DType::F64,
15249            });
15250            let b = g.push(Node {
15251                op: Op::Const,
15252                inputs: vec![],
15253                shape: s.clone(),
15254                dtype: DType::F64,
15255            });
15256            let fused = g.push(Node {
15257                op: Op::Fused(
15258                    rid,
15259                    fuel_graph::registry::FusedOpParams::Runtime {
15260                        scalars: Vec::new(),
15261                    },
15262                ),
15263                inputs: vec![a, b],
15264                shape: s,
15265                dtype: DType::F64,
15266            });
15267            g.set_target_backend(fused, BackendId::Cpu);
15268            fused
15269        };
15270        let g = graph_rc.read().unwrap();
15271        let bindings = crate::dispatch::global_bindings();
15272        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
15273        let err = match compile_one(
15274            &g,
15275            fused_id,
15276            &mut layout_cache,
15277            &bindings,
15278            &SymEnv::default(),
15279        ) {
15280            Ok(_) => panic!("dtype mismatch must be a typed error"),
15281            Err(e) => e,
15282        };
15283        // Post-fold, the dtype tuple IS the binding key: a mismatch is the
15284        // same honest `NoBackendForOp` miss as an absent kernel — reported
15285        // with the `RuntimeFused` diagnostic op tag, never a wrong-kernel bind.
15286        assert!(
15287            matches!(
15288                err,
15289                fuel_ir::Error::NoBackendForOp {
15290                    op: fuel_ir::dispatch::OpKind::RuntimeFused,
15291                    ..
15292                }
15293            ),
15294            "a dtype mismatch is an honest binding miss: {err}",
15295        );
15296    }
15297
15298    /// A runtime fused node carrying live `Runtime { scalars }` compiles with
15299    /// `OpParams::JitScalars` — the launch channel for the kernel's trailing
15300    /// `p{i}` args. (A param-free node keeps `OpParams::None`, covered by
15301    /// `compile_one_resolves_runtime_fused_from_the_sidecar`.)
15302    #[test]
15303    fn compile_one_maps_runtime_scalars_to_jit_scalars() {
15304        fn noop_kernel(
15305            _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
15306            _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
15307            _layouts: &[Layout],
15308            _params: &crate::kernel::OpParams,
15309        ) -> Result<()> {
15310            Ok(())
15311        }
15312        // Unique slot-template region (process-global sidecar).
15313        let region = fuel_graph::jit::PatternNode::Op {
15314            op: fuel_graph::jit::OpTag::Floor,
15315            attrs: fuel_graph::jit::OpAttrs::default(),
15316            operands: vec![fuel_graph::jit::PatternNode::Op {
15317                op: fuel_graph::jit::OpTag::MulScalar,
15318                attrs: fuel_graph::jit::OpAttrs::default(), // open slot
15319                operands: vec![fuel_graph::jit::PatternNode::Bind { index: 0 }],
15320            }],
15321        };
15322        let rid = crate::runtime_fused_kernels::adopt_runtime_fused(
15323            "test::compile_one::floor_mul_scalar",
15324            region,
15325            noop_kernel as crate::kernel::KernelRef,
15326            vec![DType::F32, DType::F32],
15327            BackendId::Cpu,
15328        )
15329        .expect("slot template registrable");
15330
15331        let graph_rc = Arc::new(RwLock::new(Graph::new()));
15332        let fused_id = {
15333            let mut g = graph_rc.write().unwrap();
15334            let s = Shape::from_dims(&[4]);
15335            let x = g.push(Node {
15336                op: Op::Const,
15337                inputs: vec![],
15338                shape: s.clone(),
15339                dtype: DType::F32,
15340            });
15341            let fused = g.push(Node {
15342                op: Op::Fused(
15343                    rid,
15344                    fuel_graph::registry::FusedOpParams::Runtime {
15345                        scalars: vec![3.5, -1.25],
15346                    },
15347                ),
15348                inputs: vec![x],
15349                shape: s,
15350                dtype: DType::F32,
15351            });
15352            g.set_target_backend(fused, BackendId::Cpu);
15353            fused
15354        };
15355        let g = graph_rc.read().unwrap();
15356        let bindings = crate::dispatch::global_bindings();
15357        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
15358        let item = compile_one(
15359            &g,
15360            fused_id,
15361            &mut layout_cache,
15362            &bindings,
15363            &SymEnv::default(),
15364        )
15365        .expect("compile_one runtime fused op with scalars");
15366        let compiled = item.compiled.expect("resolved a kernel");
15367        assert!(
15368            matches!(
15369                &compiled.op_params,
15370                crate::kernel::OpParams::JitScalars { scalars } if scalars == &vec![3.5, -1.25]
15371            ),
15372            "Runtime scalars ride into OpParams::JitScalars, got {:?}",
15373            compiled.op_params,
15374        );
15375    }
15376
15377    /// Move-to-same-device is the degenerate case: per the legacy
15378    /// `GraphExecutor` contract (`Op::Copy | Op::Move` shared arm →
15379    /// `backend.copy_to`) it is a plain copy — fresh storage on the
15380    /// same device, data intact — and the source is still evicted
15381    /// afterward (destructive semantics don't depend on the devices
15382    /// differing).
15383    #[test]
15384    fn pipelined_op_move_same_device_is_plain_copy() {
15385        let src = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
15386        let graph = Arc::new(RwLock::new(Graph::new()));
15387        let (src_id, move_id) = {
15388            let mut g = graph.write().unwrap();
15389            let src = g.push(Node {
15390                op: Op::Const,
15391                inputs: vec![],
15392                shape: Shape::from_dims(&[4]),
15393                dtype: DType::F32,
15394            });
15395            let mv = g.push(Node {
15396                op: Op::Move {
15397                    target: DeviceLocation::Cpu,
15398                },
15399                inputs: vec![src],
15400                shape: Shape::from_dims(&[4]),
15401                dtype: DType::F32,
15402            });
15403            g.set_target_backend(mv, BackendId::Cpu);
15404            (src, mv)
15405        };
15406        let src_arc = Arc::new(RwLock::new(src));
15407        let src_arc_external = Arc::clone(&src_arc);
15408        let mut inputs = StorageCache::new();
15409        inputs.insert(src_id, src_arc);
15410
15411        let (out, layout) =
15412            PipelinedExecutor::realize(graph, move_id, inputs).expect("realize Op::Move");
15413        let guard = out.read().unwrap();
15414        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15415            panic!()
15416        };
15417        assert_eq!(
15418            c.as_slice::<f32>().unwrap(),
15419            &[1.0, 2.0, 3.0, 4.0],
15420            "Op::Move output should carry input's data to target",
15421        );
15422        assert!(layout.is_contiguous());
15423        drop(guard);
15424        assert!(
15425            !Arc::ptr_eq(&out, &src_arc_external),
15426            "same-device Move is a plain copy — fresh storage, not an alias",
15427        );
15428        // The realize loop's destructive_input cleanup dropped the
15429        // cache's Arc to the source; only the test's external clone
15430        // survives.
15431        assert_eq!(
15432            Arc::strong_count(&src_arc_external),
15433            1,
15434            "Op::Move should evict the cache's Arc to its source",
15435        );
15436    }
15437
15438    /// The multiple-consumer-source case: a Move must NOT strand
15439    /// another consumer of its source. `execution_plan` (via
15440    /// `derive_ordering`, keyed off `destructive_input`) pins the
15441    /// Move AFTER the sibling reader; the executor's post-Move cache
15442    /// eviction then can't break the reader. Mirrors the legacy
15443    /// `op_move_pinned_after_sibling_reader_via_derive_ordering`
15444    /// test in fuel-graph-router/tests/cross_device.rs.
15445    ///
15446    ///   a   = const [1, 2, 3, 4]
15447    ///   b   = relu(a)        (non-destructive sibling reader)
15448    ///   m   = move(a, Cpu)   (destructive — evicts a once run)
15449    ///   out = add(b, m)      → [2, 4, 6, 8]
15450    #[test]
15451    fn pipelined_op_move_multi_consumer_source_not_stranded() {
15452        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
15453        let graph = Arc::new(RwLock::new(Graph::new()));
15454        let (a_id, out_id) = {
15455            let mut g = graph.write().unwrap();
15456            let a = g.push(Node {
15457                op: Op::Const,
15458                inputs: vec![],
15459                shape: Shape::from_dims(&[4]),
15460                dtype: DType::F32,
15461            });
15462            let b = g.push(Node {
15463                op: Op::Relu,
15464                inputs: vec![a],
15465                shape: Shape::from_dims(&[4]),
15466                dtype: DType::F32,
15467            });
15468            let m = g.push(Node {
15469                op: Op::Move {
15470                    target: DeviceLocation::Cpu,
15471                },
15472                inputs: vec![a],
15473                shape: Shape::from_dims(&[4]),
15474                dtype: DType::F32,
15475            });
15476            let out = g.push(Node {
15477                op: Op::Add,
15478                inputs: vec![b, m],
15479                shape: Shape::from_dims(&[4]),
15480                dtype: DType::F32,
15481            });
15482            g.set_target_backend(b, BackendId::Cpu);
15483            g.set_target_backend(m, BackendId::Cpu);
15484            g.set_target_backend(out, BackendId::Cpu);
15485            (a, out)
15486        };
15487        let mut inputs = StorageCache::new();
15488        inputs.insert(a_id, Arc::new(RwLock::new(a)));
15489
15490        let (out, _) = PipelinedExecutor::realize(graph, out_id, inputs)
15491            .expect("realize add(relu(a), move(a))");
15492        let guard = out.read().unwrap();
15493        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15494            panic!()
15495        };
15496        assert_eq!(
15497            c.as_slice::<f32>().unwrap(),
15498            &[2.0, 4.0, 6.0, 8.0],
15499            "relu(a) must run before move(a) evicts a",
15500        );
15501    }
15502
15503    /// A Move whose source is itself in the realize target set must
15504    /// not evict it — the caller asked for the source's storage. The
15505    /// destructive cleanup's `target_set` gate covers Move exactly
15506    /// like Release.
15507    #[test]
15508    fn pipelined_op_move_source_in_target_set_not_evicted() {
15509        let a = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0]);
15510        let graph = Arc::new(RwLock::new(Graph::new()));
15511        let (a_id, move_id) = {
15512            let mut g = graph.write().unwrap();
15513            let a = g.push(Node {
15514                op: Op::Const,
15515                inputs: vec![],
15516                shape: Shape::from_dims(&[2]),
15517                dtype: DType::F32,
15518            });
15519            let mv = g.push(Node {
15520                op: Op::Move {
15521                    target: DeviceLocation::Cpu,
15522                },
15523                inputs: vec![a],
15524                shape: Shape::from_dims(&[2]),
15525                dtype: DType::F32,
15526            });
15527            g.set_target_backend(mv, BackendId::Cpu);
15528            (a, mv)
15529        };
15530        let a_arc = Arc::new(RwLock::new(a));
15531        let a_arc_external = Arc::clone(&a_arc);
15532        let mut inputs = StorageCache::new();
15533        inputs.insert(a_id, a_arc);
15534
15535        let out = PipelinedExecutor::realize_many(graph, &[move_id, a_id], inputs)
15536            .expect("realize_many [move, source]");
15537        assert_eq!(out.len(), 2);
15538        let mv_guard = out[0].0.read().unwrap();
15539        let fuel_memory::BackendStorage::Cpu(c) = &mv_guard.inner else {
15540            panic!()
15541        };
15542        assert_eq!(c.as_slice::<f32>().unwrap(), &[5.0, 6.0]);
15543        assert!(
15544            Arc::ptr_eq(&out[1].0, &a_arc_external),
15545            "requested source must survive the Move's destructive cleanup",
15546        );
15547    }
15548
15549    // --- realize_many (Phase 7.6 step 9c Phase A) ----------------
15550
15551    /// realize_many on empty targets returns an empty Vec — no graph
15552    /// walk, no panic.
15553    #[test]
15554    fn pipelined_realize_many_empty_targets() {
15555        let graph = Arc::new(RwLock::new(Graph::new()));
15556        let inputs = StorageCache::new();
15557        let out = PipelinedExecutor::realize_many(graph, &[], inputs).expect("realize_many");
15558        assert!(out.is_empty());
15559    }
15560
15561    /// realize_many with two independent target chains. Each chain's
15562    /// output is in the cache; the shared topo walk realizes both.
15563    /// Verifies parallel chain handling + return order matches input.
15564    #[test]
15565    fn pipelined_realize_many_two_independent_targets() {
15566        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
15567        let rhs = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
15568        let graph = Arc::new(RwLock::new(Graph::new()));
15569        let (lhs_id, rhs_id, add_id, mul_id) = {
15570            let mut g = graph.write().unwrap();
15571            let lhs = g.push(Node {
15572                op: Op::Const,
15573                inputs: vec![],
15574                shape: Shape::from_dims(&[3]),
15575                dtype: DType::F32,
15576            });
15577            let rhs = g.push(Node {
15578                op: Op::Const,
15579                inputs: vec![],
15580                shape: Shape::from_dims(&[3]),
15581                dtype: DType::F32,
15582            });
15583            let add = g.push(Node {
15584                op: Op::Add,
15585                inputs: vec![lhs, rhs],
15586                shape: Shape::from_dims(&[3]),
15587                dtype: DType::F32,
15588            });
15589            let mul = g.push(Node {
15590                op: Op::Mul,
15591                inputs: vec![lhs, rhs],
15592                shape: Shape::from_dims(&[3]),
15593                dtype: DType::F32,
15594            });
15595            g.set_target_backend(add, BackendId::Cpu);
15596            g.set_target_backend(mul, BackendId::Cpu);
15597            (lhs, rhs, add, mul)
15598        };
15599        let mut inputs = StorageCache::new();
15600        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs)));
15601        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs)));
15602
15603        // Pass mul first to confirm return order matches targets order
15604        // (not graph order — graph order would put add first).
15605        let out = PipelinedExecutor::realize_many(graph, &[mul_id, add_id], inputs)
15606            .expect("realize_many");
15607        assert_eq!(out.len(), 2);
15608
15609        let mul_guard = out[0].0.read().unwrap();
15610        let fuel_memory::BackendStorage::Cpu(c) = &mul_guard.inner else {
15611            panic!()
15612        };
15613        assert_eq!(c.as_slice::<f32>().unwrap(), &[10.0, 40.0, 90.0]);
15614
15615        let add_guard = out[1].0.read().unwrap();
15616        let fuel_memory::BackendStorage::Cpu(c) = &add_guard.inner else {
15617            panic!()
15618        };
15619        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 22.0, 33.0]);
15620    }
15621
15622    /// realize_many with the same NodeId twice — caller asking for
15623    /// the same output twice. Both outputs are the same Arc (cheap).
15624    #[test]
15625    fn pipelined_realize_many_duplicate_target_returns_same_arc() {
15626        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
15627        let graph = Arc::new(RwLock::new(Graph::new()));
15628        let (in_id, neg_id) = {
15629            let mut g = graph.write().unwrap();
15630            let in_id = g.push(Node {
15631                op: Op::Const,
15632                inputs: vec![],
15633                shape: Shape::from_dims(&[3]),
15634                dtype: DType::F32,
15635            });
15636            let neg = g.push(Node {
15637                op: Op::Neg,
15638                inputs: vec![in_id],
15639                shape: Shape::from_dims(&[3]),
15640                dtype: DType::F32,
15641            });
15642            g.set_target_backend(neg, BackendId::Cpu);
15643            (in_id, neg)
15644        };
15645        let mut inputs = StorageCache::new();
15646        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
15647
15648        let out = PipelinedExecutor::realize_many(graph, &[neg_id, neg_id], inputs)
15649            .expect("realize_many");
15650        assert_eq!(out.len(), 2);
15651        assert!(
15652            Arc::ptr_eq(&out[0].0, &out[1].0),
15653            "duplicate target should share the same storage Arc",
15654        );
15655    }
15656
15657    /// realize_many with shared upstream nodes evaluates the shared
15658    /// chunk exactly once. Two targets `f = a + b` and `g = (a + b) * a`
15659    /// — `a + b` is computed once.
15660    #[test]
15661    fn pipelined_realize_many_shared_subgraph_evaluates_once() {
15662        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
15663        let b_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
15664        let graph = Arc::new(RwLock::new(Graph::new()));
15665        let (a_id, b_id, add_id, mul_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(&[3]),
15671                dtype: DType::F32,
15672            });
15673            let b = g.push(Node {
15674                op: Op::Const,
15675                inputs: vec![],
15676                shape: Shape::from_dims(&[3]),
15677                dtype: DType::F32,
15678            });
15679            let add = g.push(Node {
15680                op: Op::Add,
15681                inputs: vec![a, b],
15682                shape: Shape::from_dims(&[3]),
15683                dtype: DType::F32,
15684            });
15685            let mul = g.push(Node {
15686                op: Op::Mul,
15687                inputs: vec![add, a],
15688                shape: Shape::from_dims(&[3]),
15689                dtype: DType::F32,
15690            });
15691            g.set_target_backend(add, BackendId::Cpu);
15692            g.set_target_backend(mul, BackendId::Cpu);
15693            (a, b, add, mul)
15694        };
15695        let mut inputs = StorageCache::new();
15696        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
15697        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
15698
15699        let out = PipelinedExecutor::realize_many(graph, &[add_id, mul_id], inputs)
15700            .expect("realize_many");
15701        assert_eq!(out.len(), 2);
15702
15703        let add_guard = out[0].0.read().unwrap();
15704        let fuel_memory::BackendStorage::Cpu(c) = &add_guard.inner else {
15705            panic!()
15706        };
15707        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 22.0, 33.0]);
15708
15709        let mul_guard = out[1].0.read().unwrap();
15710        let fuel_memory::BackendStorage::Cpu(c) = &mul_guard.inner else {
15711            panic!()
15712        };
15713        // (a + b) * a = [11*1, 22*2, 33*3] = [11, 44, 99].
15714        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 44.0, 99.0]);
15715    }
15716
15717    /// E2E: masked_fill with -inf — the attention masking pattern.
15718    /// x = [1, 2, 3, 4]; mask = [0, 1, 0, 1]; value = -1000.
15719    /// out = [1, -1000, 3, -1000].
15720    #[test]
15721    fn pipelined_realize_masked_fill_attention_pattern() {
15722        let x_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
15723        let mut mask_storage = fuel_memory::from_slice_cpu(&[0u8, 1, 0, 1]);
15724        mask_storage.dtype = DType::Bool; // GAP-168(c): a Bool mask, not U8 bytes
15725        let graph = Arc::new(RwLock::new(Graph::new()));
15726        let (x_id, mask_id, out_id) = {
15727            let mut g = graph.write().unwrap();
15728            let x = g.push(Node {
15729                op: Op::Const,
15730                inputs: vec![],
15731                shape: Shape::from_dims(&[4]),
15732                dtype: DType::F32,
15733            });
15734            let mask = g.push(Node {
15735                op: Op::Const,
15736                inputs: vec![],
15737                shape: Shape::from_dims(&[4]),
15738                dtype: DType::Bool,
15739            });
15740            let out = g.push(Node {
15741                op: Op::MaskedFill {
15742                    value: fuel_ir::Scalar::F32(-1000.0),
15743                },
15744                inputs: vec![x, mask],
15745                shape: Shape::from_dims(&[4]),
15746                dtype: DType::F32,
15747            });
15748            g.set_target_backend(out, BackendId::Cpu);
15749            (x, mask, out)
15750        };
15751        let mut inputs = StorageCache::new();
15752        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
15753        inputs.insert(mask_id, Arc::new(RwLock::new(mask_storage)));
15754        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
15755        let guard = result_arc.read().unwrap();
15756        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15757            panic!("expected Cpu storage");
15758        };
15759        let out: &[f32] = c.as_slice().unwrap();
15760        assert_eq!(out, &[1.0, -1000.0, 3.0, -1000.0]);
15761    }
15762
15763    // ---- WriteSlice (Phase 7.6 step 9c E.3.2) -------------------------------
15764
15765    /// E2E: pipelined realize of `Op::WriteSlice` writing a [1, 3, 2]
15766    /// source slab into a [4, 3, 2] destination at axis-0 row 2 — the
15767    /// canonical KV-cache append shape.
15768    #[test]
15769    fn pipelined_realize_write_slice_kv_cache_append() {
15770        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 24]);
15771        let src_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
15772        let graph = Arc::new(RwLock::new(Graph::new()));
15773        let (dest_id, src_id, ws_id) = {
15774            let mut g = graph.write().unwrap();
15775            let dest = g.push(Node {
15776                op: Op::Const,
15777                inputs: vec![],
15778                shape: Shape::from_dims(&[4, 3, 2]),
15779                dtype: DType::F32,
15780            });
15781            let src = g.push(Node {
15782                op: Op::Const,
15783                inputs: vec![],
15784                shape: Shape::from_dims(&[1, 3, 2]),
15785                dtype: DType::F32,
15786            });
15787            let ws = g.push(Node {
15788                op: Op::WriteSlice {
15789                    ranges: vec![(2, 3), (0, 3), (0, 2)],
15790                    dyn_offset: None,
15791                },
15792                inputs: vec![dest, src],
15793                shape: Shape::from_dims(&[4, 3, 2]), // adopts dest shape
15794                dtype: DType::F32,
15795            });
15796            g.set_target_backend(ws, BackendId::Cpu);
15797            (dest, src, ws)
15798        };
15799        let mut inputs = StorageCache::new();
15800        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
15801        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
15802        let (result_arc, _) = PipelinedExecutor::realize(graph, ws_id, inputs).expect("realize");
15803        let guard = result_arc.read().unwrap();
15804        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15805            panic!("expected Cpu storage");
15806        };
15807        let out: &[f32] = c.as_slice().unwrap();
15808        let expected = [
15809            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,
15810            6.0, // row 2 = source
15811            0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
15812        ];
15813        assert_eq!(out, &expected);
15814    }
15815
15816    /// E2E: pipelined realize of `Op::WriteSlice` adopts the
15817    /// destination's Storage Arc as the output slot (in-place
15818    /// alias) — the resulting Arc points to the SAME bytes the
15819    /// destination was constructed from.
15820    #[test]
15821    fn pipelined_realize_write_slice_aliases_dest_storage() {
15822        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
15823        let src_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
15824        let graph = Arc::new(RwLock::new(Graph::new()));
15825        let (dest_id, src_id, ws_id, dest_arc_external) = {
15826            let mut g = graph.write().unwrap();
15827            let dest = g.push(Node {
15828                op: Op::Const,
15829                inputs: vec![],
15830                shape: Shape::from_dims(&[3, 2]),
15831                dtype: DType::F32,
15832            });
15833            let src = g.push(Node {
15834                op: Op::Const,
15835                inputs: vec![],
15836                shape: Shape::from_dims(&[1, 2]),
15837                dtype: DType::F32,
15838            });
15839            let ws = g.push(Node {
15840                op: Op::WriteSlice {
15841                    ranges: vec![(1, 2), (0, 2)],
15842                    dyn_offset: None,
15843                },
15844                inputs: vec![dest, src],
15845                shape: Shape::from_dims(&[3, 2]),
15846                dtype: DType::F32,
15847            });
15848            g.set_target_backend(ws, BackendId::Cpu);
15849            let arc = Arc::new(RwLock::new(dest_storage));
15850            (dest, src, ws, arc)
15851        };
15852        let mut inputs = StorageCache::new();
15853        inputs.insert(dest_id, Arc::clone(&dest_arc_external));
15854        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
15855        let (result_arc, _) = PipelinedExecutor::realize(graph, ws_id, inputs).expect("realize");
15856        // Bytes were written into the same Arc the caller held —
15857        // the WriteSlice op aliases dest's Storage Arc, not allocates
15858        // a fresh buffer.
15859        assert!(
15860            Arc::ptr_eq(&result_arc, &dest_arc_external),
15861            "WriteSlice output Arc must be the same Arc as the destination's"
15862        );
15863        let guard = dest_arc_external.read().unwrap();
15864        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15865            panic!("expected Cpu storage");
15866        };
15867        let out: &[f32] = c.as_slice().unwrap();
15868        assert_eq!(out, &[0.0, 0.0, 10.0, 20.0, 0.0, 0.0]);
15869    }
15870
15871    // ---- WriteSlice dynamic offset (Phase D symbolic extents) ---------------
15872
15873    /// E2E: pipelined realize of `Op::WriteSlice` with a runtime start
15874    /// offset (`dyn_offset`) resolved through a per-pass `SymEnv`. The
15875    /// width-2 source slab lands at the bound offset (3), not the static
15876    /// `ranges[0].0` placeholder (0) — the persistent-decode KV-cache
15877    /// write at a per-token `cached_len`.
15878    #[test]
15879    fn pipelined_realize_write_slice_dynamic_offset() {
15880        use fuel_ir::{DynScalar, SymId};
15881        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
15882        let src_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0]);
15883        let graph = Arc::new(RwLock::new(Graph::new()));
15884        let sym = SymId(0);
15885        let (dest_id, src_id, ws_id) = {
15886            let mut g = graph.write().unwrap();
15887            let dest = g.push(Node {
15888                op: Op::Const,
15889                inputs: vec![],
15890                shape: Shape::from_dims(&[6]),
15891                dtype: DType::F32,
15892            });
15893            let src = g.push(Node {
15894                op: Op::Const,
15895                inputs: vec![],
15896                shape: Shape::from_dims(&[2]),
15897                dtype: DType::F32,
15898            });
15899            let ws = g.push(Node {
15900                // ranges[0] = (0, 2): the start is a placeholder (ignored —
15901                // overridden by dyn_offset); only the width (2) is read.
15902                op: Op::WriteSlice {
15903                    ranges: vec![(0, 2)],
15904                    dyn_offset: Some((0, DynScalar::Sym(sym))),
15905                },
15906                inputs: vec![dest, src],
15907                shape: Shape::from_dims(&[6]),
15908                dtype: DType::F32,
15909            });
15910            g.set_target_backend(ws, BackendId::Cpu);
15911            (dest, src, ws)
15912        };
15913        let mut inputs = StorageCache::new();
15914        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
15915        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
15916
15917        // Bind cached_len = 3: the slab must land at indices [3, 4].
15918        let mut env = SymEnv::new();
15919        env.bind(sym, 3).unwrap();
15920
15921        let (result_arc, _) = PipelinedExecutor::realize_with_env(graph, ws_id, inputs, env)
15922            .expect("realize_with_env");
15923        let guard = result_arc.read().unwrap();
15924        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15925            panic!("expected Cpu storage");
15926        };
15927        let out: &[f32] = c.as_slice().unwrap();
15928        assert_eq!(
15929            out,
15930            &[0.0, 0.0, 0.0, 7.0, 8.0, 0.0],
15931            "slab must land at the SymEnv-bound offset 3, not the static placeholder 0",
15932        );
15933    }
15934
15935    /// Increment 2a — the data-determined bind seam. After
15936    /// `Op::NonZeroIndices` realizes, the executor reads its runtime count
15937    /// from bundle slot 1 and PUBLISHES it into the produced `SymEnv` under
15938    /// `count_sym`. This is the first op to bind a *data-determined* symbol
15939    /// mid-realize (all prior binds are host-known before realize) — the
15940    /// keystone capability for SSM decode / MoE sparsity / MLA KV.
15941    #[test]
15942    fn pipelined_realize_nonzero_indices_publishes_count() {
15943        use fuel_ir::SymId;
15944        use fuel_ir::storage::{OutputViewSpec, compose_bundle};
15945        // flat [0,1,0,1,1,0] → 3 nonzeros at 1,3,4; capacity 6.
15946        let x_storage = fuel_memory::from_slice_cpu(&[0.0_f32, 1.0, 0.0, 1.0, 1.0, 0.0]);
15947        let graph = Arc::new(RwLock::new(Graph::new()));
15948        let count_sym = SymId(0);
15949        let (x_id, nzi_id) = {
15950            let mut g = graph.write().unwrap();
15951            let x = g.push(Node {
15952                op: Op::Const,
15953                inputs: vec![],
15954                shape: Shape::from_dims(&[2, 3]),
15955                dtype: DType::F32,
15956            });
15957            let capacity = 6usize;
15958            let idx_shape = Shape::from_dims(&[capacity]);
15959            let cnt_shape = Shape::from_dims(&[1]);
15960            let specs = vec![
15961                OutputViewSpec {
15962                    dtype: DType::U32,
15963                    shape: idx_shape.clone(),
15964                    layout: Layout::contiguous(idx_shape.clone()),
15965                    name: Some("indices"),
15966                },
15967                OutputViewSpec {
15968                    dtype: DType::U32,
15969                    shape: cnt_shape.clone(),
15970                    layout: Layout::contiguous(cnt_shape),
15971                    name: Some("count"),
15972                },
15973            ];
15974            let (_bytes, views) = compose_bundle(&specs).unwrap();
15975            let nzi = g.push(Node {
15976                op: Op::NonZeroIndices { count_sym },
15977                inputs: vec![x],
15978                shape: idx_shape,
15979                dtype: DType::U32,
15980            });
15981            g.set_output_views(nzi, Arc::from(views.into_boxed_slice()))
15982                .unwrap();
15983            g.set_target_backend(nzi, BackendId::Cpu);
15984            (x, nzi)
15985        };
15986        let mut inputs = StorageCache::new();
15987        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
15988
15989        let (_arc, _layout, produced) =
15990            PipelinedExecutor::realize_with_env_producing(graph, nzi_id, inputs, SymEnv::new())
15991                .expect("realize_with_env_producing");
15992
15993        assert_eq!(
15994            produced.get(count_sym),
15995            Some(3),
15996            "the executor must publish the data-determined nonzero count into the SymEnv",
15997        );
15998    }
15999
16000    /// A `dyn_offset` whose symbol is unbound in the `SymEnv` surfaces a
16001    /// typed error at realize (never a panic).
16002    #[test]
16003    fn pipelined_realize_write_slice_dynamic_offset_unbound_errors() {
16004        use fuel_ir::{DynScalar, SymId};
16005        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
16006        let src_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0]);
16007        let graph = Arc::new(RwLock::new(Graph::new()));
16008        let (dest_id, src_id, ws_id) = {
16009            let mut g = graph.write().unwrap();
16010            let dest = g.push(Node {
16011                op: Op::Const,
16012                inputs: vec![],
16013                shape: Shape::from_dims(&[6]),
16014                dtype: DType::F32,
16015            });
16016            let src = g.push(Node {
16017                op: Op::Const,
16018                inputs: vec![],
16019                shape: Shape::from_dims(&[2]),
16020                dtype: DType::F32,
16021            });
16022            let ws = g.push(Node {
16023                op: Op::WriteSlice {
16024                    ranges: vec![(0, 2)],
16025                    dyn_offset: Some((0, DynScalar::Sym(SymId(0)))),
16026                },
16027                inputs: vec![dest, src],
16028                shape: Shape::from_dims(&[6]),
16029                dtype: DType::F32,
16030            });
16031            g.set_target_backend(ws, BackendId::Cpu);
16032            (dest, src, ws)
16033        };
16034        let mut inputs = StorageCache::new();
16035        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
16036        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
16037        // Empty env — the symbol is unbound.
16038        let result = PipelinedExecutor::realize_with_env(graph, ws_id, inputs, SymEnv::new());
16039        assert!(
16040            result.is_err(),
16041            "unbound dyn_offset symbol must surface a typed error, not a panic",
16042        );
16043    }
16044
16045    /// A runtime offset whose resolved slab runs past the destination
16046    /// capacity errors at realize (never an out-of-bounds write).
16047    #[test]
16048    fn pipelined_realize_write_slice_dynamic_offset_out_of_capacity_errors() {
16049        use fuel_ir::{DynScalar, SymId};
16050        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
16051        let src_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0]);
16052        let graph = Arc::new(RwLock::new(Graph::new()));
16053        let sym = SymId(0);
16054        let (dest_id, src_id, ws_id) = {
16055            let mut g = graph.write().unwrap();
16056            let dest = g.push(Node {
16057                op: Op::Const,
16058                inputs: vec![],
16059                shape: Shape::from_dims(&[6]),
16060                dtype: DType::F32,
16061            });
16062            let src = g.push(Node {
16063                op: Op::Const,
16064                inputs: vec![],
16065                shape: Shape::from_dims(&[2]),
16066                dtype: DType::F32,
16067            });
16068            let ws = g.push(Node {
16069                op: Op::WriteSlice {
16070                    ranges: vec![(0, 2)],
16071                    dyn_offset: Some((0, DynScalar::Sym(sym))),
16072                },
16073                inputs: vec![dest, src],
16074                shape: Shape::from_dims(&[6]),
16075                dtype: DType::F32,
16076            });
16077            g.set_target_backend(ws, BackendId::Cpu);
16078            (dest, src, ws)
16079        };
16080        let mut inputs = StorageCache::new();
16081        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
16082        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
16083        // offset 5 + width 2 = 7 > capacity 6.
16084        let mut env = SymEnv::new();
16085        env.bind(sym, 5).unwrap();
16086        let result = PipelinedExecutor::realize_with_env(graph, ws_id, inputs, env);
16087        assert!(
16088            result.is_err(),
16089            "resolved slab past destination capacity must surface a typed error",
16090        );
16091    }
16092
16093    /// Regression for the PipelinedExecutor ordering-integration session.
16094    ///
16095    /// Graph: `x = Const`, `step_x = Step(x)`, `y = SigmoidInplace(x)`.
16096    /// `Step` and `SigmoidInplace` are both readers of `x`; `Step` is
16097    /// non-destructive, `SigmoidInplace` mutates `x`'s storage. The
16098    /// correct semantic is for `Step` to read PRE-mutation bytes.
16099    ///
16100    /// Pre-this-session (raw `topo_order_multi`): the two are siblings
16101    /// in topo order and the tie-break is unspecified — `SigmoidInplace`
16102    /// could run first, making `step_x` see post-sigmoid bytes
16103    /// (`[1, 1, 1, 1]` because every sigmoid output is positive).
16104    ///
16105    /// Post-this-session: `execution_plan` consults `derive_ordering`,
16106    /// which pins `SigmoidInplace` AFTER every other reader of `x`.
16107    /// `step_x` deterministically sees `x` and is `[1, 0, 1, 0]`.
16108    #[test]
16109    fn pipelined_inplace_with_multiple_readers_orders_correctly() {
16110        use fuel_ir::Shape;
16111        let data = [1.0_f32, -2.0, 3.0, -4.0];
16112        let src_storage = fuel_memory::from_slice_cpu(&data);
16113
16114        let graph = Arc::new(RwLock::new(Graph::new()));
16115        let (x_id, step_id, sig_id) = {
16116            let mut g = graph.write().unwrap();
16117            let x = g.push(Node {
16118                op: Op::Const,
16119                inputs: vec![],
16120                shape: Shape::from_dims(&[4]),
16121                dtype: DType::F32,
16122            });
16123            let step = g.push(Node {
16124                op: Op::Step,
16125                inputs: vec![x],
16126                shape: Shape::from_dims(&[4]),
16127                dtype: DType::F32,
16128            });
16129            let sig = g.push(Node {
16130                op: Op::SigmoidInplace,
16131                inputs: vec![x],
16132                shape: Shape::from_dims(&[4]),
16133                dtype: DType::F32,
16134            });
16135            g.set_target_backend(step, BackendId::Cpu);
16136            g.set_target_backend(sig, BackendId::Cpu);
16137            (x, step, sig)
16138        };
16139
16140        let mut cache = StorageCache::new();
16141        cache.insert(x_id, Arc::new(RwLock::new(src_storage)));
16142
16143        let results = PipelinedExecutor::realize_many(graph, &[step_id, sig_id], cache)
16144            .expect("realize_many");
16145
16146        // step_x must reflect pre-mutation x: sign of [1, -2, 3, -4] →
16147        // [1, 0, 1, 0]. If the executor ran SigmoidInplace first, step
16148        // would see all-positive sigmoid outputs and produce [1, 1, 1, 1].
16149        let step_guard = results[0].0.read().unwrap();
16150        let fuel_memory::BackendStorage::Cpu(c) = &step_guard.inner else {
16151            panic!("expected Cpu storage for step output");
16152        };
16153        let step_out: &[f32] = c.as_slice().expect("f32 cast");
16154        assert_eq!(
16155            step_out,
16156            &[1.0_f32, 0.0, 1.0, 0.0],
16157            "Step must run before SigmoidInplace; got post-mutation bytes"
16158        );
16159        drop(step_guard);
16160
16161        // SigmoidInplace's output Arc IS the mutated cache entry — bytes
16162        // approximate sigmoid([1, -2, 3, -4]).
16163        let sig_guard = results[1].0.read().unwrap();
16164        let fuel_memory::BackendStorage::Cpu(c) = &sig_guard.inner else {
16165            panic!("expected Cpu storage for sigmoid output");
16166        };
16167        let sig_out: &[f32] = c.as_slice().expect("f32 cast");
16168        let sig_ref = [
16169            1.0_f32 / (1.0 + (-1.0_f32).exp()),
16170            1.0_f32 / (1.0 + (2.0_f32).exp()),
16171            1.0_f32 / (1.0 + (-3.0_f32).exp()),
16172            1.0_f32 / (1.0 + (4.0_f32).exp()),
16173        ];
16174        for (got, want) in sig_out.iter().zip(sig_ref.iter()) {
16175            assert!((got - want).abs() < 1e-6, "sigmoid: got {got}, want {want}");
16176        }
16177    }
16178
16179    /// Regression for the PipelinedExecutor ordering-integration session.
16180    ///
16181    /// Canonical residual-connection pattern:
16182    ///   `x = Const`, `y = ReluInplace(x)`, `z = Add(y, x)`.
16183    ///
16184    /// Pre-this-session: `derive_ordering` was never run, so the cycle
16185    /// (Add must precede ReluInplace per ordering edge; Add must follow
16186    /// ReluInplace per data-flow edge through y) was undetected. The
16187    /// executor produced `z = relu(x) + relu(x) = [2, 0, 6, 0]` —
16188    /// silently wrong.
16189    ///
16190    /// Post-this-session: `insert_safety_copies` runs before
16191    /// `execution_plan`, inserts `Op::Copy(x) → x_safe`, rewires Add's
16192    /// `x` input to `x_safe`. Result: `z = relu(x) + x = [2, -2, 6, -4]`.
16193    #[test]
16194    fn pipelined_residual_connection_inserts_safety_copy() {
16195        use fuel_ir::Shape;
16196        let data = [1.0_f32, -2.0, 3.0, -4.0];
16197        let src_storage = fuel_memory::from_slice_cpu(&data);
16198
16199        let graph = Arc::new(RwLock::new(Graph::new()));
16200        let (x_id, _y_id, z_id) = {
16201            let mut g = graph.write().unwrap();
16202            let x = g.push(Node {
16203                op: Op::Const,
16204                inputs: vec![],
16205                shape: Shape::from_dims(&[4]),
16206                dtype: DType::F32,
16207            });
16208            let y = g.push(Node {
16209                op: Op::ReluInplace,
16210                inputs: vec![x],
16211                shape: Shape::from_dims(&[4]),
16212                dtype: DType::F32,
16213            });
16214            let z = g.push(Node {
16215                op: Op::Add,
16216                inputs: vec![y, x],
16217                shape: Shape::from_dims(&[4]),
16218                dtype: DType::F32,
16219            });
16220            g.set_target_backend(y, BackendId::Cpu);
16221            g.set_target_backend(z, BackendId::Cpu);
16222            (x, y, z)
16223        };
16224
16225        let mut cache = StorageCache::new();
16226        cache.insert(x_id, Arc::new(RwLock::new(src_storage)));
16227
16228        let (result_arc, _) = PipelinedExecutor::realize(graph, z_id, cache)
16229            .expect("realize z — insert_safety_copies must break the cycle");
16230
16231        let guard = result_arc.read().unwrap();
16232        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16233            panic!("expected Cpu storage");
16234        };
16235        let got: &[f32] = c.as_slice().expect("f32 cast");
16236        assert_eq!(
16237            got,
16238            &[2.0_f32, -2.0, 6.0, -4.0],
16239            "Add must read pre-mutation x via the inserted safety copy"
16240        );
16241    }
16242
16243    // ------------------------------------------------------------------
16244    // Item 3 end-to-end: SelectiveScan through the bundled-output
16245    // PipelinedExecutor path. The producer allocates bundled
16246    // (y_bytes + last_state_bytes), the kernel writes both slots,
16247    // and the bundled-tuple builder returns each via Op::View.
16248    // ------------------------------------------------------------------
16249
16250    fn cpu_const_f32(
16251        graph: &Arc<RwLock<Graph>>,
16252        cache: &mut StorageCache,
16253        data: &[f32],
16254        dims: &[usize],
16255    ) -> NodeId {
16256        let id = {
16257            let mut g = graph.write().unwrap();
16258            g.push(Node {
16259                op: Op::Const,
16260                inputs: vec![],
16261                shape: Shape::from_dims(dims),
16262                dtype: DType::F32,
16263            })
16264        };
16265        cache.insert(id, Arc::new(RwLock::new(fuel_memory::from_slice_cpu(data))));
16266        id
16267    }
16268
16269    /// `selective_scan_bundled` realizes both `y` and `last_state` in
16270    /// a single `realize_many` pass; the Views project the same
16271    /// producer's bundled Storage Arc and the numerics match the
16272    /// hand-computed single-step kernel test (b=1,s=1,d=1,k=1).
16273    #[test]
16274    fn pipelined_realize_selective_scan_bundled_produces_y_and_last_state() {
16275        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16276        let mut cache = StorageCache::new();
16277
16278        let u_id = cpu_const_f32(&graph, &mut cache, &[3.0], &[1, 1, 1]);
16279        let delta_id = cpu_const_f32(&graph, &mut cache, &[1.0], &[1, 1, 1]);
16280        let a_id = cpu_const_f32(&graph, &mut cache, &[-1.0], &[1, 1]);
16281        let b_id = cpu_const_f32(&graph, &mut cache, &[2.0], &[1, 1, 1]);
16282        let c_id = cpu_const_f32(&graph, &mut cache, &[0.5], &[1, 1, 1]);
16283
16284        let (y_id, last_state_id) = {
16285            let u_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), u_id);
16286            let delta_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), delta_id);
16287            let a_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), a_id);
16288            let b_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), b_id);
16289            let c_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), c_id);
16290            let (y, last_state) = u_t
16291                .selective_scan_bundled(&delta_t, &a_t, &b_t, &c_t, /* delta_softplus */ false)
16292                .expect("selective_scan_bundled");
16293            (y.id(), last_state.id())
16294        };
16295        // Set target_backend on the producer (View nodes inherit it).
16296        {
16297            let mut g = graph.write().unwrap();
16298            let producer = g.node(y_id).inputs[0];
16299            g.set_target_backend(producer, BackendId::Cpu);
16300        }
16301
16302        let outputs =
16303            PipelinedExecutor::realize_many(Arc::clone(&graph), &[y_id, last_state_id], cache)
16304                .expect("realize_many");
16305        let (y_arc, y_layout) = outputs[0].clone();
16306        let (last_state_arc, last_state_layout) = outputs[1].clone();
16307
16308        // Both Views project the same bundled producer Storage Arc.
16309        assert!(
16310            Arc::ptr_eq(&y_arc, &last_state_arc),
16311            "y and last_state Views project the SAME bundled producer Storage",
16312        );
16313
16314        // Hand-computed numerics (single-step recurrence):
16315        // h[0,0,0] = exp(1.0 * -1.0) * 0 + 1.0 * 2.0 * 3.0 = 6.0
16316        // y[0,0,0] = h * c = 6.0 * 0.5 = 3.0
16317        // last_state[0,0,0] = h = 6.0
16318        let guard = y_arc.read().unwrap();
16319        let fuel_memory::BackendStorage::Cpu(c_bytes) = &guard.inner else {
16320            panic!("expected Cpu storage");
16321        };
16322        let typed: &[f32] = c_bytes.as_slice().expect("f32 cast");
16323        assert_eq!(y_layout.start_offset(), 0);
16324        let y_value = typed[y_layout.start_offset()];
16325        assert!((y_value - 3.0).abs() < 1e-5, "y expected 3.0 got {y_value}");
16326        assert_eq!(
16327            last_state_layout.start_offset(),
16328            1,
16329            "slot 1 byte_offset 4 / sizeof(f32) = 1",
16330        );
16331        let ls_value = typed[last_state_layout.start_offset()];
16332        assert!(
16333            (ls_value - 6.0).abs() < 1e-5,
16334            "last_state expected 6.0 got {ls_value}"
16335        );
16336    }
16337
16338    // ---- Ordering-defect repros (MLA decode multi-round WriteSlice) -----
16339
16340    /// DIAGNOSTIC (not a repro by itself): a plain single-hop view chain
16341    /// `S = Slice(X); K = Relu(S)` competing with a SECOND destructive
16342    /// WriteSlice on `X` (`Y = WriteSlice(X, ...)`) within one
16343    /// `realize_many` call. `collect_alias_set` adds `S` to `X`'s alias
16344    /// set (Slice IS `is_view_op`), so `derive_ordering` pins `Y` after
16345    /// `S`'s reader `K` directly. This form is expected to STAY GREEN —
16346    /// recorded here as the control that isolates the Reshape-specific
16347    /// gap exercised by the next test.
16348    #[test]
16349    fn pipelined_write_slice_round2_plain_slice_reader_not_stranded() {
16350        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16351        let mut cache = StorageCache::new();
16352
16353        let b_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16354        let src1_id = cpu_const_f32(&graph, &mut cache, &[1.0, 2.0], &[2]);
16355        let src2_id = cpu_const_f32(&graph, &mut cache, &[99.0, 98.0], &[2]);
16356
16357        let (k_id, y_id) = {
16358            let mut g = graph.write().unwrap();
16359            let x_id = g.push(Node {
16360                op: Op::WriteSlice {
16361                    ranges: vec![(0, 2)],
16362                    dyn_offset: None,
16363                },
16364                inputs: vec![b_id, src1_id],
16365                shape: Shape::from_dims(&[4]),
16366                dtype: DType::F32,
16367            });
16368            let s_id = g.push(Node {
16369                op: Op::Slice {
16370                    dim: 0,
16371                    start: 0,
16372                    len: 2,
16373                },
16374                inputs: vec![x_id],
16375                shape: Shape::from_dims(&[2]),
16376                dtype: DType::F32,
16377            });
16378            let k_id = g.push(Node {
16379                op: Op::Relu,
16380                inputs: vec![s_id],
16381                shape: Shape::from_dims(&[2]),
16382                dtype: DType::F32,
16383            });
16384            // Round 2 OVERLAPS round 1's [0,2) range so a wrong-order
16385            // execution would be numerically visible in K's output.
16386            let y_id = g.push(Node {
16387                op: Op::WriteSlice {
16388                    ranges: vec![(0, 2)],
16389                    dyn_offset: None,
16390                },
16391                inputs: vec![x_id, src2_id],
16392                shape: Shape::from_dims(&[4]),
16393                dtype: DType::F32,
16394            });
16395            g.set_target_backend(x_id, BackendId::Cpu);
16396            g.set_target_backend(k_id, BackendId::Cpu);
16397            g.set_target_backend(y_id, BackendId::Cpu);
16398            (k_id, y_id)
16399        };
16400
16401        let plan = fuel_graph::opt::execution_plan(&graph.read().unwrap(), &[k_id, y_id]);
16402        eprintln!("[diagnostic plain-slice] execution_plan = {:?}", plan,);
16403
16404        let outputs = PipelinedExecutor::realize_many(Arc::clone(&graph), &[k_id, y_id], cache)
16405            .expect("realize_many: plain slice reader must not error");
16406        let (k_arc, _) = &outputs[0];
16407        let guard = k_arc.read().unwrap();
16408        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16409            panic!("expected Cpu storage");
16410        };
16411        let out: &[f32] = c.as_slice().unwrap();
16412        assert_eq!(
16413            out,
16414            &[1.0, 2.0],
16415            "K = relu(slice(X,0,2)) must read PRE-round-2 bytes; got {:?}",
16416            out,
16417        );
16418    }
16419
16420    /// CRITICAL SUSPECT #2 repro: `Op::Reshape`/`Op::Contiguize` compile
16421    /// to `WorkItemKind::ContiguizeOf`, which zero-copy ADOPTS the
16422    /// input's Storage Arc when the input is contiguous at offset 0 —
16423    /// but `Op::Reshape` is NOT in `collect_alias_set`'s alias-extending
16424    /// predicate (only `Op::is_view_op` + `Op::View{..}`). So for
16425    /// `X = write_slice(B, src1); S = X.slice(0, 0, 2) [offset-0
16426    /// contiguous]; R = S.reshape([2]); K = relu(R); Y =
16427    /// write_slice(X, src2)`, `collect_alias_set(X)` stops at `{X, S}`
16428    /// — `R` never enters the alias set, so `derive_ordering` never
16429    /// scans `R`'s consumers (`K`) for pinning against `Y`. `K` and `Y`
16430    /// become simultaneously "ready" once `R` completes, and
16431    /// `execution_plan`'s stable tiebreak (smaller `topo_order_multi`
16432    /// position wins) can schedule `Y` (destructive) BEFORE `K` — `K`
16433    /// then dereferences `R`'s adopted Arc (== `X`'s Arc, mutated
16434    /// in-place by `Y`) and silently reads POST-`Y` bytes. No error;
16435    /// wrong numbers.
16436    #[test]
16437    fn pipelined_write_slice_reshape_adopted_arc_reader_reads_pre_write_bytes() {
16438        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16439        let mut cache = StorageCache::new();
16440
16441        let b_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16442        let src1_id = cpu_const_f32(&graph, &mut cache, &[1.0, 2.0], &[2]);
16443        let src2_id = cpu_const_f32(&graph, &mut cache, &[99.0, 98.0], &[2]);
16444
16445        let (x_id, k_id, y_id) = {
16446            let mut g = graph.write().unwrap();
16447            let x_id = g.push(Node {
16448                op: Op::WriteSlice {
16449                    ranges: vec![(0, 2)],
16450                    dyn_offset: None,
16451                },
16452                inputs: vec![b_id, src1_id],
16453                shape: Shape::from_dims(&[4]),
16454                dtype: DType::F32,
16455            });
16456            let s_id = g.push(Node {
16457                // OFFSET-0 contiguous prefix slice — ContiguizeOf's
16458                // zero-copy fast path requires this at execute time.
16459                op: Op::Slice {
16460                    dim: 0,
16461                    start: 0,
16462                    len: 2,
16463                },
16464                inputs: vec![x_id],
16465                shape: Shape::from_dims(&[2]),
16466                dtype: DType::F32,
16467            });
16468            let r_id = g.push(Node {
16469                op: Op::Reshape(Shape::from_dims(&[2])),
16470                inputs: vec![s_id],
16471                shape: Shape::from_dims(&[2]),
16472                dtype: DType::F32,
16473            });
16474            let k_id = g.push(Node {
16475                op: Op::Relu,
16476                inputs: vec![r_id],
16477                shape: Shape::from_dims(&[2]),
16478                dtype: DType::F32,
16479            });
16480            // Round 2 OVERLAPS round 1's [0,2) range (not the [2,4)
16481            // tail) so a wrong-order execution is numerically visible
16482            // in K's output — a disjoint round 2 would corrupt bytes
16483            // K never reads, masking the defect.
16484            let y_id = g.push(Node {
16485                op: Op::WriteSlice {
16486                    ranges: vec![(0, 2)],
16487                    dyn_offset: None,
16488                },
16489                inputs: vec![x_id, src2_id],
16490                shape: Shape::from_dims(&[4]),
16491                dtype: DType::F32,
16492            });
16493            g.set_target_backend(x_id, BackendId::Cpu);
16494            g.set_target_backend(k_id, BackendId::Cpu);
16495            g.set_target_backend(y_id, BackendId::Cpu);
16496            (x_id, k_id, y_id)
16497        };
16498        let _ = x_id;
16499
16500        let plan = fuel_graph::opt::execution_plan(&graph.read().unwrap(), &[k_id, y_id]);
16501        eprintln!(
16502            "[diagnostic reshape-adopted-arc] execution_plan = {:?}",
16503            plan,
16504        );
16505
16506        let outputs = PipelinedExecutor::realize_many(Arc::clone(&graph), &[k_id, y_id], cache)
16507            .expect("realize_many");
16508        let (k_arc, _) = &outputs[0];
16509        let guard = k_arc.read().unwrap();
16510        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16511            panic!("expected Cpu storage");
16512        };
16513        let out: &[f32] = c.as_slice().unwrap();
16514        // K = relu(reshape(slice(X,0,2))) must read PRE-round-2 bytes:
16515        // relu([1.0, 2.0]) = [1.0, 2.0]. Round 2 overwrites the SAME
16516        // [0,2) range with [99.0, 98.0] — if Y (round 2) runs before K
16517        // (the ordering defect), K instead observes [99.0, 98.0].
16518        assert_eq!(
16519            out,
16520            &[1.0, 2.0],
16521            "K must read PRE-round-2 bytes through the adopted Arc; got {:?} \
16522             (post-round-2 corruption if this fails)",
16523            out,
16524        );
16525    }
16526
16527    /// The MLA-decode shape from `rebind_latent_cache_fresh_graph`'s doc
16528    /// (`fuel-core/src/lazy_deepseek2.rs`): layer L's post-append buffer
16529    /// `X_L_N` (round N) is read TWICE within one realize call — once
16530    /// (non-destructively) through a Slice+Reshape "attention math" view
16531    /// chain whose result becomes an ancestor of layer L+1's round-N
16532    /// write, and again as the DESTINATION of layer L's round-(N+1)
16533    /// append. Reproduces the same Reshape-adoption gap as
16534    /// `pipelined_write_slice_reshape_adopted_arc_reader_reads_pre_write_bytes`
16535    /// at 2-layer scale, confirming the defect is not an artifact of the
16536    /// single-hop minimal form.
16537    #[test]
16538    fn pipelined_write_slice_mla_two_layer_round2_reshape_reader_not_stranded() {
16539        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16540        let mut cache = StorageCache::new();
16541
16542        let b_l_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16543        let src_l_n_id = cpu_const_f32(&graph, &mut cache, &[1.0, 2.0], &[2]);
16544        let b_l1_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16545        let src_l_n1_id = cpu_const_f32(&graph, &mut cache, &[99.0, 98.0], &[2]);
16546
16547        let (x_l_n1_id, x_l1_n_id) = {
16548            let mut g = graph.write().unwrap();
16549            // Round N, layer L: append src_l_n into b_l.
16550            let x_l_n = g.push(Node {
16551                op: Op::WriteSlice {
16552                    ranges: vec![(0, 2)],
16553                    dyn_offset: None,
16554                },
16555                inputs: vec![b_l_id, src_l_n_id],
16556                shape: Shape::from_dims(&[4]),
16557                dtype: DType::F32,
16558            });
16559            // "Attention math" for round N at layer L: read the filled
16560            // prefix, reshape (head-split-style hop), then a kernel.
16561            let s_l_n = g.push(Node {
16562                op: Op::Slice {
16563                    dim: 0,
16564                    start: 0,
16565                    len: 2,
16566                },
16567                inputs: vec![x_l_n],
16568                shape: Shape::from_dims(&[2]),
16569                dtype: DType::F32,
16570            });
16571            let rs_l_n = g.push(Node {
16572                op: Op::Reshape(Shape::from_dims(&[2])),
16573                inputs: vec![s_l_n],
16574                shape: Shape::from_dims(&[2]),
16575                dtype: DType::F32,
16576            });
16577            let r_l_n = g.push(Node {
16578                op: Op::Relu,
16579                inputs: vec![rs_l_n],
16580                shape: Shape::from_dims(&[2]),
16581                dtype: DType::F32,
16582            });
16583            // Round N, layer L+1: append the attention-math result.
16584            let x_l1_n = g.push(Node {
16585                op: Op::WriteSlice {
16586                    ranges: vec![(0, 2)],
16587                    dyn_offset: None,
16588                },
16589                inputs: vec![b_l1_id, r_l_n],
16590                shape: Shape::from_dims(&[4]),
16591                dtype: DType::F32,
16592            });
16593            // Round N+1, layer L: append into x_l_n directly (SAME node
16594            // s_l_n/rs_l_n/r_l_n read from) — OVERLAPPING range so a
16595            // wrong-order execution is numerically visible downstream.
16596            let x_l_n1 = g.push(Node {
16597                op: Op::WriteSlice {
16598                    ranges: vec![(0, 2)],
16599                    dyn_offset: None,
16600                },
16601                inputs: vec![x_l_n, src_l_n1_id],
16602                shape: Shape::from_dims(&[4]),
16603                dtype: DType::F32,
16604            });
16605            g.set_target_backend(x_l_n, BackendId::Cpu);
16606            g.set_target_backend(r_l_n, BackendId::Cpu);
16607            g.set_target_backend(x_l1_n, BackendId::Cpu);
16608            g.set_target_backend(x_l_n1, BackendId::Cpu);
16609            (x_l_n1, x_l1_n)
16610        };
16611
16612        let plan = fuel_graph::opt::execution_plan(&graph.read().unwrap(), &[x_l1_n_id, x_l_n1_id]);
16613        eprintln!("[diagnostic mla-2-layer] execution_plan = {:?}", plan);
16614
16615        let outputs =
16616            PipelinedExecutor::realize_many(Arc::clone(&graph), &[x_l1_n_id, x_l_n1_id], cache)
16617                .expect("realize_many");
16618        // outputs[0] = x_l1_n = write_slice(b_l1, relu(reshape(slice(x_l_n))))
16619        // Must reflect round-N's PRE-round-(N+1) bytes: relu([1,2]) = [1,2].
16620        let (x_l1_n_arc, _) = &outputs[0];
16621        let guard = x_l1_n_arc.read().unwrap();
16622        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16623            panic!("expected Cpu storage");
16624        };
16625        let out: &[f32] = c.as_slice().unwrap();
16626        assert_eq!(
16627            out,
16628            &[1.0, 2.0, 0.0, 0.0],
16629            "layer L+1's round-N append must reflect PRE-round-(N+1) attention \
16630             math output; got {:?} (post-round-(N+1) corruption if this fails)",
16631            out,
16632        );
16633    }
16634}