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    Iota { len: usize },
588    /// `Op::Release` — metadata-only "this storage is no longer
589    /// needed" directive. Per `Op::Release`'s contract: the output
590    /// is a zero-element marker (NodeId placeholder for graph
591    /// bookkeeping; never read by any consumer). The executor emits
592    /// a zero-byte CPU `Storage` at the node's slot so downstream
593    /// cache lookups don't surface "missing slot" errors; the actual
594    /// deallocation of `inputs[0]` is driven by `destructive_input`
595    /// in the realize loop (Phase B), which drops the Arc held by
596    /// the cache. The held Arc's Drop chain frees device memory
597    /// (sync for CPU, stream-deferred for async backends).
598    ReleaseMarker,
599    /// `Op::WriteSlice` — in-place scatter write. The output adopts
600    /// the destination input's Storage Arc (zero-copy alias); the
601    /// kernel mutates that Arc's bytes via a write lock. The source
602    /// input's slab is copied into the destination's rectangular
603    /// region defined by `OpParams::WriteSlice`'s `ranges`.
604    ///
605    /// Carries `dest`/`source` NodeIds so the executor can:
606    /// 1. Adopt the dest's Arc as the kernel's output slot.
607    /// 2. Pass only the source as a kernel input (the dest is not
608    ///    a read-input to the kernel; it's the destination buffer
609    ///    being mutated in place).
610    ///
611    /// The realize loop's `destructive_input` cleanup evicts the
612    /// `dest` NodeId from the cache after this op runs (per
613    /// `Op::WriteSlice`'s destructive_input == Some(0) contract).
614    /// Downstream consumers read post-write bytes via this op's
615    /// own NodeId, not the dest's.
616    WriteSlice { dest: NodeId, source: NodeId },
617    /// `Op::WriteSliceRotating` — like `WriteSlice` but the rotating
618    /// axis wraps modulo `modulus`. Carries `dest`/`source`/`position`
619    /// NodeIds; the kernel reads the U32 position from `position`'s
620    /// storage and splits the write across the ring boundary if
621    /// `position % modulus + slab_len > modulus`.
622    WriteSliceRotating {
623        dest: NodeId,
624        source: NodeId,
625        position: NodeId,
626    },
627    /// `Op::WriteSliceDoff` — like `WriteSlice` but the start on `axis`
628    /// is read from a device-resident rank-0 `I64` scalar (`offset`)
629    /// at kernel launch, not host-baked. Carries `dest`/`source`/
630    /// `offset` NodeIds; the CUDA wrapper threads `offset`'s device
631    /// pointer straight to the kernel (no D2H) so a captured graph
632    /// replays at the host-updated position. No ring wrap.
633    WriteSliceDoff {
634        dest: NodeId,
635        source: NodeId,
636        offset: NodeId,
637    },
638    /// `Op::Copy { target }` — produce a fresh Storage on
639    /// `target_location`, copying bytes from `inputs[0]`'s residency.
640    ///
641    /// The kernel lookup goes through the standard binding-table path
642    /// at `(OpKind::Copy, [dt, dt], source_backend)`, so D2H is a peer
643    /// of every other op (architecture identity check #1). The
644    /// dedicated WorkItemKind exists because Op::Copy is the one op
645    /// whose output's device differs from `target_backend`:
646    /// `target_backend` is the **source** backend (where the kernel
647    /// runs — it owns the download path), while `target_location`
648    /// drives output allocation. WorkItemKind::Kernel always allocates
649    /// output on `target_backend`; Copy needs the override.
650    ///
651    /// Phase 2 of the bridge-retirement trajectory. Replaces the
652    /// per-variant `match self` in `BackendStorage::read_to_cpu_bytes`
653    /// (deleted alongside this commit) with a graph-level node the
654    /// optimizer can see, cost, and eventually fuse.
655    Copy { target_location: DeviceLocation },
656    /// `Op::Move { target }` — `Op::Copy`'s destructive sibling:
657    /// produce a fresh Storage on `target_location` via the same
658    /// data-movement kernel (binding-table lookup at
659    /// `(OpKind::Copy, [dt, dt], source_backend)`; output allocation
660    /// driven by `target_location`), then release the source. The
661    /// release half is NOT handled in the executor's arm — it rides
662    /// the realize loop's `destructive_input` cleanup
663    /// (`Op::Move::destructive_input() == Some(0)`), exactly like
664    /// `Op::Release`: the cache's Arc to the source drops after the
665    /// move runs and the Drop chain frees device memory (sync for
666    /// CPU, stream-deferred for async backends).
667    ///
668    /// Ordering safety is the graph's job, not this arm's:
669    /// `execution_plan` integrates `derive_ordering`, which pins the
670    /// Move AFTER every non-destructive reader of the source's alias
671    /// set, and `insert_safety_copies` snapshots the source for any
672    /// reader that data-flow-depends on the Move's output. A Move
673    /// therefore never strands a sibling consumer of its source.
674    ///
675    /// Same-device moves are legal and match the legacy
676    /// `GraphExecutor` contract: a plain copy producing fresh
677    /// storage on the same device, with the source still evicted
678    /// afterward.
679    Move { target_location: DeviceLocation },
680    /// `Op::Alloc { target }` — produce a freshly-allocated, zero-
681    /// initialized Storage on `target_location` with the node's shape
682    /// + dtype. Zero inputs.
683    ///
684    /// Doesn't dispatch through the binding table — the executor's
685    /// arm calls each backend's native allocator directly. For
686    /// non-CPU targets it takes the device handle from the
687    /// [`DeviceRegistry`] the caller handed the realize (a
688    /// `*_with_devices` entry point).
689    ///
690    /// Phase 3a of the bridge-retirement trajectory (post-9c).
691    /// Replaces `fuel-tensor::inference_context::alloc_zeroed_on`'s
692    /// per-`DeviceLocation` match with a graph node the optimizer
693    /// can see; the per-backend match moves from fuel-core's bridge
694    /// layer into fuel-storage's executor (the architectural dispatch
695    /// layer).
696    Alloc { target_location: DeviceLocation },
697    /// `Op::ZeroFill` — fill the input's storage bytes with zero,
698    /// in place. Adopts the input's Storage Arc as the output (same
699    /// Storage; bytes mutated). Destructive on `inputs[0]`.
700    ///
701    /// Direct executor dispatch (no binding-table lookup) per the
702    /// same rationale as `WorkItemKind::Alloc`: structural op,
703    /// per-backend dispatch. Per-backend behaviour:
704    /// - CPU: `bytes_mut().fill(0)` via the CoW path.
705    /// - CUDA: `CudaStorageBytes::zero_async` via baracuda alpha.30's
706    ///   `DeviceBuffer::zero_async` (cuMemsetD8Async, in-place).
707    /// - Vulkan: `VulkanBackend::fill_bytes_zero` via
708    ///   `vkCmdFillBuffer` — device-side, ~2× the bandwidth of the
709    ///   old host-staged zeros path that `alloc_zeroed_on` used.
710    ///
711    /// Phase 3a follow-up of bridge-retirement (post-9c). Pairs with
712    /// the uninit-alloc `WorkItemKind::Alloc` to give the
713    /// architecturally clean "Op::Alloc (uninit) → Op::ZeroFill
714    /// (explicit fill)" pipeline.
715    ZeroFill,
716    /// In-place kernel — the output adopts the input at index
717    /// `target_idx`'s Storage Arc and the kernel mutates that Arc's
718    /// bytes through a single write lock. Phase 3 of the in-place ops
719    /// infrastructure
720    /// (`docs/session-prompts/in-place-ops-infrastructure.md`).
721    ///
722    /// Kernel lookup goes through the standard binding table at
723    /// `(op_to_op_kind, [target_dtype], target_backend)`. The wrapper's
724    /// `inputs` slice is empty; `outputs[0]` is the target Arc. The
725    /// wrapper acquires `outputs[0]`'s write lock and calls the
726    /// underlying single-pointer kernel (e.g. baracuda's
727    /// `affine_inplace_*` on CUDA, or the chassis with `src == dst`
728    /// on CPU).
729    ///
730    /// Output Arc adoption: identical to `WorkItemKind::WriteSlice`
731    /// (the output's slot = the target's Arc; the realize loop's
732    /// `destructive_input` cleanup evicts the target's NodeId from the
733    /// cache afterward). Downstream consumers read post-mutation bytes
734    /// through this op's NodeId, not the target's.
735    InplaceKernel {
736        /// Index into `inputs` whose Storage Arc the output adopts.
737        /// Always equal to the source `Op::destructive_input().unwrap()`;
738        /// stored explicitly so the executor doesn't re-derive it.
739        target_idx: usize,
740    },
741    /// `Op::View { slot }` — multi-output projection (Option C,
742    /// Session 4). The output's Storage Arc IS the producer's Arc;
743    /// the WorkItem's `output_layout` was prepared by
744    /// [`fuel_graph::NodeHandle::view`] with the slot's `byte_offset`
745    /// baked into `Layout::start_offset` so downstream kernels reading
746    /// the producer's bytes as `slot_dtype` elements land on the
747    /// slot's first byte. Structurally identical to [`Self::ViewOf`]
748    /// at execute time — kept distinct so error messages and
749    /// telemetry have a clean dispatch point.
750    SlotView { producer: NodeId },
751    /// `Op::ViewOwned { slot }` — multi-output projection with an
752    /// independent destination buffer. At realize time, allocate a
753    /// fresh contiguous Storage of the slot's `(shape, dtype)` on
754    /// the producer's device, then memcpy
755    /// `producer.bytes[slot.byte_offset .. slot.byte_offset + slot.len_bytes]`
756    /// into the new storage. Session 4 ships the CPU path; non-CPU
757    /// backends return a typed error until their copy-with-offset
758    /// hooks land in the followup session.
759    SlotOwn { producer: NodeId, slot: u32 },
760}
761
762/// One unit of work emitted by the compiler thread to the executor
763/// thread.
764/// Phase name of a work item's kind, for the executor's host-phase accounting
765/// (`op_profile::PhaseTimer`). One name per variant so the table splits the
766/// per-item executor time by what the item is.
767fn work_item_kind_name(kind: &WorkItemKind) -> &'static str {
768    match kind {
769        WorkItemKind::ConstAdopt => "item.ConstAdopt",
770        WorkItemKind::ViewOf { .. } => "item.ViewOf",
771        WorkItemKind::ContiguizeOf { .. } => "item.ContiguizeOf",
772        WorkItemKind::Kernel => "item.Kernel",
773        WorkItemKind::Iota { .. } => "item.Iota",
774        WorkItemKind::ReleaseMarker => "item.ReleaseMarker",
775        WorkItemKind::WriteSlice { .. } => "item.WriteSlice",
776        WorkItemKind::WriteSliceRotating { .. } => "item.WriteSliceRotating",
777        WorkItemKind::WriteSliceDoff { .. } => "item.WriteSliceDoff",
778        WorkItemKind::Copy { .. } => "item.Copy",
779        WorkItemKind::Move { .. } => "item.Move",
780        WorkItemKind::Alloc { .. } => "item.Alloc",
781        WorkItemKind::ZeroFill => "item.ZeroFill",
782        WorkItemKind::InplaceKernel { .. } => "item.InplaceKernel",
783        WorkItemKind::SlotView { .. } => "item.SlotView",
784        WorkItemKind::SlotOwn { .. } => "item.SlotOwn",
785    }
786}
787
788/// Work items that choose no backend of their own: adopting an input-cache entry
789/// (`Op::Const`), the metadata-only view items, and `ContiguizeOf` (it runs on its
790/// input's backend; its `target_backend` is a `Cpu` placeholder, which made every
791/// Qwen3 decode step look like ~900 Vulkan -> Cpu -> Vulkan switches and forced a
792/// batch submit at each one). Their `target_backend` is a placeholder
793/// (a `Const` is always stamped `Cpu`; a view inherits its producer's or
794/// defaults to `Cpu`), so letting them take part in the chunk-boundary logic made
795/// every weight `Const` that sits between two Vulkan kernels look like a
796/// Vulkan -> Cpu -> Vulkan backend switch: the executor armed `multi_backend`,
797/// submitted the open Vulkan batch at each "switch", and then waited for it
798/// before the next Vulkan op. In Qwen3-0.6B decode that was about 400 forced
799/// submit-and-wait round trips per step (`docs/research/qwen3-vulkan-decode-profile.md`).
800fn is_backend_neutral(kind: &WorkItemKind) -> bool {
801    matches!(
802        kind,
803        WorkItemKind::ConstAdopt
804            | WorkItemKind::ViewOf { .. }
805            | WorkItemKind::SlotView { .. }
806            | WorkItemKind::ContiguizeOf { .. }
807    )
808}
809
810struct WorkItem {
811    node_id: NodeId,
812    inputs: Vec<NodeId>,
813    /// Number of elements in the output (for output Storage
814    /// allocation; multiplied by dtype size at allocation time).
815    elem_count: usize,
816    dtype: DType,
817    target_backend: BackendId,
818    /// What kind of work this represents (kernel vs adopt vs view).
819    kind: WorkItemKind,
820    /// `Some` for [`WorkItemKind::Kernel`]; `None` for the other
821    /// two. Carries the resolved kernel ref + op_params.
822    compiled: Option<CompiledNode>,
823    /// The output's [`Layout`]. For kernels: always
824    /// `Layout::contiguous(node.shape)`. For metadata-only view
825    /// ops: a strided/broadcast Layout pointing at the input's
826    /// Storage. Carried so the executor can publish the right
827    /// Layout into its layout cache and ultimately return it from
828    /// [`PipelinedExecutor::realize`].
829    output_layout: Layout,
830    /// Index into `inputs` whose storage gets destroyed by this op
831    /// (`Op::Release` / `Op::Move` → `Some(0)`; non-destructive ops
832    /// → `None`). The executor evicts the destroyed input from the
833    /// cache after the op runs, unless it's also in the realize
834    /// target set. Snapshot of `node.op.destructive_input()` at
835    /// compile time.
836    destructive_input: Option<usize>,
837    /// Multi-output bundle metadata (Option C, item 3). `Some(_)`
838    /// when the node was declared multi-output via
839    /// `Graph::set_output_views`; the Kernel arm allocates one
840    /// contiguous output Storage sized to fit every slot's bytes,
841    /// then attaches the bundle via `Storage::with_bundle` so
842    /// downstream `Op::View`/`Op::ViewOwned` nodes resolve
843    /// correctly.
844    output_bundle: Option<Arc<[fuel_ir::storage::OutputView]>>,
845}
846
847/// Merge the graph's side-effect roots into the caller's requested
848/// roots. Preserves caller order (user roots come first), dedupes,
849/// and appends side-effect-bearing nodes (`Op::Print`, `Op::Save`,
850/// etc.) so their effects fire even when not reachable from the
851/// caller's roots. Mirrors `fuel-graph-executor::extend_with_side_effect_roots`.
852///
853/// Short-circuits to a borrow-equivalent `Vec<NodeId>` when the graph
854/// has no side-effect roots — the common case during inference.
855fn extend_with_side_effect_roots(graph: &Graph, user_roots: &[NodeId]) -> Vec<NodeId> {
856    let side = graph.side_effect_roots();
857    if side.is_empty() {
858        return user_roots.to_vec();
859    }
860    let mut out = Vec::with_capacity(user_roots.len() + side.len());
861    out.extend_from_slice(user_roots);
862    for &s in side {
863        if !out.contains(&s) {
864            out.push(s);
865        }
866    }
867    out
868}
869
870/// Pipelined executor: walks a graph, compiles each node in a
871/// dedicated thread, executes the compiled stream on the calling
872/// thread.
873///
874/// # Architectural commitments (Phase 7.6 step 9c)
875///
876/// ## Fail-fast dispatch — no runtime CPU fallback
877///
878/// The binding-table lookup is fail-fast. If
879/// `global_bindings().lookup(op_kind, dtypes, backend)` returns
880/// `None`, `realize` / `realize_many` surface a typed `Error::Msg`
881/// at compile time. There is **no runtime fallback** to a CPU
882/// sibling when a registered kernel returns `Err`; we commit to the
883/// backend contract that registered kernels must succeed for shapes
884/// matching their declared coverage.
885///
886/// Rationale: per-decision-point alternatives (architecture v1.0
887/// §04) already let multiple backends register at the same key. If
888/// a backend's coverage is partial, the right answer is to register
889/// only the shapes it actually handles — not to silently fall back
890/// at runtime, which masks bugs and slows the hot path. The
891/// long-term home for "this op on this device" is graph-level
892/// dispatch insertion (Op::Copy edges to a backend that does
893/// support the shape), which makes the routing decision visible in
894/// the IR rather than hidden in the executor. Picker-arc step 4b
895/// landed exactly that: `compile_plan`'s off-device fallback
896/// (`PlanOptions::fallback_placements_for`) admits a candidate on
897/// another device when the pinned device lacks the implementation,
898/// and the bridge's cross-device-copy pass stitches residency
899/// around the off-device winner. There is exactly ONE fallback
900/// owner — the plan-time picker; this executor still dispatches
901/// fail-fast, and ops with no implementation anywhere surface the
902/// plan-time `NoBackendForOp` error.
903///
904/// This is a deliberate departure from the legacy executor's
905/// `cpu_fallback(op, inputs, shape, dtype, cache)` semantics.
906///
907/// ## Optimizer separation — callers compose
908///
909/// The pipelined executor does **not** run `fuel_graph::opt` or any
910/// `RuleRegistry` pass itself. Callers that want graph-level
911/// optimization compose it at the call site:
912///
913/// ```ignore
914/// let optimized_targets = registry.optimize_to_fixpoint(&graph, &targets);
915/// PipelinedExecutor::realize_many(graph, &optimized_targets, inputs)?;
916/// ```
917///
918/// Rationale: the legacy `GraphExecutor<B>::with_optimization(bool)`
919/// coupling reflected its per-typed-entry API surface
920/// (`realize_f32`, etc.) where the convenience of a single
921/// optimize+realize call was load-bearing. The pipelined path has
922/// a uniform `realize_many` that composes trivially — no need to
923/// re-couple them at the executor layer. This keeps the executor
924/// focused on execution and lets the optimizer evolve
925/// independently (different rule registries per call site, mid-
926/// pipeline opt+realize+opt+realize patterns, etc.).
927pub struct PipelinedExecutor;
928
929impl PipelinedExecutor {
930    /// Realize `target` and every transitive dependency. Compilation
931    /// runs in a worker thread; execution runs on the calling
932    /// thread.
933    ///
934    /// Pre-conditions:
935    ///
936    /// - Every reachable `Op::Const` node must have a corresponding
937    ///   entry in `inputs` (pre-realized Storage Arc).
938    /// - Every reachable non-`Const` node must have its
939    ///   `target_backend` set in the graph
940    ///   (`Graph::set_target_backend`).
941    /// - The op + dtype must be registered in `global_bindings()`.
942    ///
943    /// Returns the realized `Storage` Arc for `target` plus its
944    /// resolved [`Layout`]. The Layout is contiguous for kernel
945    /// outputs; for graphs whose target is a metadata-only view
946    /// op (`Op::Transpose`, `Op::Permute`, `Op::BroadcastTo`),
947    /// the returned Storage shares its bytes with an upstream
948    /// node and the Layout encodes the view's strides + offset.
949    ///
950    /// Production-correct: errors on any unmet precondition rather
951    /// than panicking.
952    pub fn realize(
953        graph: Arc<RwLock<Graph>>,
954        target: NodeId,
955        inputs: StorageCache,
956    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
957        Self::realize_inner(
958            graph,
959            target,
960            inputs,
961            OrderSource::Default,
962            SymEnv::default(),
963        )
964        .map(|(s, l, _produced)| (s, l))
965    }
966
967    /// [`Self::realize`] with the device handles the caller already holds (ROADMAP row 137, seam S3 step 3c):
968    /// a CUDA or Vulkan place named in `devices` is where the executor finds its handle. Use this for any
969    /// graph that allocates on, or copies to, a GPU; the plain [`Self::realize`] has no handle to give the
970    /// executor, so it is for CPU graphs and for graphs whose GPU work needs none.
971    pub fn realize_with_devices(
972        graph: Arc<RwLock<Graph>>,
973        target: NodeId,
974        inputs: StorageCache,
975        devices: DeviceRegistry,
976    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
977        Self::realize_inner_with(
978            graph,
979            target,
980            inputs,
981            OrderSource::Default,
982            SymEnv::default(),
983            devices,
984        )
985        .map(|(s, l, _produced)| (s, l))
986    }
987
988    /// Env-carrying sibling of [`Self::realize`]: realize `target` with a
989    /// per-pass [`SymEnv`] supplying the runtime bindings for any
990    /// `DynScalar` op params (today: `Op::WriteSlice`'s dynamic start
991    /// offset — Phase D symbolic extents). An **empty** env is
992    /// byte-identical to [`Self::realize`]; the env is consulted only by ops
993    /// that carry a `DynScalar`, so a graph with none ignores it. Uses
994    /// the default (`execution_plan`) dispatch order.
995    ///
996    /// This is the input-determined path for persistent decode (the
997    /// per-token `cached_len` write offset). The `OptimizedGraph`/route
998    /// entry points keep an empty env until the realize bridge threads
999    /// the session env through them (Phase D step 1, fuel-core).
1000    pub fn realize_with_env(
1001        graph: Arc<RwLock<Graph>>,
1002        target: NodeId,
1003        inputs: StorageCache,
1004        sym_env: SymEnv,
1005    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1006        Self::realize_inner(graph, target, inputs, OrderSource::Default, sym_env)
1007            .map(|(s, l, _produced)| (s, l))
1008    }
1009
1010    /// Producing sibling of [`Self::realize_with_env`]: realize `target` and
1011    /// ALSO return the [`SymEnv`] of symbols BOUND BY PRODUCERS during the
1012    /// pass — data-determined dynamic shapes (`Op::NonZeroIndices`'s
1013    /// runtime count, etc.). The returned env is disjoint from the input
1014    /// `sym_env` (which is input-determined). Empty when the graph has no
1015    /// data-determined producer. This is the observation point for the
1016    /// increment-2a bind seam; a downstream pass consumes these bindings
1017    /// as dynamic extents.
1018    pub fn realize_with_env_producing(
1019        graph: Arc<RwLock<Graph>>,
1020        target: NodeId,
1021        inputs: StorageCache,
1022        sym_env: SymEnv,
1023    ) -> Result<(Arc<RwLock<Storage>>, Layout, SymEnv)> {
1024        Self::realize_inner(graph, target, inputs, OrderSource::Default, sym_env)
1025    }
1026
1027    /// PR-A3b-1 entry: realize `target` driven from `optimized`'s
1028    /// in-place "plan IS the graph" form. The dispatch order is the
1029    /// `OptimizedGraph`'s `extract_runs`/`lower_run` lowering (computed
1030    /// after safety-copy insertion); per-node kernel resolution uses
1031    /// the binding-table-lookup path (no `ExecutionPlan`, so no
1032    /// route-picking — A3b-1 is branchless). The optimize-time
1033    /// `generation` drives the `TopologyChanged` chunk-boundary check.
1034    ///
1035    /// Pre-conditions match [`Self::realize`]: every reachable kernel-bearing
1036    /// node must have `target_backend` set (the bridge's
1037    /// `stamp_plan_backends` does this) and a registered binding.
1038    pub fn realize_with_optimized(
1039        graph: Arc<RwLock<Graph>>,
1040        target: NodeId,
1041        inputs: StorageCache,
1042        optimized: &OptimizedGraph,
1043    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1044        Self::realize_inner(
1045            graph,
1046            target,
1047            inputs,
1048            OrderSource::Optimized {
1049                optimized,
1050                route: None,
1051            },
1052            SymEnv::default(),
1053        )
1054        .map(|(s, l, _produced)| (s, l))
1055    }
1056
1057    /// [`Self::realize_with_optimized`] with the device handles the caller already holds (ROADMAP row 137,
1058    /// seam S3 step 3b): a CUDA or Vulkan place named in `devices` is not looked for in the storage cache.
1059    pub fn realize_with_optimized_with_devices(
1060        graph: Arc<RwLock<Graph>>,
1061        target: NodeId,
1062        inputs: StorageCache,
1063        optimized: &OptimizedGraph,
1064        devices: DeviceRegistry,
1065    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1066        Self::realize_inner_with(
1067            graph,
1068            target,
1069            inputs,
1070            OrderSource::Optimized {
1071                optimized,
1072                route: None,
1073            },
1074            SymEnv::default(),
1075            devices,
1076        )
1077        .map(|(s, l, _produced)| (s, l))
1078    }
1079
1080    /// [`Self::realize_with_optimized_picking_env`] with the device handles the caller already holds.
1081    #[allow(clippy::too_many_arguments)]
1082    pub fn realize_with_optimized_picking_env_with_devices(
1083        graph: Arc<RwLock<Graph>>,
1084        target: NodeId,
1085        inputs: StorageCache,
1086        optimized: &OptimizedGraph,
1087        selector: Option<Arc<dyn RuntimeSelector>>,
1088        lookup: Option<BackendRuntimeLookup>,
1089        sym_env: SymEnv,
1090        devices: DeviceRegistry,
1091    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1092        let order_source = match Self::streaming_pick_for(&graph, selector, lookup)? {
1093            Some(pick) => {
1094                return Self::realize_inner_with(
1095                    graph,
1096                    target,
1097                    inputs,
1098                    OrderSource::Streaming {
1099                        optimized,
1100                        pick: &pick,
1101                    },
1102                    sym_env,
1103                    devices,
1104                )
1105                .map(|(s, l, _produced)| (s, l));
1106            }
1107            None => OrderSource::Optimized {
1108                optimized,
1109                route: None,
1110            },
1111        };
1112        Self::realize_inner_with(graph, target, inputs, order_source, sym_env, devices)
1113            .map(|(s, l, _produced)| (s, l))
1114    }
1115
1116    /// [`Self::realize_with_optimized_picking_cached_env`] with the device handles the caller already holds.
1117    #[allow(clippy::too_many_arguments)]
1118    pub fn realize_with_optimized_picking_cached_env_with_devices(
1119        graph: Arc<RwLock<Graph>>,
1120        target: NodeId,
1121        inputs: StorageCache,
1122        optimized: &OptimizedGraph,
1123        order_cache: &std::sync::OnceLock<Vec<NodeId>>,
1124        selector: Option<Arc<dyn RuntimeSelector>>,
1125        lookup: Option<BackendRuntimeLookup>,
1126        sym_env: SymEnv,
1127        devices: DeviceRegistry,
1128    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1129        let order_source = match Self::streaming_pick_for(&graph, selector, lookup)? {
1130            Some(pick) => {
1131                return Self::realize_inner_with(
1132                    graph,
1133                    target,
1134                    inputs,
1135                    OrderSource::Streaming {
1136                        optimized,
1137                        pick: &pick,
1138                    },
1139                    sym_env,
1140                    devices,
1141                )
1142                .map(|(s, l, _produced)| (s, l));
1143            }
1144            None => OrderSource::Cached {
1145                optimized,
1146                order_cache,
1147            },
1148        };
1149        Self::realize_inner_with(graph, target, inputs, order_source, sym_env, devices)
1150            .map(|(s, l, _produced)| (s, l))
1151    }
1152
1153    /// Env-carrying sibling of [`Self::realize_with_optimized`]: same
1154    /// optimized-graph dispatch, but with a per-pass [`SymEnv`] supplying
1155    /// the runtime bindings for `DynScalar` op params (Phase D symbolic
1156    /// extents). An empty env is byte-identical to
1157    /// [`Self::realize_with_optimized`]. The realize bridge threads its session
1158    /// env through here for persistent decode.
1159    pub fn realize_with_optimized_env(
1160        graph: Arc<RwLock<Graph>>,
1161        target: NodeId,
1162        inputs: StorageCache,
1163        optimized: &OptimizedGraph,
1164        sym_env: SymEnv,
1165    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1166        Self::realize_inner(
1167            graph,
1168            target,
1169            inputs,
1170            OrderSource::Optimized {
1171                optimized,
1172                route: None,
1173            },
1174            sym_env,
1175        )
1176        .map(|(s, l, _produced)| (s, l))
1177    }
1178
1179    /// PR-C1 entry: realize `target` driven from `optimized`'s in-place
1180    /// form **following the runtime route picker's chosen arms**. The
1181    /// dispatch order is the route-aware lowering
1182    /// ([`fuel_graph::lower_picked_route`]) over `route` — the per-branch
1183    /// arm the picker (Picker 2) selected by live telemetry. A branch
1184    /// absent from `route` defaults to arm 0, so an **empty** route is
1185    /// byte-identical to [`Self::realize_with_optimized`] (the no-pressure /
1186    /// no-telemetry contract). A branchless graph has no branches ⇒ the
1187    /// route is empty ⇒ this is exactly the arm-0 path.
1188    pub fn realize_with_optimized_route(
1189        graph: Arc<RwLock<Graph>>,
1190        target: NodeId,
1191        inputs: StorageCache,
1192        optimized: &OptimizedGraph,
1193        route: &PickedRoute,
1194    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1195        Self::realize_inner(
1196            graph,
1197            target,
1198            inputs,
1199            OrderSource::Optimized {
1200                optimized,
1201                route: Some(route),
1202            },
1203            SymEnv::default(),
1204        )
1205        .map(|(s, l, _produced)| (s, l))
1206    }
1207
1208    /// Env-carrying sibling of [`Self::realize_with_optimized_route`] — the
1209    /// route-aware lowering with a per-pass [`SymEnv`]. An empty env is
1210    /// byte-identical to [`Self::realize_with_optimized_route`].
1211    pub fn realize_with_optimized_route_env(
1212        graph: Arc<RwLock<Graph>>,
1213        target: NodeId,
1214        inputs: StorageCache,
1215        optimized: &OptimizedGraph,
1216        route: &PickedRoute,
1217        sym_env: SymEnv,
1218    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1219        Self::realize_inner(
1220            graph,
1221            target,
1222            inputs,
1223            OrderSource::Optimized {
1224                optimized,
1225                route: Some(route),
1226            },
1227            sym_env,
1228        )
1229        .map(|(s, l, _produced)| (s, l))
1230    }
1231
1232    /// Cleanup Step C/D entry: the executor OWNS `Op::Branch` arm-selection.
1233    /// Given the runtime `selector` + the live device `lookup` (built
1234    /// bridge-side from the realize `Device` + Judge oracle and passed in,
1235    /// exactly like the residency `input_residency` provider), pick one arm per
1236    /// branch HERE — at dispatch — then lower the chosen route. The per-arm
1237    /// candidates are re-enumerated from the runtime binding registry + the
1238    /// graph (Step D: no threaded `ExecutionPlan`).
1239    ///
1240    /// No `selector` (the `runtime_selector_disabled()` opt-out) or a
1241    /// branchless graph yields the arm-0 lowering, byte-identical to Phase B.
1242    ///
1243    /// **Step E Phase C, PR C1 — STREAMING.** A branched graph WITH a
1244    /// selector no longer resolves the whole route up front: it routes to the
1245    /// `OrderSource::Streaming` walk, where the compiler thread resolves
1246    /// each branch lazily as the frontier reaches it (via
1247    /// [`resolve_branch`]). C1 keeps the SAME VRAM-only selector chain — so
1248    /// the streamed route equals the one-shot `pick_route` route byte-for-byte
1249    /// — and only changes *when* a branch resolves; C2 makes that moment read
1250    /// live device load.
1251    pub fn realize_with_optimized_picking_env(
1252        graph: Arc<RwLock<Graph>>,
1253        target: NodeId,
1254        inputs: StorageCache,
1255        optimized: &OptimizedGraph,
1256        selector: Option<Arc<dyn RuntimeSelector>>,
1257        lookup: Option<BackendRuntimeLookup>,
1258        sym_env: SymEnv,
1259    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1260        match Self::streaming_pick_for(&graph, selector, lookup)? {
1261            Some(pick) => Self::realize_inner(
1262                graph,
1263                target,
1264                inputs,
1265                OrderSource::Streaming {
1266                    optimized,
1267                    pick: &pick,
1268                },
1269                sym_env,
1270            )
1271            .map(|(s, l, _produced)| (s, l)),
1272            None => Self::realize_with_optimized_env(graph, target, inputs, optimized, sym_env),
1273        }
1274    }
1275
1276    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
1277    /// §5) — cached sibling of [`Self::realize_with_optimized_picking_env`]
1278    /// for the plan-once persistent-decode caller, which holds `order_cache`
1279    /// across repeated calls over the SAME graph/roots/`optimized` (one per
1280    /// `DecodeSession`, initially empty). On a branchless graph with no
1281    /// selector pressure (the decode shape this is for), dispatches via
1282    /// [`OrderSource::Cached`] — computed once, reused thereafter, see that
1283    /// variant's doc for the safety argument. A branched graph WITH a
1284    /// resolved selector pick falls back to the uncached
1285    /// [`OrderSource::Streaming`] path unchanged (caching doesn't apply
1286    /// there; this entry point exists for the decode case, not to cover
1287    /// every caller).
1288    pub fn realize_with_optimized_picking_cached_env(
1289        graph: Arc<RwLock<Graph>>,
1290        target: NodeId,
1291        inputs: StorageCache,
1292        optimized: &OptimizedGraph,
1293        order_cache: &std::sync::OnceLock<Vec<NodeId>>,
1294        selector: Option<Arc<dyn RuntimeSelector>>,
1295        lookup: Option<BackendRuntimeLookup>,
1296        sym_env: SymEnv,
1297    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1298        match Self::streaming_pick_for(&graph, selector, lookup)? {
1299            Some(pick) => Self::realize_inner(
1300                graph,
1301                target,
1302                inputs,
1303                OrderSource::Streaming {
1304                    optimized,
1305                    pick: &pick,
1306                },
1307                sym_env,
1308            )
1309            .map(|(s, l, _produced)| (s, l)),
1310            None => Self::realize_inner(
1311                graph,
1312                target,
1313                inputs,
1314                OrderSource::Cached {
1315                    optimized,
1316                    order_cache,
1317                },
1318                sym_env,
1319            )
1320            .map(|(s, l, _produced)| (s, l)),
1321        }
1322    }
1323
1324    /// Build the [`StreamingPick`] for the executor's picking entry points —
1325    /// the streaming successor of the one-shot `pick_route_for` (which was the
1326    /// relocated body of the bridge's old `resolve_runtime_route`). Returns
1327    /// `None` (⇒ arm-0 lowering, the untouched `route: None` /
1328    /// `dispatch_order` path) when there is no `selector` (the disabled
1329    /// opt-out) or the graph has no `Op::Branch` (the branchless fast-path:
1330    /// skip the streaming machinery entirely so the common case is unchanged
1331    /// and byte-identical). Otherwise it carries the selector + lookup into
1332    /// the [`OrderSource::Streaming`] walk, which resolves each branch at the
1333    /// frontier (PR C1). The per-arm candidates are re-enumerated from the
1334    /// runtime binding registry inside the compiler thread (Step D — was the
1335    /// threaded `ExecutionPlan`).
1336    fn streaming_pick_for(
1337        graph: &Arc<RwLock<Graph>>,
1338        selector: Option<Arc<dyn RuntimeSelector>>,
1339        // Accepted for call-site parity with `pick_route` but not stored: the
1340        // streaming walk reads VRAM + load through the selector, which holds its
1341        // own `BackendRuntimeLookup`.
1342        _lookup: Option<BackendRuntimeLookup>,
1343    ) -> Result<Option<StreamingPick>> {
1344        let Some(selector) = selector else {
1345            return Ok(None);
1346        };
1347        let g = graph
1348            .read()
1349            .map_err(|_| Error::Msg("graph lock poisoned".into()).bt())?;
1350        let has_branch = (0..g.len()).any(|i| matches!(g.node(NodeId(i)).op, Op::Branch { .. }));
1351        if !has_branch {
1352            return Ok(None);
1353        }
1354        Ok(Some(StreamingPick { selector }))
1355    }
1356
1357    /// Capture a single-device CUDA decode step's kernel launches into a
1358    /// replayable [`CapturedRun`] (the CapturedRun executor build-out).
1359    ///
1360    /// Runs the graph TWICE against fixed-address buffers:
1361    ///   1. **Warm (record)**: realize normally into a fresh cache cloned
1362    ///      from `inputs`, recording every compute node's output Arc as its
1363    ///      fixed capture buffer, and synchronizing so the result is stable.
1364    ///   2. **Capture (reuse)**: re-issue the same launch sequence — each
1365    ///      node writing INTO its recorded buffer via the write-into kernel
1366    ///      path (no allocation) — inside [`CudaDevice::capture_run`],
1367    ///      producing an instantiated [`CapturedRun`].
1368    ///
1369    /// Both passes share the SAME input Arcs (cloned map, shared buffers)
1370    /// and the SAME recorded output buffers, so every device address the
1371    /// captured graph bakes in is stable for replay. To replay a later
1372    /// token: overwrite the fixed input buffers in place (H2D), call
1373    /// `run.replay(dev)`, then read `output`.
1374    ///
1375    /// Contract (surfaced as `Err`, never a panic or a mid-capture alloc):
1376    ///   - CUDA-only, single device: every compute node targets `Cuda`;
1377    ///     no cross-device `Op::Copy`/`Move` in the graph.
1378    ///   - Every compute node's op must have a write-into CUDA wrapper
1379    ///     (`op_kind_is_capture_writeinto`); an unsupported op surfaces a
1380    ///     clear capability gap rather than silently breaking the capture.
1381    ///   - Inputs must be contiguous (no auto-Contiguize alloc in capture).
1382    #[cfg(feature = "cuda")]
1383    pub fn capture_decode(
1384        graph: Arc<RwLock<Graph>>,
1385        target: NodeId,
1386        inputs: StorageCache,
1387        sym_env: SymEnv,
1388    ) -> Result<CapturedDecode> {
1389        use fuel_memory::BackendStorage;
1390
1391        // Front matter mirrors realize_inner: safety copies + frozen order.
1392        {
1393            let mut g = graph.write().map_err(|_| poisoned("graph lock"))?;
1394            let effective_roots = extend_with_side_effect_roots(&g, &[target]);
1395            insert_safety_copies(&mut g, &effective_roots);
1396        }
1397        let (compiler_work, _wait_set, seed_layouts) = {
1398            let g = graph.read().map_err(|_| poisoned("graph lock"))?;
1399            let effective_roots = extend_with_side_effect_roots(&g, &[target]);
1400            let (work, wait_set) =
1401                compiler_work_and_wait_set_for(&g, &effective_roots, &OrderSource::Default);
1402            let mut layouts: HashMap<NodeId, Layout> = HashMap::with_capacity(inputs.len());
1403            for &id in inputs.keys() {
1404                layouts.insert(id, g.layout(id));
1405            }
1406            (work, wait_set, layouts)
1407        };
1408
1409        // Compile every WorkItem once (one compiler thread) and collect them
1410        // so both passes replay the identical sequence.
1411        let (tx, rx) = channel::<Result<WorkItem>>();
1412        let graph_for_compiler = Arc::clone(&graph);
1413        let compiler = thread::spawn(move || {
1414            compiler_thread_body(graph_for_compiler, compiler_work, sym_env, tx);
1415        });
1416        let mut items: Vec<WorkItem> = Vec::new();
1417        for item in rx {
1418            items.push(item?);
1419        }
1420        compiler
1421            .join()
1422            .map_err(|_| Error::Msg("compiler thread panicked".to_string()).bt())?;
1423
1424        // CapturedRun 4b Step-4 diagnostic: name every kernel placed OFF Cuda
1425        // (an unseeded / audited-loser op that forces a cross-device copy and
1426        // blocks capture), so verification-ledger seeding can target it
1427        // precisely. Fires only when a capture is attempted AND something is
1428        // mis-placed — otherwise silent.
1429        {
1430            let off: Vec<String> = items
1431                .iter()
1432                .filter_map(|it| match &it.kind {
1433                    WorkItemKind::Kernel if it.target_backend != BackendId::Cuda => {
1434                        let desc = it
1435                            .compiled
1436                            .as_ref()
1437                            .map(|c| format!("{:?} dtypes={:?}", c.op, c.dtypes))
1438                            .unwrap_or_else(|| "?".to_string());
1439                        Some(format!(
1440                            "node {:?}: {desc} on {:?}",
1441                            it.node_id, it.target_backend
1442                        ))
1443                    }
1444                    _ => None,
1445                })
1446                .collect();
1447            if !off.is_empty() {
1448                eprintln!(
1449                    "[capture-diag] {} kernel(s) placed OFF Cuda (these block capture): {}",
1450                    off.len(),
1451                    off.join("; "),
1452                );
1453            }
1454        }
1455
1456        // Capture-safety validation — surface every gap up front, before any
1457        // launch, so a capture scope is never entered on an unsupported graph.
1458        for item in &items {
1459            match &item.kind {
1460                // Op::Move: the destructive half (releasing the source) is
1461                // driven by the realize loop's `destructive_input` cleanup,
1462                // which runs once per REALIZE call — not once per `replay()`.
1463                // A captured graph's `replay()` re-executes the same baked
1464                // launches repeatedly without re-running that surrounding
1465                // cleanup between replays, so whether a repeat-replayed Move
1466                // is even meaningful is unclear; out of scope here (4b-ζ) —
1467                // keep rejecting every Move unconditionally.
1468                WorkItemKind::Move { .. } => {
1469                    return Err(Error::Msg(format!(
1470                        "capture_decode: graph has an Op::Move at node {:?}; \
1471                         Move's destructive source-release half is driven by \
1472                         per-realize cleanup, not per-replay, so capture is \
1473                         not supported for Move (out of scope — see the \
1474                         `capture_decode` validation loop's Move arm).",
1475                        item.node_id,
1476                    ))
1477                    .bt());
1478                }
1479                // Op::Copy: a same-device CUDA→CUDA copy (e.g. an
1480                // `insert_safety_copies` snapshot) has a write-into wrapper
1481                // (`copy_from_cuda_wrapper`'s `BackendStorage::Cuda` branch,
1482                // via `CudaStorageBytes::copy_from_device`) and is
1483                // capture-safe. A copy whose `target_location` is `Cpu` or
1484                // `Vulkan` is a genuine host round-trip / cross-backend
1485                // transfer and can never be part of a CUDA graph capture —
1486                // keep rejecting those. (`gpu_id` is not cross-checked
1487                // against the capture device, matching the `Kernel` arm's
1488                // `target_backend` check just above: today's decode graphs
1489                // are single-GPU only.)
1490                WorkItemKind::Copy { target_location } => {
1491                    if !matches!(target_location, DeviceLocation::Cuda { .. }) {
1492                        return Err(Error::Msg(format!(
1493                            "capture_decode: graph has a cross-device Op::Copy at \
1494                             node {:?} (target {:?}); capture requires a \
1495                             single-device CUDA decode step — only same-device \
1496                             CUDA→CUDA copies are capture-safe.",
1497                            item.node_id, target_location,
1498                        ))
1499                        .bt());
1500                    }
1501                }
1502                WorkItemKind::Kernel => {
1503                    if item.target_backend != BackendId::Cuda {
1504                        return Err(Error::Msg(format!(
1505                            "capture_decode: kernel node {:?} targets {:?}, not Cuda",
1506                            item.node_id, item.target_backend,
1507                        ))
1508                        .bt());
1509                    }
1510                    let compiled = item.compiled.as_ref().ok_or_else(|| {
1511                        Error::Msg(format!(
1512                            "capture_decode: kernel node {:?} has no compiled op",
1513                            item.node_id,
1514                        ))
1515                        .bt()
1516                    })?;
1517                    let op = compiled.op;
1518                    if !op_kind_is_capture_writeinto(op) {
1519                        return Err(Error::Msg(format!(
1520                            "capture_decode: op {:?} (node {:?}) has no write-into CUDA \
1521                             wrapper yet — capture unsupported for this op. Extend \
1522                             op_kind_is_capture_writeinto once its write-into variant lands.",
1523                            op, item.node_id,
1524                        ))
1525                        .bt());
1526                    }
1527                    // Concat's capture-safety is conditional on arity — N==2
1528                    // has a write-into path (concat2_into), N>2 does not (its
1529                    // wrapper falls back to an allocating N-1 chain). This
1530                    // can't be expressed by op_kind_is_capture_writeinto (a
1531                    // pure OpKind -> bool predicate with no OpParams access),
1532                    // so reject N>2 explicitly here, BEFORE the warm pass —
1533                    // see op_kind_is_capture_writeinto's doc comment.
1534                    if op == OpKind::Concat {
1535                        if let OpParams::Concat {
1536                            input_dim_sizes, ..
1537                        } = &compiled.op_params
1538                        {
1539                            if input_dim_sizes.len() != 2 {
1540                                return Err(Error::Msg(format!(
1541                                    "capture_decode: Concat node {:?} has {} inputs; only \
1542                                     2-input concat (the rope rotate-half shape) has a \
1543                                     write-into CUDA path today — N-ary (N>2) concat would \
1544                                     allocate mid-capture.",
1545                                    item.node_id,
1546                                    input_dim_sizes.len(),
1547                                ))
1548                                .bt());
1549                            }
1550                        }
1551                    }
1552                }
1553                // View / adopt / slot kinds: no alloc, no launch — capture-safe.
1554                _ => {}
1555            }
1556        }
1557
1558        // ---- Pass 1: warm (record) — fixed buffers + a synchronized result --
1559        let mut persistent = PersistentOutputs::recording();
1560        let mut warm_cache: StorageCache = inputs.clone();
1561        let mut warm_layouts = seed_layouts.clone();
1562        let mut warm_syms = SymEnv::new();
1563        let mut warm_devices = cuda_registry_of_inputs(&warm_cache);
1564        for item in &items {
1565            let _handle = execute_work_item(
1566                item,
1567                &mut warm_cache,
1568                &mut warm_devices,
1569                &mut warm_layouts,
1570                &mut warm_syms,
1571                false,
1572                Some(&mut persistent),
1573            )
1574            .map_err(|e| with_node_location(&graph, item.node_id, e))?;
1575        }
1576        // Flush all warm launches before capture (device idle; result stable).
1577        sync_active_cuda_devices(&warm_cache)?;
1578
1579        let output = warm_cache.get(&target).cloned().ok_or_else(|| {
1580            Error::Msg(format!(
1581                "capture_decode: target {:?} not realized in warm run",
1582                target,
1583            ))
1584            .bt()
1585        })?;
1586        let output_layout = warm_layouts.get(&target).cloned().ok_or_else(|| {
1587            Error::Msg(format!("capture_decode: target {:?} has no layout", target)).bt()
1588        })?;
1589
1590        // Derive the CUDA device from the target's storage for capture_run.
1591        let device = {
1592            let guard = output.read().map_err(|_| poisoned("output storage"))?;
1593            match &guard.inner {
1594                BackendStorage::Cuda(c) => c.device().clone(),
1595                other => {
1596                    return Err(Error::Msg(format!(
1597                        "capture_decode: target {:?} is BackendStorage::{:?}, not Cuda",
1598                        target,
1599                        other.backend_id(),
1600                    ))
1601                    .bt());
1602                }
1603            }
1604        };
1605
1606        // ---- Pass 2: capture (reuse) — record the launch sequence ----------
1607        let mut reuse = PersistentOutputs::reuse(persistent.into_map());
1608        // Retain EVERY input buffer before `inputs` is consumed: the captured
1609        // graph bakes their device addresses, so they must outlive it even if
1610        // the caller doesn't independently hold them.
1611        let retained_inputs: Vec<Arc<RwLock<Storage>>> = inputs.values().cloned().collect();
1612        let mut cap_cache: StorageCache = inputs;
1613        let mut cap_layouts = seed_layouts;
1614        let mut cap_syms = SymEnv::new();
1615        let mut cap_devices = cuda_registry_of_inputs(&cap_cache);
1616        let mut inner_err: Option<Error> = None;
1617        let items_ref = &items;
1618        let graph_ref = &graph;
1619        let run = device.capture_run(|_stream| {
1620            // Inside the capture scope: NO device alloc, NO host sync. Each
1621            // kernel launches on device.stream() (now capturing) and writes
1622            // into its reused fixed buffer.
1623            for item in items_ref {
1624                match execute_work_item(
1625                    item,
1626                    &mut cap_cache,
1627                    &mut cap_devices,
1628                    &mut cap_layouts,
1629                    &mut cap_syms,
1630                    false,
1631                    Some(&mut reuse),
1632                ) {
1633                    Ok(_handle) => {}
1634                    Err(e) => {
1635                        inner_err = Some(with_node_location(graph_ref, item.node_id, e));
1636                        break;
1637                    }
1638                }
1639            }
1640            Ok(())
1641        })?;
1642        if let Some(e) = inner_err {
1643            return Err(e);
1644        }
1645
1646        Ok(CapturedDecode {
1647            run,
1648            output,
1649            output_layout,
1650            retained_inputs,
1651            persistent: reuse.into_map(),
1652        })
1653    }
1654
1655    fn realize_inner(
1656        graph: Arc<RwLock<Graph>>,
1657        target: NodeId,
1658        inputs: StorageCache,
1659        order_source: OrderSource<'_>,
1660        sym_env: SymEnv,
1661    ) -> Result<(Arc<RwLock<Storage>>, Layout, SymEnv)> {
1662        Self::realize_inner_with(
1663            graph,
1664            target,
1665            inputs,
1666            order_source,
1667            sym_env,
1668            DeviceRegistry::new(),
1669        )
1670    }
1671
1672    /// [`Self::realize_inner`] with the device handles the caller already holds.
1673    fn realize_inner_with(
1674        graph: Arc<RwLock<Graph>>,
1675        target: NodeId,
1676        inputs: StorageCache,
1677        order_source: OrderSource<'_>,
1678        sym_env: SymEnv,
1679        device_handles: DeviceRegistry,
1680    ) -> Result<(Arc<RwLock<Storage>>, Layout, SymEnv)> {
1681        // Auto-insert safety copies for in-place ops whose target
1682        // has additional readers in this realize set (residual-
1683        // connection cycle break). No-op when no destructive ops
1684        // are present.
1685        {
1686            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.safety_copies");
1687            let mut g = graph.write().map_err(|_| poisoned("graph lock"))?;
1688            let effective_roots = extend_with_side_effect_roots(&g, &[target]);
1689            insert_safety_copies(&mut g, &effective_roots);
1690        }
1691
1692        // Execution plan + initial layouts for the input cache
1693        // entries, computed on the calling thread to keep the
1694        // compiler thread free of graph-locking responsibilities.
1695        // Side-effect roots (Op::Print, Op::Save, etc.) are merged
1696        // into the walk so their effects fire even when not
1697        // reachable from the user's `target`. `execution_plan`
1698        // integrates `derive_ordering`'s view-aware pinning so
1699        // destructive ops run AFTER non-destructive readers of
1700        // their targets.
1701        let (compiler_work, wait_set, mut layout_cache): (
1702            CompilerWork,
1703            WaitSet,
1704            HashMap<NodeId, Layout>,
1705        ) = {
1706            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.plan_order");
1707            let g = graph.read().map_err(|_| poisoned("graph lock"))?;
1708            let effective_roots = extend_with_side_effect_roots(&g, &[target]);
1709            // PR-A3b-1: the OptimizedGraph path lowers via
1710            // `extract_runs`/`lower_run` (computed here, AFTER
1711            // `insert_safety_copies`, so the order covers freshly
1712            // inserted safety-copy nodes). The default path keeps the
1713            // pre-A3b-1 `execution_plan` walk. On a branchless graph the
1714            // two sequences are identical (A3a equivalence gate).
1715            //
1716            // PR-C1: a `Streaming` source is NOT flattened here — it is
1717            // handed to the compiler thread as a `CompilerWork::Streaming`
1718            // spec so the thread resolves each branch lazily at the
1719            // frontier (see `compiler_thread_body`).
1720            //
1721            // Step E A4b open question #4: the SAME pass also derives the
1722            // `WaitSet` from the materialized order ("event only where
1723            // waited" — see `compiler_work_and_wait_set_for`).
1724            let (work, wait_set) =
1725                compiler_work_and_wait_set_for(&g, &effective_roots, &order_source);
1726            let mut layouts = HashMap::with_capacity(inputs.len());
1727            for &id in inputs.keys() {
1728                layouts.insert(id, g.layout(id));
1729            }
1730            (work, wait_set, layouts)
1731        };
1732
1733        let (tx, rx) = channel::<Result<WorkItem>>();
1734        let graph_for_compiler = Arc::clone(&graph);
1735
1736        // Compiler thread: read graph nodes, resolve kernels,
1737        // push WorkItems. On error, push the error and bail. PR-C1: for a
1738        // `Streaming` work spec the thread also resolves each branch's arm
1739        // at the frontier (the SAME VRAM-only selector the one-shot picker
1740        // uses) before compiling that arm's runs.
1741        let compiler = {
1742            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.spawn_compiler");
1743            thread::spawn(move || {
1744                let _t = crate::compiled::op_profile::PhaseTimer::start(
1745                    "compiler_thread (runs concurrently)",
1746                );
1747                compiler_thread_body(graph_for_compiler, compiler_work, sym_env, tx);
1748            })
1749        };
1750
1751        // Executor on this thread: consume WorkItems, gather
1752        // inputs from the cache, allocate outputs, call kernels,
1753        // populate the cache. After each destructive op
1754        // (Op::Release / Op::Move) evict the destroyed input from
1755        // the cache, unless it's the realize target.
1756        //
1757        // Phase 4.3: at each dispatch-chunk boundary (target_backend
1758        // change), check the live SystemTopology generation against
1759        // the plan's stamped generation. Mismatch surfaces
1760        // `Error::TopologyChanged`; the realize layer
1761        // (`pipelined_bridge`) catches it, rebuilds the plan against
1762        // the fresh topology, and retries.
1763        let plan_generation: Option<u64> = generation_for(&order_source);
1764        let mut current_chunk_backend: Option<BackendId> = None;
1765        let mut cache: StorageCache = inputs;
1766        let mut devices = device_handles;
1767        // Data-dependent dynamic-shapes: symbols BOUND BY PRODUCERS during
1768        // this pass (e.g. `Op::NonZeroIndices`'s runtime count). Distinct
1769        // from the compile-time `sym_env` (input-determined, moved into the
1770        // compiler thread): these become known only as ops execute. Returned
1771        // to the caller so a downstream pass can consume them.
1772        let mut produced_syms = SymEnv::new();
1773        // Step E A4b-1: per-node async-completion handles. Each producing node's
1774        // `execute_compiled` returns a `CompletionHandle` (CUDA → a recorded
1775        // `Event`; CPU/Vulkan → `Ready`) instead of being `wait`ed inline. We
1776        // store them here, wait the SOURCE producer's handle before a
1777        // cross-device copy (A4b-3, below), and drain whatever remains at
1778        // realize-end.
1779        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
1780        // Step E A4b-4: eagerly-submitted-but-not-yet-waited Vulkan batches. The
1781        // OVERLAP enabler — when we LEAVE a Vulkan chunk (or are about to block on
1782        // a CUDA copy) we `submit_pending` the open Vulkan batch so the iGPU runs
1783        // it while the executor records/dispatches the next (CUDA) chunk, instead
1784        // of letting it sit merely-recorded until realize-end (the A4b-2 behavior,
1785        // which never overlapped). Each submitted batch is tracked here and waited
1786        // at the in-flight-lifetime guard (before a Vulkan read / Vulkan-referenced
1787        // eviction / realize-end). `multi_backend` gates ALL eager submits so a
1788        // single-device realize never touches this path (byte-identical to A4b-2).
1789        let mut inflight_vulkan: Vec<InflightVulkan> = Vec::new();
1790        // Step E A4b-4: set true the first time the dispatch order transitions
1791        // between two DIFFERENT non-CPU... actually any two distinct backends — a
1792        // genuine backend switch. On a pure-CUDA or pure-Vulkan graph there is no
1793        // switch, so this stays false and the eager-submit / in-flight machinery is
1794        // unreachable (single-device byte-identical + throughput-neutral, §5).
1795        let mut multi_backend = false;
1796        let loop_total = crate::compiled::op_profile::PhaseTimer::start("realize.loop_total");
1797        loop {
1798            let t_wait =
1799                crate::compiled::op_profile::PhaseTimer::start("realize.wait_for_compiler");
1800            let Ok(item) = rx.recv() else {
1801                break;
1802            };
1803            drop(t_wait);
1804            let item = item?;
1805            // Chunk-boundary hook (target_backend change). Existing duty: the
1806            // `TopologyChanged` generation check. Step E A4b-4 adds two duties:
1807            // (1) detect a genuine backend switch → arm `multi_backend`; (2) when
1808            // LEAVING a Vulkan chunk on a multi-backend graph, eager-submit the
1809            // open Vulkan batch so the iGPU starts it concurrently with the chunk
1810            // we are about to dispatch (the overlap win).
1811            if !is_backend_neutral(&item.kind) && current_chunk_backend != Some(item.target_backend)
1812            {
1813                if let Some(plan_gen) = plan_generation {
1814                    let live = crate::dispatch::topology_generation();
1815                    if live != plan_gen {
1816                        return Err(Error::TopologyChanged {
1817                            plan_generation: plan_gen,
1818                            current_generation: live,
1819                        }
1820                        .bt());
1821                    }
1822                }
1823                let leaving = current_chunk_backend;
1824                if let Some(prev) = leaving
1825                    && prev != item.target_backend
1826                {
1827                    // A real backend switch occurred — this realize is
1828                    // genuinely multi-backend.
1829                    multi_backend = true;
1830                    // Leaving a Vulkan chunk → submit it NOW so it runs on the
1831                    // iGPU while we record/dispatch the next chunk. Whole-chunk
1832                    // granularity (the open batch IS the just-finished Vulkan
1833                    // chunk with all its intra-CB barriers) — UAF/race-safe per
1834                    // `eager_submit_all_vulkan`'s contract.
1835                    if prev == BackendId::Vulkan {
1836                        {
1837                            let _pt = crate::compiled::op_profile::PhaseTimer::start(
1838                                "realize.eager_submit_vulkan",
1839                            );
1840                            eager_submit_all_vulkan(&cache, &mut inflight_vulkan)?;
1841                        }
1842                    }
1843                }
1844                current_chunk_backend = Some(item.target_backend);
1845            }
1846            // Vulkan realizes run the async path (deferred eviction, size-based eager
1847            // submit) even on a single device: ordering between batches is structural
1848            // (inter-batch barrier + epoch-gated buffer reuse), not a host wait.
1849            if item.target_backend == BackendId::Vulkan && matches!(item.kind, WorkItemKind::Kernel)
1850            {
1851                multi_backend = true;
1852            }
1853            // Same-device cross-chunk RAW/WAR safety between Vulkan batches (the old
1854            // "Invariant E": wait every in-flight Vulkan batch on the HOST before
1855            // recording a new Vulkan op) is now structural: the Vulkan recorder
1856            // starts every batch with a memory barrier whose first scope covers all
1857            // earlier submissions on the queue (`Recorder::record_inter_batch_barrier`),
1858            // so a later batch cannot read or overwrite what an earlier in-flight
1859            // one is still using. The host therefore keeps recording while the
1860            // GPU runs the batches already submitted; waits remain only where the
1861            // host needs a result (D2H reads), before freeing a buffer, and at
1862            // realize-end.
1863            // Step E A4b-3 + A4b-4: the cross-device residency boundary.
1864            if matches!(
1865                item.kind,
1866                WorkItemKind::Copy { .. } | WorkItemKind::Move { .. }
1867            ) {
1868                // A4b-4: before we (possibly) block the host on the CUDA producer,
1869                // eager-submit any open Vulkan chunk so the iGPU runs it WHILE we
1870                // wait on CUDA (the §5.1 ordering — submit Vulkan *before* draining
1871                // CUDA). Cheap + safe; gated to multi-backend (no-op single-device).
1872                if multi_backend {
1873                    {
1874                        let _pt = crate::compiled::op_profile::PhaseTimer::start(
1875                            "realize.eager_submit_vulkan",
1876                        );
1877                        eager_submit_all_vulkan(&cache, &mut inflight_vulkan)?;
1878                    }
1879                }
1880                if let Some(&producer) = item.inputs.first() {
1881                    // A4b-4: a VULKAN-source D2H must read COMPLETED data, and the
1882                    // Vulkan download path only flushes the OPEN batch (not our
1883                    // in-flight ones) — so wait the in-flight Vulkan batches here.
1884                    // For a CUDA/CPU source we do NOT wait Vulkan (the copy reads no
1885                    // Vulkan buffer); waiting it would needlessly serialize the
1886                    // independent Vulkan sub-DAG and kill the overlap. The Vulkan
1887                    // work that was eager-submitted at the chunk boundary keeps
1888                    // running concurrently until ITS result is the one being copied.
1889                    if multi_backend && copy_source_is_vulkan(&cache, producer)? {
1890                        {
1891                            let _pt = crate::compiled::op_profile::PhaseTimer::start(
1892                                "realize.drain_inflight_vulkan",
1893                            );
1894                            drain_inflight_vulkan(&mut inflight_vulkan)?;
1895                        }
1896                    }
1897                    // Step E A4b-3: FINER CUDA source-drain — wait ONLY the source
1898                    // producer's recorded event (not the whole source device), so
1899                    // the OTHER sub-DAG's independent in-flight CUDA work keeps
1900                    // running. No-op for a Vulkan/CPU producer (no CUDA handle).
1901                    wait_producer_handle(&mut handles, producer)?;
1902                }
1903            }
1904            let t_exec =
1905                crate::compiled::op_profile::PhaseTimer::start(work_item_kind_name(&item.kind));
1906            let handle = execute_work_item(
1907                &item,
1908                &mut cache,
1909                &mut devices,
1910                &mut layout_cache,
1911                &mut produced_syms,
1912                will_be_waited(&wait_set, item.node_id),
1913                // No persistent-output mode on the standard realize paths —
1914                // fresh alloc per node, byte-identical to pre-CapturedRun.
1915                None,
1916            )
1917            .map_err(|e| with_node_location(&graph, item.node_id, e))?;
1918            drop(t_exec);
1919            store_handle(&mut handles, item.node_id, handle);
1920            if let Some(d_idx) = item.destructive_input
1921                && let Some(&destroyed) = item.inputs.get(d_idx)
1922                && destroyed != target
1923            {
1924                // Step E A2.1 (in-flight-batch DATA-BUFFER lifetime — the
1925                // UAF guard, now DEFERRED-DELETION instead of a drain). A
1926                // `SubmittedBatch` owns its CB/descriptors/transients but
1927                // NOT the DATA buffers it reads (those live here in the
1928                // cache); recycling a data buffer an in-flight/open CB still
1929                // reads is a use-after-free. PRE-A2.1 we host-blocked here —
1930                // `drain_inflight_vulkan` (wait every in-flight batch) +
1931                // `force_flush` (submit+wait the open batch) — which stalled
1932                // the iGPU work we were overlapping with CUDA at EVERY such
1933                // eviction. A2.1 instead RETAINS the evicted buffer until the
1934                // reader fences signal: it eager-submits the open batch (no
1935                // wait → it becomes a fenced in-flight batch) and moves a
1936                // refcount clone of the buffer into every in-flight batch, so
1937                // the buffer frees POST-fence on each batch's `Drop`
1938                // (follow-on #2) with NO host block. Conservative over all
1939                // batches (no cheap buffer→batch map — the same reason the old
1940                // drain waited all of them). CUDA eviction is stream-ordered-
1941                // safe via A3. Single-device (multi_backend == false) keeps the
1942                // pre-A2.1 blocking force_flush of the OPEN batch (the else
1943                // branch) — byte-identical + UAF-safe there; the deferred path is
1944                // unsafe single-device (no eager-submit/in-flight tracking, and the
1945                // cross-batch RAW guard at :832 doesn't run — see
1946                // force_flush_vulkan's doc).
1947                let _t =
1948                    crate::compiled::op_profile::PhaseTimer::start("realize.evict_destroyed_input");
1949                if multi_backend {
1950                    defer_evicted_vulkan_buffer(&cache, destroyed, &mut inflight_vulkan)?;
1951                } else if let Some(d_arc) = cache.get(&destroyed) {
1952                    let _f = crate::compiled::op_profile::PhaseTimer::start(
1953                        "realize.evict_force_flush_vulkan",
1954                    );
1955                    force_flush_vulkan(d_arc)?;
1956                }
1957                cache.remove(&destroyed);
1958                layout_cache.remove(&destroyed);
1959                // Drop the evicted node's CUDA handle (if still present)
1960                // so the realize-end drain's empty-map assert stays
1961                // meaningful. The free itself is stream-ordered-safe (A3).
1962                handles.remove(&destroyed);
1963            }
1964        }
1965
1966        drop(loop_total);
1967        {
1968            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.join_compiler");
1969            compiler
1970                .join()
1971                .map_err(|_| Error::Msg("compiler thread panicked".to_string()).bt())?;
1972        }
1973
1974        // Step E A4b-1: drain every outstanding async handle before the result is
1975        // read / the cache drops (freeing intermediates). For CUDA this waits the
1976        // recorded events (one stream/device ⇒ waiting the latest drains all prior
1977        // stream work too; see `drain_handles`).
1978        let post_loop = crate::compiled::op_profile::PhaseTimer::start("realize.post_loop_drains");
1979        drain_handles(&mut handles)?;
1980        // Step E A4b open question #4 — "event only where waited": most CUDA
1981        // nodes in this realize never got an Event (elided per the `WaitSet`),
1982        // so `drain_handles` above only retired the (typically few) tracked
1983        // handles. This blanket per-device `cuStreamSynchronize` flushes the
1984        // elided work too — safe + sufficient because of single-stream-per-
1985        // device ordering (see `sync_active_cuda_devices`'s doc).
1986        sync_active_cuda_devices(&cache)?;
1987        // Step E A4b-4: wait every eagerly-submitted (in-flight) Vulkan batch
1988        // before the cache drops, freeing the data buffers their CBs read. Empty
1989        // on a single-device realize (nothing was eager-submitted).
1990        {
1991            let _pt =
1992                crate::compiled::op_profile::PhaseTimer::start("realize.drain_inflight_vulkan");
1993            drain_inflight_vulkan(&mut inflight_vulkan)?;
1994        }
1995        // Step E A4b-2: drain all deferred Vulkan work before reading/returning
1996        // the result (and before the cache drops, freeing buffers). The A2
1997        // submit+wait is now SPLIT — `drain_vulkan_pending` submits the open
1998        // batch then waits it via a `VulkanCompletion` handle. Byte-identical to
1999        // A2 for pure-Vulkan (one submission at realize-end, just split).
2000        drain_vulkan_pending(&cache)?;
2001        debug_assert!(
2002            inflight_vulkan.is_empty(),
2003            "A4b-4: in-flight Vulkan batch list must be empty after realize-end drain",
2004        );
2005
2006        drop(post_loop);
2007        let storage = cache.remove(&target).ok_or_else(|| {
2008            Error::Msg(format!(
2009                "PipelinedExecutor::realize: target slot {:?} not populated after execution",
2010                target
2011            ))
2012            .bt()
2013        })?;
2014        let layout = layout_cache.remove(&target).ok_or_else(|| {
2015            Error::Msg(format!(
2016                "PipelinedExecutor::realize: target layout {:?} not populated after execution",
2017                target
2018            ))
2019            .bt()
2020        })?;
2021        {
2022            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.drop_cache");
2023            drop(cache);
2024            drop(handles);
2025            drop(layout_cache);
2026        }
2027        Ok((storage, layout, produced_syms))
2028    }
2029
2030    /// Realize multiple targets in one walk. Each target's transitive
2031    /// dependency set is collapsed into a single execution plan
2032    /// (via [`execution_plan`]); shared subgraphs are evaluated
2033    /// once. Returns a `Vec<(Storage, Layout)>` whose order matches
2034    /// `targets`.
2035    ///
2036    /// This is Phase A of Phase 7.6 step 9c — feature-parity with the
2037    /// legacy `GraphExecutor::realize_many_f32`. Multi-session
2038    /// migration target ([memory: project_phase_7_6_step_9c_parity_audit.md]).
2039    ///
2040    /// Pre-conditions: every reachable `Op::Const` must be in
2041    /// `inputs`; every reachable non-`Const` must have its
2042    /// `target_backend` set; the op + dtype must be registered in
2043    /// `global_bindings()`. Same as single-target [`Self::realize`].
2044    pub fn realize_many(
2045        graph: Arc<RwLock<Graph>>,
2046        targets: &[NodeId],
2047        inputs: StorageCache,
2048    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2049        Self::realize_many_inner(
2050            graph,
2051            targets,
2052            inputs,
2053            OrderSource::Default,
2054            SymEnv::default(),
2055        )
2056    }
2057
2058    /// [`Self::realize_many`] with the device handles the caller already holds (ROADMAP row 137, seam S3
2059    /// step 3b).
2060    pub fn realize_many_with_devices(
2061        graph: Arc<RwLock<Graph>>,
2062        targets: &[NodeId],
2063        inputs: StorageCache,
2064        devices: DeviceRegistry,
2065    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2066        Self::realize_many_inner_with(
2067            graph,
2068            targets,
2069            inputs,
2070            OrderSource::Default,
2071            SymEnv::default(),
2072            devices,
2073        )
2074    }
2075
2076    /// [`Self::realize_many_with_optimized_picking_env`] with the device handles the caller already holds.
2077    #[allow(clippy::too_many_arguments)]
2078    pub fn realize_many_with_optimized_picking_env_with_devices(
2079        graph: Arc<RwLock<Graph>>,
2080        targets: &[NodeId],
2081        inputs: StorageCache,
2082        optimized: &OptimizedGraph,
2083        selector: Option<Arc<dyn RuntimeSelector>>,
2084        lookup: Option<BackendRuntimeLookup>,
2085        sym_env: SymEnv,
2086        devices: DeviceRegistry,
2087    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2088        let order_source = match Self::streaming_pick_for(&graph, selector, lookup)? {
2089            Some(pick) => {
2090                return Self::realize_many_inner_with(
2091                    graph,
2092                    targets,
2093                    inputs,
2094                    OrderSource::Streaming {
2095                        optimized,
2096                        pick: &pick,
2097                    },
2098                    sym_env,
2099                    devices,
2100                );
2101            }
2102            None => OrderSource::Optimized {
2103                optimized,
2104                route: None,
2105            },
2106        };
2107        Self::realize_many_inner_with(graph, targets, inputs, order_source, sym_env, devices)
2108    }
2109
2110    /// Multi-target PR-A3b-1 entry — the `realize_many` sibling of
2111    /// [`Self::realize_with_optimized`]. Drives the executor from the
2112    /// `OptimizedGraph`'s run lowering via the binding-table-lookup
2113    /// path, with the optimize-time `generation` keying the
2114    /// `TopologyChanged` chunk-boundary check.
2115    pub fn realize_many_with_optimized(
2116        graph: Arc<RwLock<Graph>>,
2117        targets: &[NodeId],
2118        inputs: StorageCache,
2119        optimized: &OptimizedGraph,
2120    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2121        Self::realize_many_inner(
2122            graph,
2123            targets,
2124            inputs,
2125            OrderSource::Optimized {
2126                optimized,
2127                route: None,
2128            },
2129            SymEnv::default(),
2130        )
2131    }
2132
2133    /// Env-carrying sibling of [`Self::realize_many_with_optimized`] (Phase D
2134    /// symbolic extents). An empty env is byte-identical to it.
2135    pub fn realize_many_with_optimized_env(
2136        graph: Arc<RwLock<Graph>>,
2137        targets: &[NodeId],
2138        inputs: StorageCache,
2139        optimized: &OptimizedGraph,
2140        sym_env: SymEnv,
2141    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2142        Self::realize_many_inner(
2143            graph,
2144            targets,
2145            inputs,
2146            OrderSource::Optimized {
2147                optimized,
2148                route: None,
2149            },
2150            sym_env,
2151        )
2152    }
2153
2154    /// Multi-target PR-C1 entry — the `realize_many` sibling of
2155    /// [`Self::realize_with_optimized_route`]. Lowers each target's runs
2156    /// following the picker's chosen arms via
2157    /// [`fuel_graph::lower_picked_route`].
2158    pub fn realize_many_with_optimized_route(
2159        graph: Arc<RwLock<Graph>>,
2160        targets: &[NodeId],
2161        inputs: StorageCache,
2162        optimized: &OptimizedGraph,
2163        route: &PickedRoute,
2164    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2165        Self::realize_many_inner(
2166            graph,
2167            targets,
2168            inputs,
2169            OrderSource::Optimized {
2170                optimized,
2171                route: Some(route),
2172            },
2173            SymEnv::default(),
2174        )
2175    }
2176
2177    /// Env-carrying sibling of [`Self::realize_many_with_optimized_route`]
2178    /// (Phase D symbolic extents). An empty env is byte-identical to it.
2179    pub fn realize_many_with_optimized_route_env(
2180        graph: Arc<RwLock<Graph>>,
2181        targets: &[NodeId],
2182        inputs: StorageCache,
2183        optimized: &OptimizedGraph,
2184        route: &PickedRoute,
2185        sym_env: SymEnv,
2186    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2187        Self::realize_many_inner(
2188            graph,
2189            targets,
2190            inputs,
2191            OrderSource::Optimized {
2192                optimized,
2193                route: Some(route),
2194            },
2195            sym_env,
2196        )
2197    }
2198
2199    /// Multi-target sibling of [`Self::realize_with_optimized_picking_env`] —
2200    /// the executor resolves one arm per `Op::Branch` (cleanup Step C/D) over
2201    /// the effective targets. PR C1: a branched graph routes to the
2202    /// `OrderSource::Streaming` walk (lazy per-branch resolution at the
2203    /// frontier); branchless / no-selector falls to the untouched arm-0 path.
2204    pub fn realize_many_with_optimized_picking_env(
2205        graph: Arc<RwLock<Graph>>,
2206        targets: &[NodeId],
2207        inputs: StorageCache,
2208        optimized: &OptimizedGraph,
2209        selector: Option<Arc<dyn RuntimeSelector>>,
2210        lookup: Option<BackendRuntimeLookup>,
2211        sym_env: SymEnv,
2212    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2213        match Self::streaming_pick_for(&graph, selector, lookup)? {
2214            Some(pick) => Self::realize_many_inner(
2215                graph,
2216                targets,
2217                inputs,
2218                OrderSource::Streaming {
2219                    optimized,
2220                    pick: &pick,
2221                },
2222                sym_env,
2223            ),
2224            None => {
2225                Self::realize_many_with_optimized_env(graph, targets, inputs, optimized, sym_env)
2226            }
2227        }
2228    }
2229
2230    fn realize_many_inner(
2231        graph: Arc<RwLock<Graph>>,
2232        targets: &[NodeId],
2233        inputs: StorageCache,
2234        order_source: OrderSource<'_>,
2235        sym_env: SymEnv,
2236    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2237        Self::realize_many_inner_with(
2238            graph,
2239            targets,
2240            inputs,
2241            order_source,
2242            sym_env,
2243            DeviceRegistry::new(),
2244        )
2245    }
2246
2247    /// [`Self::realize_many_inner`] with the device handles the caller already holds.
2248    fn realize_many_inner_with(
2249        graph: Arc<RwLock<Graph>>,
2250        targets: &[NodeId],
2251        inputs: StorageCache,
2252        order_source: OrderSource<'_>,
2253        sym_env: SymEnv,
2254        device_handles: DeviceRegistry,
2255    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2256        if targets.is_empty() {
2257            return Ok(Vec::new());
2258        }
2259
2260        // Auto-insert safety copies for in-place ops whose target
2261        // has additional readers in this realize set (residual-
2262        // connection cycle break). No-op when no destructive ops
2263        // are present.
2264        {
2265            let mut g = graph.write().map_err(|_| poisoned("graph lock"))?;
2266            let effective_roots = extend_with_side_effect_roots(&g, targets);
2267            insert_safety_copies(&mut g, &effective_roots);
2268        }
2269
2270        // Execution plan covering every target's dependency set +
2271        // initial layouts for the input cache entries. Side-effect
2272        // roots merge in so their effects fire even when not
2273        // reachable from any target. `execution_plan` integrates
2274        // `derive_ordering`'s view-aware pinning so destructive ops
2275        // run AFTER non-destructive readers of their targets.
2276        let (compiler_work, wait_set, mut layout_cache): (
2277            CompilerWork,
2278            WaitSet,
2279            HashMap<NodeId, Layout>,
2280        ) = {
2281            let g = graph.read().map_err(|_| poisoned("graph lock"))?;
2282            let effective_roots = extend_with_side_effect_roots(&g, targets);
2283            // PR-A3b-1: derive from the OptimizedGraph's run lowering
2284            // when present (post-safety-copies); else the legacy
2285            // `execution_plan` walk. Identical on branchless graphs.
2286            //
2287            // PR-C1: a `Streaming` source is handed to the compiler thread
2288            // unflattened (resolves branches at the frontier).
2289            //
2290            // Step E A4b open question #4: also derives the `WaitSet`
2291            // ("event only where waited") from the same materialized order.
2292            let (work, wait_set) =
2293                compiler_work_and_wait_set_for(&g, &effective_roots, &order_source);
2294            let mut layouts = HashMap::with_capacity(inputs.len());
2295            for &id in inputs.keys() {
2296                layouts.insert(id, g.layout(id));
2297            }
2298            (work, wait_set, layouts)
2299        };
2300
2301        // Caller's target set — used to gate destructive-input
2302        // eviction so we don't drop a tensor the caller asked for.
2303        let target_set: std::collections::HashSet<NodeId> = targets.iter().copied().collect();
2304
2305        let (tx, rx) = channel::<Result<WorkItem>>();
2306        let graph_for_compiler = Arc::clone(&graph);
2307
2308        let compiler = thread::spawn(move || {
2309            compiler_thread_body(graph_for_compiler, compiler_work, sym_env, tx);
2310        });
2311
2312        // Phase 4.3: per-chunk SystemTopology generation check (see
2313        // realize_inner for the rationale). PR-A3b-1: the OptimizedGraph
2314        // path supplies its own optimize-time generation.
2315        let plan_generation: Option<u64> = generation_for(&order_source);
2316        let mut current_chunk_backend: Option<BackendId> = None;
2317        let mut cache: StorageCache = inputs;
2318        let mut devices = device_handles;
2319        // Data-dependent dynamic-shapes producer-bound symbols (see
2320        // `realize_inner`). `realize_many` does not expose them today; the
2321        // env is dropped at pass end (producers still publish, keeping the
2322        // seam uniform across both realize loops).
2323        let mut produced_syms = SymEnv::new();
2324        // Step E A4b-1/A4b-3: per-node async-completion handles (see realize_inner
2325        // for the full rationale). Map drained at realize-end; the cross-device
2326        // copy waits the SOURCE producer's handle (A4b-3).
2327        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
2328        // Step E A4b-4: eagerly-submitted in-flight Vulkan batches + the
2329        // multi-backend gate. See realize_inner for the full rationale — this is
2330        // the identical eager-submit / in-flight-lifetime machinery applied to the
2331        // multi-target walk. `multi_backend` arms on a genuine backend switch and
2332        // gates every eager submit, so a single-device realize_many is
2333        // byte-identical to A4b-2.
2334        let mut inflight_vulkan: Vec<InflightVulkan> = Vec::new();
2335        let mut multi_backend = false;
2336        for item in rx {
2337            let item = item?;
2338            // Chunk-boundary hook: TopologyChanged check + (A4b-4) backend-switch
2339            // detection + eager-submit-on-leaving-a-Vulkan-chunk.
2340            if !is_backend_neutral(&item.kind) && current_chunk_backend != Some(item.target_backend)
2341            {
2342                if let Some(plan_gen) = plan_generation {
2343                    let live = crate::dispatch::topology_generation();
2344                    if live != plan_gen {
2345                        return Err(Error::TopologyChanged {
2346                            plan_generation: plan_gen,
2347                            current_generation: live,
2348                        }
2349                        .bt());
2350                    }
2351                }
2352                let leaving = current_chunk_backend;
2353                if let Some(prev) = leaving
2354                    && prev != item.target_backend
2355                {
2356                    multi_backend = true;
2357                    if prev == BackendId::Vulkan {
2358                        eager_submit_all_vulkan(&cache, &mut inflight_vulkan)?;
2359                    }
2360                }
2361                current_chunk_backend = Some(item.target_backend);
2362            }
2363            // Vulkan realizes run the async path (deferred eviction, size-based eager
2364            // submit) even on a single device: ordering between batches is structural
2365            // (inter-batch barrier + epoch-gated buffer reuse), not a host wait.
2366            if item.target_backend == BackendId::Vulkan && matches!(item.kind, WorkItemKind::Kernel)
2367            {
2368                multi_backend = true;
2369            }
2370            // Inter-batch Vulkan ordering is structural (see realize_inner): no host
2371            // wait before recording a new Vulkan op.
2372            // Step E A4b-3 + A4b-4: cross-device residency boundary. See
2373            // realize_inner for the full rationale.
2374            if matches!(
2375                item.kind,
2376                WorkItemKind::Copy { .. } | WorkItemKind::Move { .. }
2377            ) {
2378                // A4b-4: submit any open Vulkan chunk so the iGPU runs while the
2379                // host (possibly) waits on the CUDA producer.
2380                if multi_backend {
2381                    eager_submit_all_vulkan(&cache, &mut inflight_vulkan)?;
2382                }
2383                if let Some(&producer) = item.inputs.first() {
2384                    // A4b-4: wait in-flight Vulkan ONLY for a Vulkan-source D2H
2385                    // (reads completed data; download flushes only the OPEN batch).
2386                    // A CUDA/CPU source does NOT wait Vulkan (preserves overlap).
2387                    if multi_backend && copy_source_is_vulkan(&cache, producer)? {
2388                        drain_inflight_vulkan(&mut inflight_vulkan)?;
2389                    }
2390                    // Step E A4b-3: finer CUDA source-drain — wait ONLY the producer.
2391                    wait_producer_handle(&mut handles, producer)?;
2392                }
2393            }
2394            let handle = execute_work_item(
2395                &item,
2396                &mut cache,
2397                &mut devices,
2398                &mut layout_cache,
2399                &mut produced_syms,
2400                will_be_waited(&wait_set, item.node_id),
2401                // No persistent-output mode on the standard realize paths —
2402                // fresh alloc per node, byte-identical to pre-CapturedRun.
2403                None,
2404            )
2405            .map_err(|e| with_node_location(&graph, item.node_id, e))?;
2406            store_handle(&mut handles, item.node_id, handle);
2407            if let Some(d_idx) = item.destructive_input
2408                && let Some(&destroyed) = item.inputs.get(d_idx)
2409                && !target_set.contains(&destroyed)
2410            {
2411                // Step E A2.1 (in-flight DATA-BUFFER lifetime — UAF guard,
2412                // now DEFERRED-DELETION instead of a drain): retain the
2413                // evicted buffer until the reader fences signal — eager-
2414                // submit the open batch (no wait) + move a refcount clone of
2415                // the buffer into every in-flight batch, freeing it post-
2416                // fence on each batch's `Drop` with NO host block. Replaces
2417                // the pre-A2.1 `drain_inflight_vulkan` + open-batch
2418                // `force_flush` (two host-blocking fence waits). See
2419                // `defer_evicted_vulkan_buffer` / realize_inner for the
2420                // UAF/leak argument. CUDA eviction is A3 stream-safe.
2421                // Single-device (multi_backend == false) keeps the pre-A2.1
2422                // blocking force_flush of the OPEN batch (the else branch) —
2423                // byte-identical + UAF-safe; the deferred path is unsafe there
2424                // (see force_flush_vulkan's doc).
2425                if multi_backend {
2426                    defer_evicted_vulkan_buffer(&cache, destroyed, &mut inflight_vulkan)?;
2427                } else if let Some(d_arc) = cache.get(&destroyed) {
2428                    force_flush_vulkan(d_arc)?;
2429                }
2430                cache.remove(&destroyed);
2431                layout_cache.remove(&destroyed);
2432                // CUDA eviction is stream-ordered-safe (A3); drop the
2433                // handle so the realize-end empty-map assert stays valid.
2434                handles.remove(&destroyed);
2435            }
2436        }
2437
2438        compiler
2439            .join()
2440            .map_err(|_| Error::Msg("compiler thread panicked".to_string()).bt())?;
2441
2442        // Step E A4b-1: drain every outstanding async handle (CUDA events) before
2443        // results are read / the cache drops.
2444        drain_handles(&mut handles)?;
2445        // Step E A4b open question #4: blanket per-device stream sync for the
2446        // elided nodes `drain_handles` never tracked — see `realize_inner`'s
2447        // identical comment / `sync_active_cuda_devices`'s doc for the argument.
2448        sync_active_cuda_devices(&cache)?;
2449        // Step E A4b-4: wait every eagerly-submitted in-flight Vulkan batch before
2450        // the cache drops. Empty on a single-device realize.
2451        drain_inflight_vulkan(&mut inflight_vulkan)?;
2452        // Step E A4b-2: drain all deferred Vulkan work — submit the open batch
2453        // then wait it via a `VulkanCompletion` handle (the A2 submit+wait, split;
2454        // byte-identical for pure-Vulkan — one submission at realize-end).
2455        drain_vulkan_pending(&cache)?;
2456        debug_assert!(
2457            inflight_vulkan.is_empty(),
2458            "A4b-4: in-flight Vulkan batch list must be empty after realize-end drain",
2459        );
2460
2461        // Verify every target was realized + collect outputs in
2462        // target order. We don't `remove` from the cache because the
2463        // same NodeId can appear twice in `targets` (caller wants the
2464        // same storage twice) — clone the Arc instead.
2465        let mut out = Vec::with_capacity(targets.len());
2466        for &target in targets {
2467            let storage = cache.get(&target).cloned().ok_or_else(|| {
2468                Error::Msg(format!(
2469                    "PipelinedExecutor::realize_many: target {:?} not populated after execution",
2470                    target
2471                ))
2472                .bt()
2473            })?;
2474            let layout = layout_cache.get(&target).cloned().ok_or_else(|| {
2475                Error::Msg(format!(
2476                    "PipelinedExecutor::realize_many: target layout {:?} not populated after execution",
2477                    target
2478                ))
2479                .bt()
2480            })?;
2481            out.push((storage, layout));
2482        }
2483        Ok(out)
2484    }
2485}
2486
2487/// Resolve the executor's dispatch order from the configured
2488/// [`OrderSource`]. PR-A3b-1: `Optimized` lowers the in-place
2489/// "plan IS the graph" form via `extract_runs`/`lower_run`; `Default`
2490/// keeps the pre-A3b-1 `execution_plan` walk. Both produce the same
2491/// `NodeId` sequence on a branchless graph (A3a equivalence gate),
2492/// computed here AFTER safety-copy insertion so either path covers
2493/// any freshly inserted copies.
2494fn order_for(
2495    graph: &Graph,
2496    effective_roots: &[NodeId],
2497    order_source: &OrderSource<'_>,
2498) -> Vec<NodeId> {
2499    match order_source {
2500        OrderSource::Default => execution_plan(graph, effective_roots),
2501        // The streaming walk is driven in the compiler thread (it
2502        // interleaves arm resolution with compilation), so `order_for`
2503        // never flattens it on the production path. This arm exists only
2504        // for match totality / non-pipelined callers: it collects the SAME
2505        // lazily-resolved order eagerly (the streaming walk with the same
2506        // `resolve_branch` over the threaded selector), which equals the
2507        // one-shot `lower_picked_route(pick_route(..))` order.
2508        OrderSource::Streaming {
2509            optimized: _optimized,
2510            pick,
2511        } => {
2512            let bindings = global_bindings();
2513            fuel_graph::lower_picked_route_streaming(graph, effective_roots, |branch| {
2514                resolve_branch(graph, branch, &bindings, pick.selector.as_ref())
2515            })
2516        }
2517        OrderSource::Optimized { optimized, route } => {
2518            // Lower the runs over the *effective* roots (user targets +
2519            // any spliced/side-effect roots) so the order matches the
2520            // walk's reachable set rather than only the optimize-time
2521            // roots. On a branchless graph this is the same concatenated
2522            // `lower_run` sequence the OptimizedGraph reports.
2523            //
2524            // PR-C1: when the picker supplied a route, follow the chosen
2525            // arms (`lower_picked_route`); otherwise the arm-0 lowering
2526            // (`OptimizedGraph::dispatch_order`). An empty route is
2527            // byte-identical to arm-0, so the two paths agree whenever
2528            // the picker chose arm-0 everywhere (the no-pressure case).
2529            match route {
2530                Some(route) => fuel_graph::lower_picked_route(graph, effective_roots, route),
2531                None => {
2532                    // A transient view built solely to call `dispatch_order`;
2533                    // it does no planning, so it carries no placements. The
2534                    // real optimization's map lives on `optimized`.
2535                    let view = OptimizedGraph {
2536                        roots: effective_roots.to_vec(),
2537                        generation: optimized.generation,
2538                        placements: None,
2539                        eviction: None,
2540                    };
2541                    view.dispatch_order(graph)
2542                }
2543            }
2544        }
2545        // Resolved by `compiler_work_and_wait_set_for` before delegating
2546        // here (the whole point of `Cached` is to skip this computation
2547        // on a hit) — never reached. Kept exhaustive rather than wildcarded
2548        // so a future `OrderSource` variant can't silently fall through.
2549        OrderSource::Cached { .. } => {
2550            unreachable!("OrderSource::Cached is resolved before order_for is called")
2551        }
2552    }
2553}
2554
2555/// Step E A4b open question #4 — "event only where waited". The producer
2556/// [`NodeId`]s that some later `Op::Copy`/`Op::Move` node in `order` will
2557/// `wait_producer_handle` on (the executor's cross-device residency
2558/// boundary — see `wait_producer_handle`, whose `item.inputs.first()` read
2559/// this mirrors exactly). A CUDA node whose id is absent from the returned
2560/// set has NO mid-walk reader: same-device consumers are correct via stream
2561/// ordering alone (they never `wait`), and nothing touches its handle before
2562/// the realize-end drain, so [`crate::compiled::execute_compiled_with_wait_hint`]
2563/// can skip recording an `Event` for it entirely.
2564///
2565/// Requires a materialized `order` (works for [`OrderSource::Default`] /
2566/// [`OrderSource::Optimized`], whose [`CompilerWork::Order`] is a frozen
2567/// `Vec<NodeId>` computed up front) — see
2568/// [`compiler_work_and_wait_set_for`] for the [`OrderSource::Streaming`]
2569/// fallback.
2570fn build_wait_set(graph: &Graph, order: &[NodeId]) -> HashSet<NodeId> {
2571    let mut set = HashSet::new();
2572    for &id in order {
2573        let node = graph.node(id);
2574        if matches!(node.op, Op::Copy { .. } | Op::Move { .. })
2575            && let Some(&producer) = node.inputs.first()
2576        {
2577            set.insert(producer);
2578        }
2579    }
2580    set
2581}
2582
2583/// Step E A4b open question #4: the executor's per-realize wait-set.
2584/// `None` is the CONSERVATIVE fallback — every CUDA node still gets an Event
2585/// (today's pre-elision behavior, byte-identical). `Some(set)` restricts
2586/// event production to `set`'s members ([`build_wait_set`]'s output);
2587/// everything else gets `CompletionHandle::Ready` with no Event recorded.
2588type WaitSet = Option<HashSet<NodeId>>;
2589
2590/// Whether `node_id`'s completion handle must be individually observable
2591/// (i.e. `execute_compiled_with_wait_hint`'s `will_be_waited`). `None` (the
2592/// [`OrderSource::Streaming`] fallback — never elides) is always `true`.
2593#[inline]
2594fn will_be_waited(wait_set: &WaitSet, node_id: NodeId) -> bool {
2595    match wait_set {
2596        None => true,
2597        Some(set) => set.contains(&node_id),
2598    }
2599}
2600
2601/// Build the [`CompilerWork`] the compiler thread walks for the configured
2602/// [`OrderSource`], plus the [`WaitSet`] "event only where waited" (open
2603/// question #4) consults. The non-streaming sources flatten up front via
2604/// [`order_for`] (unchanged) and the SAME materialized order feeds
2605/// [`build_wait_set`], so the pre-scan and the dispatch order never
2606/// disagree. [`OrderSource::Streaming`] is handed to the compiler thread as
2607/// a [`CompilerWork::Streaming`] spec — NOT flattened here — so the thread
2608/// resolves branches lazily at the frontier (Step E Phase C, PR C1); the lazy
2609/// order can't be pre-scanned without eagerly resolving it (which would
2610/// defeat the point of streaming), so it falls back to the conservative
2611/// `WaitSet::None` — event every node, unchanged behavior. Holds the graph
2612/// read-lock only for the flattening branches; the streaming branch defers
2613/// the lock to the compiler thread.
2614fn compiler_work_and_wait_set_for(
2615    graph: &Graph,
2616    effective_roots: &[NodeId],
2617    order_source: &OrderSource<'_>,
2618) -> (CompilerWork, WaitSet) {
2619    match order_source {
2620        OrderSource::Streaming { pick, .. } => (
2621            CompilerWork::Streaming {
2622                roots: effective_roots.to_vec(),
2623                pick: (*pick).clone(),
2624            },
2625            None,
2626        ),
2627        OrderSource::Cached {
2628            optimized,
2629            order_cache,
2630        } => {
2631            let order = order_cache.get_or_init(|| {
2632                order_for(
2633                    graph,
2634                    effective_roots,
2635                    &OrderSource::Optimized {
2636                        optimized,
2637                        route: None,
2638                    },
2639                )
2640            });
2641            let wait_set = build_wait_set(graph, order);
2642            (CompilerWork::Order(order.clone()), Some(wait_set))
2643        }
2644        other => {
2645            let order = order_for(graph, effective_roots, other);
2646            let wait_set = build_wait_set(graph, &order);
2647            (CompilerWork::Order(order), Some(wait_set))
2648        }
2649    }
2650}
2651
2652/// The topology generation that keys the executor's `TopologyChanged`
2653/// chunk-boundary check. Uses the `OptimizedGraph`'s optimize-time
2654/// generation (PR-A3b-1 path). `None` ⇒ no check (the plain
2655/// `realize`/`realize_many` entries).
2656fn generation_for(order_source: &OrderSource<'_>) -> Option<u64> {
2657    match order_source {
2658        OrderSource::Optimized { optimized, .. } => Some(optimized.generation),
2659        OrderSource::Streaming { optimized, .. } => Some(optimized.generation),
2660        OrderSource::Cached { optimized, .. } => Some(optimized.generation),
2661        OrderSource::Default => None,
2662    }
2663}
2664
2665/// What the compiler thread walks: either a pre-flattened dispatch
2666/// `Order` (the `Default` / `Optimized` paths — unchanged), or a
2667/// `Streaming` spec the thread resolves branch-by-branch at the frontier
2668/// (Step E Phase C, PR C1).
2669enum CompilerWork {
2670    /// A frozen topological order (computed up front by `order_for`). The
2671    /// compiler thread compiles each node and sends it in turn.
2672    Order(Vec<NodeId>),
2673    /// The streaming run-walk: the compiler thread drives
2674    /// [`fuel_graph::walk_picked_route_streaming`] over `roots`, resolving
2675    /// each `Op::Branch` lazily via [`resolve_branch`] as the frontier
2676    /// reaches its arm-entry, and compiling + sending only the chosen
2677    /// arm's runs. `roots` are the effective roots (same set `order_for`
2678    /// lowers over). Byte-identical to `Order(lower_picked_route(
2679    /// pick_route(..)))` in C1 (same VRAM-only selector).
2680    Streaming {
2681        roots: Vec<NodeId>,
2682        pick: StreamingPick,
2683    },
2684}
2685
2686/// Compiler thread body. Holds the graph read-lock + a thread-local
2687/// layout cache and emits `WorkItem`s in topological order. For
2688/// [`CompilerWork::Order`] it walks the frozen order; for
2689/// [`CompilerWork::Streaming`] it resolves each branch at the frontier and
2690/// emits only the chosen arm's runs (Step E Phase C, PR C1). Sends
2691/// `Err(...)` and stops on the first failure.
2692fn compiler_thread_body(
2693    graph: Arc<RwLock<Graph>>,
2694    work: CompilerWork,
2695    sym_env: SymEnv,
2696    tx: Sender<Result<WorkItem>>,
2697) {
2698    let bindings = global_bindings();
2699
2700    let g = match graph.read() {
2701        Ok(g) => g,
2702        Err(_) => {
2703            let _ = tx.send(Err(poisoned("graph lock in compiler")));
2704            return;
2705        }
2706    };
2707
2708    // Compiler-thread-local layout cache. Populated as compile_one
2709    // walks topologically; downstream nodes look up their inputs'
2710    // layouts here (rather than from the graph side-table) to honor
2711    // the strided layouts emitted by metadata-only view ops earlier
2712    // in the same realize call.
2713    let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
2714    // `compile_one` for one node + send; returns `false` to stop the walk
2715    // (channel closed or compile error). Shared by both work modes so the
2716    // streamed and frozen-order paths compile identically.
2717    let compile_and_send = |id: NodeId, layout_cache: &mut HashMap<NodeId, Layout>| -> bool {
2718        let item = compile_one(&g, id, layout_cache, &bindings, &sym_env);
2719        let stop_on_err = item.is_err();
2720        if tx.send(item).is_err() {
2721            return false;
2722        }
2723        !stop_on_err
2724    };
2725
2726    match work {
2727        CompilerWork::Order(order) => {
2728            for id in order {
2729                if !compile_and_send(id, &mut layout_cache) {
2730                    return;
2731                }
2732            }
2733        }
2734        CompilerWork::Streaming { roots, pick } => {
2735            // Resolve each branch lazily at its arm-entry. C1 built the
2736            // streaming frontier; C2 made `pick.selector` load-aware (the
2737            // production `ChainedSelector` now reads each arm's live device
2738            // load — `pending_work_count / slot_capacity` via the
2739            // `BackendStreams` seam — as a key leg under the VRAM guard),
2740            // so this resolution reads live device load at THIS moment: the
2741            // executor has been submitting/draining (and updating the B1
2742            // counter) while the compiler ran ahead. Emit only the chosen
2743            // arm's runs, compiling + sending each node as the walk reaches
2744            // it — genuine streaming (resolution interleaved with
2745            // dispatch), not a pre-flattened order.
2746            let mut stopped = false;
2747            fuel_graph::walk_picked_route_streaming(
2748                &g,
2749                &roots,
2750                |branch| resolve_branch(&g, branch, &bindings, pick.selector.as_ref()),
2751                |members| {
2752                    if stopped {
2753                        return;
2754                    }
2755                    for &id in members {
2756                        if !compile_and_send(id, &mut layout_cache) {
2757                            stopped = true;
2758                            return;
2759                        }
2760                    }
2761                },
2762            );
2763        }
2764    }
2765}
2766
2767/// Resolve the [`CompiledNode`] for a kernel-bearing graph node via
2768/// the first-registered [`compile_node`] binding-table lookup.
2769///
2770/// `op_params` always comes from the executor's
2771/// `op_to_op_params(graph, node, id, layout_cache, sym_env)` — the live
2772/// OpParams shape (reduce dims, conv geometry, the per-pass
2773/// `SymEnv`-resolved `WriteSlice` offset, etc.) derives from the graph
2774/// node + its resolved input layouts at execute time.
2775fn resolve_compiled(
2776    op_kind: OpKind,
2777    dtypes: &[DType],
2778    target_backend: BackendId,
2779    op_params: OpParams,
2780    bindings: &KernelBindingTable,
2781) -> Result<CompiledNode> {
2782    compile_node(op_kind, dtypes, target_backend, op_params, bindings)
2783}
2784
2785/// Resolve one node into a `WorkItem` and update `layout_cache`
2786/// with the node's output layout. Three op shapes:
2787///
2788/// - `Op::Const` — adopts the entry from the input cache; layout is
2789///   read from the graph's side-table (or its contiguous fallback).
2790///
2791/// - Metadata-only view op — output layout is read from the graph's
2792///   side-table (populated by `Graph::push` at construction time);
2793///   the executor adopts the input's Storage Arc (no allocation, no
2794///   kernel).
2795///
2796/// - Computational op — output layout is `Layout::contiguous(node.shape)`
2797///   because today's kernels write contiguous output. The compiler
2798///   resolves the kernel ref and emits a Kernel work item.
2799fn compile_one(
2800    graph: &Graph,
2801    id: NodeId,
2802    layout_cache: &mut HashMap<NodeId, Layout>,
2803    bindings: &KernelBindingTable,
2804    sym_env: &SymEnv,
2805) -> Result<WorkItem> {
2806    let node = graph.node(id);
2807    let elem_count = node.shape.elem_count();
2808    let inputs = node.inputs.clone();
2809    // Snapshot destructive-input metadata from the graph at compile
2810    // time so the executor can evict the destroyed input from its
2811    // cache after the op runs (Op::Release / Op::Move semantics).
2812    let destructive_input = node.op.destructive_input();
2813
2814    if matches!(node.op, Op::Const) {
2815        let output_layout = graph.layout(id);
2816        layout_cache.insert(id, output_layout.clone());
2817        return Ok(WorkItem {
2818            node_id: id,
2819            inputs,
2820            elem_count,
2821            dtype: node.dtype,
2822            target_backend: BackendId::Cpu,
2823            kind: WorkItemKind::ConstAdopt,
2824            compiled: None,
2825            output_layout,
2826            destructive_input,
2827            output_bundle: None,
2828        });
2829    }
2830
2831    if node.op.is_view_op() {
2832        if inputs.len() != 1 {
2833            return Err(Error::Msg(format!(
2834                "view op {:?} expects 1 input, got {}",
2835                node.op,
2836                inputs.len(),
2837            ))
2838            .bt());
2839        }
2840        // Layout is read from the graph's side-table — populated by
2841        // `Graph::push` at construction time for view ops, and by
2842        // graph-rewriting opt passes that emit view nodes. The
2843        // compiler does not re-derive: graph.layout(id) is the single
2844        // source of truth.
2845        let output_layout = graph.layout(id);
2846        layout_cache.insert(id, output_layout.clone());
2847        // Inherit the upstream's target_backend (or default CPU) —
2848        // metadata-only adoption doesn't actually run on a backend,
2849        // but downstream consumers look at target_backend so it
2850        // needs to be set sensibly. Any device works.
2851        let target_backend = graph
2852            .target_backend(id)
2853            .or_else(|| graph.target_backend(inputs[0]))
2854            .unwrap_or(BackendId::Cpu);
2855        return Ok(WorkItem {
2856            node_id: id,
2857            inputs,
2858            elem_count,
2859            dtype: node.dtype,
2860            target_backend,
2861            kind: WorkItemKind::ViewOf {
2862                input: node.inputs[0],
2863            },
2864            compiled: None,
2865            output_layout,
2866            destructive_input,
2867            output_bundle: None,
2868        });
2869    }
2870
2871    // Op::View — multi-output projection (Option C, Session 4).
2872    // Structurally identical to a metadata-only view op at realize
2873    // time: clone the producer's Storage Arc into the View's cache
2874    // slot. The graph's layout side-table, populated by
2875    // `Tensor::view`, already carries the slot's effective layout
2876    // (slot.byte_offset baked into start_offset in slot-dtype-element
2877    // units).
2878    if let Op::View { .. } = node.op {
2879        if inputs.len() != 1 {
2880            return Err(Error::Msg(format!(
2881                "Op::View expects 1 input (the producer), got {}",
2882                inputs.len(),
2883            ))
2884            .bt());
2885        }
2886        let output_layout = graph.layout(id);
2887        layout_cache.insert(id, output_layout.clone());
2888        let target_backend = graph
2889            .target_backend(id)
2890            .or_else(|| graph.target_backend(inputs[0]))
2891            .unwrap_or(BackendId::Cpu);
2892        return Ok(WorkItem {
2893            node_id: id,
2894            inputs: inputs.clone(),
2895            elem_count,
2896            dtype: node.dtype,
2897            target_backend,
2898            kind: WorkItemKind::SlotView {
2899                producer: inputs[0],
2900            },
2901            compiled: None,
2902            output_layout,
2903            destructive_input,
2904            output_bundle: None,
2905        });
2906    }
2907
2908    // Op::ViewOwned — copies the slot's bytes into a fresh
2909    // contiguous Storage at realize time. Output layout is
2910    // contiguous starting at offset 0 (the memcpy produced an
2911    // independent buffer).
2912    if let Op::ViewOwned { slot } = node.op {
2913        if inputs.len() != 1 {
2914            return Err(Error::Msg(format!(
2915                "Op::ViewOwned expects 1 input (the producer), got {}",
2916                inputs.len(),
2917            ))
2918            .bt());
2919        }
2920        let output_layout = Layout::contiguous(node.shape.clone());
2921        layout_cache.insert(id, output_layout.clone());
2922        let target_backend = graph
2923            .target_backend(id)
2924            .or_else(|| graph.target_backend(inputs[0]))
2925            .unwrap_or(BackendId::Cpu);
2926        return Ok(WorkItem {
2927            node_id: id,
2928            inputs: inputs.clone(),
2929            elem_count,
2930            dtype: node.dtype,
2931            target_backend,
2932            kind: WorkItemKind::SlotOwn {
2933                producer: inputs[0],
2934                slot,
2935            },
2936            compiled: None,
2937            output_layout,
2938            destructive_input,
2939            output_bundle: None,
2940        });
2941    }
2942
2943    if matches!(node.op, Op::Release) {
2944        // Op::Release produces a zero-element marker output. The
2945        // marker storage is CPU + 0 bytes — nothing reads it; it
2946        // exists so cache lookups on the Release NodeId resolve.
2947        // The actual deallocation of `inputs[0]` happens in the
2948        // realize loop via `destructive_input` cleanup.
2949        if inputs.len() != 1 {
2950            return Err(
2951                Error::Msg(format!("Op::Release expects 1 input, got {}", inputs.len(),)).bt(),
2952            );
2953        }
2954        let output_layout = Layout::contiguous(node.shape.clone());
2955        layout_cache.insert(id, output_layout.clone());
2956        // Inherit the source's target_backend so any downstream
2957        // backend-aware logic (telemetry, scheduling) sees a sensible
2958        // value. The marker doesn't actually run on any backend.
2959        let target_backend = graph
2960            .target_backend(id)
2961            .or_else(|| graph.target_backend(inputs[0]))
2962            .unwrap_or(BackendId::Cpu);
2963        return Ok(WorkItem {
2964            node_id: id,
2965            inputs,
2966            elem_count,
2967            dtype: node.dtype,
2968            target_backend,
2969            kind: WorkItemKind::ReleaseMarker,
2970            compiled: None,
2971            output_layout,
2972            destructive_input,
2973            output_bundle: None,
2974        });
2975    }
2976
2977    // In-place ops (Phase 3 of in-place ops infrastructure): kernel
2978    // lookup goes through the standard binding-table path, but the
2979    // executor adopts the target's Arc as the output instead of
2980    // allocating fresh bytes. The compile-time predicate is exactly
2981    // `op.destructive_input().is_some()` AND NOT one of the
2982    // structural ops (WriteSlice / ZeroFill / Release / Move) which
2983    // have their own dedicated WorkItemKind arms in this function.
2984    if !matches!(
2985        node.op,
2986        Op::WriteSlice { .. }
2987            | Op::WriteSliceRotating { .. }
2988            | Op::WriteSliceDoff { .. }
2989            | Op::ZeroFill
2990            | Op::Release
2991            | Op::Move { .. },
2992    ) && let Some(target_idx) = node.op.destructive_input()
2993    {
2994        if inputs.len() <= target_idx {
2995            return Err(Error::Msg(format!(
2996                "in-place op {:?} declares destructive_input={target_idx} \
2997                     but has only {} input(s)",
2998                node.op,
2999                inputs.len(),
3000            ))
3001            .bt());
3002        }
3003        let target_backend = graph.target_backend(id).ok_or_else(|| {
3004            Error::Msg(format!(
3005                "PipelinedExecutor: in-place op node {id:?} has no target_backend set",
3006            ))
3007            .bt()
3008        })?;
3009        let op_kind = op_to_op_kind(&node.op).ok_or_else(|| {
3010            Error::Msg(format!(
3011                "PipelinedExecutor: in-place op {:?} has no op_to_op_kind mapping",
3012                node.op,
3013            ))
3014            .bt()
3015        })?;
3016        let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3017        let dtypes = build_lookup_dtypes(graph, node);
3018        let compiled = resolve_compiled(op_kind, &dtypes, target_backend, op_params, bindings)?;
3019        // Output adopts target's Layout (same Storage Arc, same shape).
3020        let output_layout = graph.layout(inputs[target_idx]);
3021        layout_cache.insert(id, output_layout.clone());
3022        return Ok(WorkItem {
3023            node_id: id,
3024            inputs: inputs.clone(),
3025            elem_count,
3026            dtype: node.dtype,
3027            target_backend,
3028            kind: WorkItemKind::InplaceKernel { target_idx },
3029            compiled: Some(compiled),
3030            output_layout,
3031            destructive_input,
3032            output_bundle: None,
3033        });
3034    }
3035
3036    if matches!(node.op, Op::WriteSlice { .. }) {
3037        // WriteSlice: kernel lookup happens like a normal kernel, but
3038        // the work item carries a dedicated kind so the executor
3039        // knows to adopt the destination's Arc as the output rather
3040        // than allocating a fresh buffer. The destination's NodeId is
3041        // captured here so the executor doesn't have to re-derive it.
3042        if inputs.len() != 2 {
3043            return Err(Error::Msg(format!(
3044                "Op::WriteSlice expects 2 inputs (destination, source), got {}",
3045                inputs.len(),
3046            ))
3047            .bt());
3048        }
3049        let target_backend = graph.target_backend(id).ok_or_else(|| {
3050            Error::Msg(format!(
3051                "PipelinedExecutor: WriteSlice node {:?} has no target_backend set",
3052                id
3053            ))
3054            .bt()
3055        })?;
3056        let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3057        let dtypes = build_lookup_dtypes(graph, node);
3058        let compiled = resolve_compiled(
3059            OpKind::WriteSlice,
3060            &dtypes,
3061            target_backend,
3062            op_params,
3063            bindings,
3064        )?;
3065        // Output adopts the destination's Layout — same Storage Arc,
3066        // same shape. Downstream consumers that want a post-write
3067        // sub-extent compose an explicit Op::Slice (WriteSlice does
3068        // not encode partial extents).
3069        let output_layout = graph.layout(inputs[0]);
3070        layout_cache.insert(id, output_layout.clone());
3071        return Ok(WorkItem {
3072            node_id: id,
3073            inputs: inputs.clone(),
3074            elem_count,
3075            dtype: node.dtype,
3076            target_backend,
3077            kind: WorkItemKind::WriteSlice {
3078                dest: inputs[0],
3079                source: inputs[1],
3080            },
3081            compiled: Some(compiled),
3082            output_layout,
3083            destructive_input,
3084            output_bundle: None,
3085        });
3086    }
3087
3088    if matches!(node.op, Op::WriteSliceRotating { .. }) {
3089        // WriteSliceRotating: same shape as WriteSlice but with a
3090        // third input (position scalar). Dispatch through the
3091        // binding table at `OpKind::WriteSliceRotating`; the
3092        // executor's arm reads the position from `position`'s
3093        // storage and the kernel splits across the ring boundary.
3094        if inputs.len() != 3 {
3095            return Err(Error::Msg(format!(
3096                "Op::WriteSliceRotating expects 3 inputs (destination, source, position), got {}",
3097                inputs.len(),
3098            ))
3099            .bt());
3100        }
3101        let target_backend = graph.target_backend(id).ok_or_else(|| {
3102            Error::Msg(format!(
3103                "PipelinedExecutor: WriteSliceRotating node {:?} has no target_backend set",
3104                id
3105            ))
3106            .bt()
3107        })?;
3108        let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3109        let dtypes = build_lookup_dtypes(graph, node);
3110        let compiled = resolve_compiled(
3111            OpKind::WriteSliceRotating,
3112            &dtypes,
3113            target_backend,
3114            op_params,
3115            bindings,
3116        )?;
3117        let output_layout = graph.layout(inputs[0]);
3118        layout_cache.insert(id, output_layout.clone());
3119        return Ok(WorkItem {
3120            node_id: id,
3121            inputs: inputs.clone(),
3122            elem_count,
3123            dtype: node.dtype,
3124            target_backend,
3125            kind: WorkItemKind::WriteSliceRotating {
3126                dest: inputs[0],
3127                source: inputs[1],
3128                position: inputs[2],
3129            },
3130            compiled: Some(compiled),
3131            output_layout,
3132            destructive_input,
3133            output_bundle: None,
3134        });
3135    }
3136
3137    if matches!(node.op, Op::WriteSliceDoff { .. }) {
3138        // WriteSliceDoff: same shape as WriteSlice but with a third
3139        // input (device-resident I64 offset). Dispatch through the
3140        // binding table at `OpKind::WriteSliceDoff`; the executor's arm
3141        // threads the offset's device pointer straight to the kernel
3142        // (no D2H, capture-safe).
3143        if inputs.len() != 3 {
3144            return Err(Error::Msg(format!(
3145                "Op::WriteSliceDoff expects 3 inputs (destination, source, offset), got {}",
3146                inputs.len(),
3147            ))
3148            .bt());
3149        }
3150        let target_backend = graph.target_backend(id).ok_or_else(|| {
3151            Error::Msg(format!(
3152                "PipelinedExecutor: WriteSliceDoff node {:?} has no target_backend set",
3153                id
3154            ))
3155            .bt()
3156        })?;
3157        let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3158        let dtypes = build_lookup_dtypes(graph, node);
3159        let compiled = resolve_compiled(
3160            OpKind::WriteSliceDoff,
3161            &dtypes,
3162            target_backend,
3163            op_params,
3164            bindings,
3165        )?;
3166        let output_layout = graph.layout(inputs[0]);
3167        layout_cache.insert(id, output_layout.clone());
3168        return Ok(WorkItem {
3169            node_id: id,
3170            inputs: inputs.clone(),
3171            elem_count,
3172            dtype: node.dtype,
3173            target_backend,
3174            kind: WorkItemKind::WriteSliceDoff {
3175                dest: inputs[0],
3176                source: inputs[1],
3177                offset: inputs[2],
3178            },
3179            compiled: Some(compiled),
3180            output_layout,
3181            destructive_input,
3182            output_bundle: None,
3183        });
3184    }
3185
3186    if let Op::Alloc { target } = node.op {
3187        // Op::Alloc { target }: produce a fresh zero-init Storage on
3188        // `target` with node.shape * node.dtype. Zero inputs.
3189        // Direct executor dispatch via WorkItemKind::Alloc — no
3190        // binding-table lookup (the device handle threading isn't
3191        // expressible through the binding table's current key shape).
3192        if !inputs.is_empty() {
3193            return Err(
3194                Error::Msg(format!("Op::Alloc expects 0 inputs, got {}", inputs.len(),)).bt(),
3195            );
3196        }
3197        let output_layout = Layout::contiguous(node.shape.clone());
3198        layout_cache.insert(id, output_layout.clone());
3199        // target_backend is informational here (the executor's Alloc
3200        // arm consults target_location for allocation routing); set
3201        // it to target's backend for consistency with how downstream
3202        // nodes inherit/read it.
3203        let target_backend = target.backend();
3204        return Ok(WorkItem {
3205            node_id: id,
3206            inputs,
3207            elem_count,
3208            dtype: node.dtype,
3209            target_backend,
3210            kind: WorkItemKind::Alloc {
3211                target_location: target,
3212            },
3213            compiled: None,
3214            output_layout,
3215            destructive_input,
3216            output_bundle: None,
3217        });
3218    }
3219
3220    if let Op::Iota { len } = node.op {
3221        // Op::Iota { len }: 0-input F32 position generator
3222        // [0.0, 1.0, …, (len-1)]. Direct executor dispatch via
3223        // WorkItemKind::Iota — no binding-table lookup (a leaf has no
3224        // inputs[0] to inherit a backend from). Modeled on Op::Alloc.
3225        if !inputs.is_empty() {
3226            return Err(
3227                Error::Msg(format!("Op::Iota expects 0 inputs, got {}", inputs.len(),)).bt(),
3228            );
3229        }
3230        let output_layout = Layout::contiguous(node.shape.clone());
3231        layout_cache.insert(id, output_layout.clone());
3232        // Leaf: the planner may not place a 0-input node, so fall back to
3233        // CPU. Iota is a tiny host-side generator; its only consumer today
3234        // is the CPU flash-attn decomposition's alibi bias.
3235        let target_backend = graph.target_backend(id).unwrap_or(BackendId::Cpu);
3236        return Ok(WorkItem {
3237            node_id: id,
3238            inputs,
3239            elem_count,
3240            dtype: node.dtype,
3241            target_backend,
3242            kind: WorkItemKind::Iota { len },
3243            compiled: None,
3244            output_layout,
3245            destructive_input,
3246            output_bundle: None,
3247        });
3248    }
3249
3250    if matches!(node.op, Op::ZeroFill) {
3251        // Op::ZeroFill: 1 input (the buffer to zero); output aliases
3252        // input's Storage Arc (destructive in-place). No binding-
3253        // table lookup — per-backend dispatch in execute_work_item.
3254        if inputs.len() != 1 {
3255            return Err(Error::Msg(format!(
3256                "Op::ZeroFill expects 1 input, got {}",
3257                inputs.len(),
3258            ))
3259            .bt());
3260        }
3261        // Output layout: contiguous in the node's shape. We don't
3262        // require the input to be contiguous (auto_contiguize in the
3263        // executor handles strided inputs), but the destructive
3264        // semantic means callers should only ZeroFill an Op::Alloc
3265        // output today.
3266        let output_layout = Layout::contiguous(node.shape.clone());
3267        layout_cache.insert(id, output_layout.clone());
3268        let target_backend = graph
3269            .target_backend(id)
3270            .or_else(|| graph.target_backend(inputs[0]))
3271            .unwrap_or(BackendId::Cpu);
3272        return Ok(WorkItem {
3273            node_id: id,
3274            inputs,
3275            elem_count,
3276            dtype: node.dtype,
3277            target_backend,
3278            kind: WorkItemKind::ZeroFill,
3279            compiled: None,
3280            output_layout,
3281            destructive_input,
3282            output_bundle: None,
3283        });
3284    }
3285
3286    if let Op::Copy { target } = node.op {
3287        // Op::Copy { target }: download bytes from the source residency
3288        // to a fresh Storage allocated on `target`. Kernel lookup uses
3289        // `target_backend` = source backend (set by `prepare()` on the
3290        // realize device the source is on); the wrapper does the actual
3291        // transfer (e.g. Vulkan::download_bytes → memcpy into a CPU
3292        // CpuStorageBytes). The output Storage's variant is determined
3293        // by `target_location` and allocated in `execute_work_item`'s
3294        // WorkItemKind::Copy arm.
3295        if inputs.len() != 1 {
3296            return Err(
3297                Error::Msg(format!("Op::Copy expects 1 input, got {}", inputs.len(),)).bt(),
3298            );
3299        }
3300        let target_backend = graph.target_backend(id).ok_or_else(|| {
3301            Error::Msg(format!(
3302                "PipelinedExecutor: Op::Copy node {:?} has no target_backend \
3303                 set (= source backend, the one whose kernel runs the \
3304                 download)",
3305                id
3306            ))
3307            .bt()
3308        })?;
3309        let op_params = OpParams::None;
3310        let dtypes = build_lookup_dtypes(graph, node);
3311        let compiled =
3312            resolve_compiled(OpKind::Copy, &dtypes, target_backend, op_params, bindings)?;
3313        // Output layout: contiguous in the node's shape (mirrors the
3314        // source's logical shape). Auto-contiguize on the input side
3315        // (in execute_work_item) handles strided source views by
3316        // materializing them into a contiguous source buffer before
3317        // the kernel runs.
3318        let output_layout = Layout::contiguous(node.shape.clone());
3319        layout_cache.insert(id, output_layout.clone());
3320        return Ok(WorkItem {
3321            node_id: id,
3322            inputs,
3323            elem_count,
3324            dtype: node.dtype,
3325            target_backend,
3326            kind: WorkItemKind::Copy {
3327                target_location: target,
3328            },
3329            compiled: Some(compiled),
3330            output_layout,
3331            destructive_input,
3332            output_bundle: None,
3333        });
3334    }
3335
3336    if let Op::Move { target } = node.op {
3337        // Op::Move { target }: identical data-movement half to
3338        // Op::Copy — kernel lookup at (OpKind::Copy, [dt, dt],
3339        // source_backend); output allocated on `target` by the
3340        // executor's Copy/Move arm. The destructive half (release
3341        // the source) rides the realize loop's `destructive_input`
3342        // cleanup via the snapshot taken at the top of this function
3343        // (`Op::Move::destructive_input() == Some(0)`). Ordering
3344        // safety (a Move must not strand a sibling consumer of its
3345        // source) is `execution_plan`/`derive_ordering`'s job — the
3346        // Move is pinned after every non-destructive reader of the
3347        // source's alias set before any work item is emitted.
3348        if inputs.len() != 1 {
3349            return Err(
3350                Error::Msg(format!("Op::Move expects 1 input, got {}", inputs.len(),)).bt(),
3351            );
3352        }
3353        let target_backend = graph.target_backend(id).ok_or_else(|| {
3354            Error::Msg(format!(
3355                "PipelinedExecutor: Op::Move node {:?} has no target_backend \
3356                 set (= source backend, the one whose kernel runs the \
3357                 transfer)",
3358                id
3359            ))
3360            .bt()
3361        })?;
3362        let op_params = OpParams::None;
3363        let dtypes = build_lookup_dtypes(graph, node);
3364        let compiled =
3365            resolve_compiled(OpKind::Copy, &dtypes, target_backend, op_params, bindings)?;
3366        // Output layout: contiguous in the node's shape, same as
3367        // Op::Copy (the transfer materializes strided sources via
3368        // auto-contiguize on the input side).
3369        let output_layout = Layout::contiguous(node.shape.clone());
3370        layout_cache.insert(id, output_layout.clone());
3371        return Ok(WorkItem {
3372            node_id: id,
3373            inputs,
3374            elem_count,
3375            dtype: node.dtype,
3376            target_backend,
3377            kind: WorkItemKind::Move {
3378                target_location: target,
3379            },
3380            compiled: Some(compiled),
3381            output_layout,
3382            destructive_input,
3383            output_bundle: None,
3384        });
3385    }
3386
3387    if matches!(node.op, Op::Reshape(_)) {
3388        if inputs.len() != 1 {
3389            return Err(
3390                Error::Msg(format!("Op::Reshape expects 1 input, got {}", inputs.len(),)).bt(),
3391            );
3392        }
3393        let input_layout = graph.layout(inputs[0]);
3394        // Output is contiguous in the new shape — bytes per element
3395        // are unchanged, so a contiguous input flows through with
3396        // zero copy. A non-contiguous input is auto-contiguized at
3397        // execute time and the result is naturally contiguous.
3398        let output_layout = Layout::contiguous(node.shape.clone());
3399        layout_cache.insert(id, output_layout.clone());
3400        let target_backend = graph
3401            .target_backend(id)
3402            .or_else(|| graph.target_backend(inputs[0]))
3403            .unwrap_or(BackendId::Cpu);
3404        // Sanity: same total element count.
3405        let in_elem_count = input_layout.shape().elem_count();
3406        if in_elem_count != elem_count {
3407            return Err(Error::Msg(format!(
3408                "Op::Reshape changes element count: input {} → output {}",
3409                in_elem_count, elem_count,
3410            ))
3411            .bt());
3412        }
3413        return Ok(WorkItem {
3414            node_id: id,
3415            inputs,
3416            elem_count,
3417            dtype: node.dtype,
3418            target_backend,
3419            kind: WorkItemKind::ContiguizeOf {
3420                input: node.inputs[0],
3421            },
3422            compiled: None,
3423            output_layout,
3424            destructive_input,
3425            output_bundle: None,
3426        });
3427    }
3428
3429    if matches!(node.op, Op::Contiguize) {
3430        // Op::Contiguize: same execute-time path as Reshape, but
3431        // output shape == input shape so there's no element-count
3432        // check. Zero-copy when input is already contiguous +
3433        // zero-offset (the ContiguizeOf arm in execute_work_item
3434        // adopts the input Arc); otherwise auto_contiguize allocates
3435        // a fresh contiguous Storage on the input's backend.
3436        if inputs.len() != 1 {
3437            return Err(Error::Msg(format!(
3438                "Op::Contiguize expects 1 input, got {}",
3439                inputs.len(),
3440            ))
3441            .bt());
3442        }
3443        let output_layout = Layout::contiguous(node.shape.clone());
3444        layout_cache.insert(id, output_layout.clone());
3445        let target_backend = graph
3446            .target_backend(id)
3447            .or_else(|| graph.target_backend(inputs[0]))
3448            .unwrap_or(BackendId::Cpu);
3449        return Ok(WorkItem {
3450            node_id: id,
3451            inputs,
3452            elem_count,
3453            dtype: node.dtype,
3454            target_backend,
3455            kind: WorkItemKind::ContiguizeOf {
3456                input: node.inputs[0],
3457            },
3458            compiled: None,
3459            output_layout,
3460            destructive_input,
3461            output_bundle: None,
3462        });
3463    }
3464
3465    // Runtime fused op — a JIT-adopted (Tier-2) kernel. `Op::Fused(fid, _)`
3466    // with `fid.is_runtime()` has no `OpKind` (the op was synthesized after
3467    // startup): its kernel resolves from the SAME binding table as every
3468    // static kernel, under `BindingKey::RuntimeFused(fid)` — the dtype tuple
3469    // is the key, so an absent kernel AND a dtype mismatch are one honest
3470    // `NoBackendForOp` miss. A deterministic *lookup*, not a decision: the
3471    // optimizer's gate emitted the arm only when this kernel was bound, and
3472    // pinned `target_backend` (`runtime-fused-op-registration.md` §6). The
3473    // guards are invariant checks, never live fallbacks.
3474    if let Op::Fused(fid, _) = &node.op
3475        && fid.is_runtime()
3476    {
3477        let target_backend = graph.target_backend(id).ok_or_else(|| {
3478            Error::Msg(format!(
3479                "PipelinedExecutor: runtime fused op {:?} (node {:?}) has no \
3480                     target_backend — the arm emitter pins it at emission",
3481                fid, id,
3482            ))
3483            .bt()
3484        })?;
3485        // v1: single-output only. Reject a multi-output bundle explicitly
3486        // rather than silently dropping it.
3487        if graph.output_views_arc(id).is_some() {
3488            return Err(Error::Msg(format!(
3489                "PipelinedExecutor: runtime fused op {:?} (node {:?}) carries a \
3490                     multi-output bundle — synthesized kernels are single-output in v1",
3491                fid, id,
3492            ))
3493            .bt());
3494        }
3495        let dtypes = build_lookup_dtypes(graph, node);
3496        let (kernel, caps) = bindings.lookup_with_caps(
3497            crate::kernel::BindingKey::RuntimeFused(*fid),
3498            &dtypes,
3499            target_backend,
3500        )?;
3501        let output_layout = Layout::contiguous(node.shape.clone());
3502        layout_cache.insert(id, output_layout.clone());
3503        // Deliberate, not a fallthrough to `op_to_op_params` (which doesn't
3504        // know runtime ops): the node's `Runtime { scalars }` — the live
3505        // `extract:` values, pattern pre-order — becomes `JitScalars` (the
3506        // launch appends them as the kernel's trailing `p{i}` args); a
3507        // param-free op carries `None` (its launch is layout-driven:
3508        // pointers + element count).
3509        let op_params = match &node.op {
3510            Op::Fused(_, FusedOpParams::Runtime { scalars }) if !scalars.is_empty() => {
3511                OpParams::JitScalars {
3512                    scalars: scalars.clone(),
3513                }
3514            }
3515            _ => OpParams::None,
3516        };
3517        let compiled = CompiledNode {
3518            op: OpKind::RuntimeFused,
3519            dtypes: KernelDTypes::from_slice(&dtypes),
3520            backend: target_backend,
3521            kernel,
3522            caps,
3523            op_params,
3524        };
3525        return Ok(WorkItem {
3526            node_id: id,
3527            inputs,
3528            elem_count,
3529            dtype: node.dtype,
3530            target_backend,
3531            kind: WorkItemKind::Kernel,
3532            compiled: Some(compiled),
3533            output_layout,
3534            destructive_input,
3535            output_bundle: None,
3536        });
3537    }
3538
3539    let target_backend = graph.target_backend(id).ok_or_else(|| {
3540        Error::Msg(format!(
3541            "PipelinedExecutor: node {:?} ({:?}) has no target_backend set",
3542            id, node.op
3543        ))
3544        .bt()
3545    })?;
3546
3547    let op_kind = op_to_op_kind(&node.op).ok_or_else(|| {
3548        Error::Msg(format!(
3549            "PipelinedExecutor: op {:?} not yet mapped to an OpKind \
3550             (Phase C migrates more ops as they're registered)",
3551            node.op,
3552        ))
3553        .bt()
3554    })?;
3555
3556    let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3557    // Build the per-operand dtype list for the binding-table lookup —
3558    // inputs in order, then outputs. Variadic uniform-dtype ops
3559    // (Concat) collapse to the canonical `[T_in, T_out]` shorthand to
3560    // match how registrations index them.
3561    let dtypes = build_lookup_dtypes(graph, node);
3562    let compiled = resolve_compiled(op_kind, &dtypes, target_backend, op_params, bindings)?;
3563    let output_layout = Layout::contiguous(node.shape.clone());
3564    layout_cache.insert(id, output_layout.clone());
3565    // Multi-output: snapshot the producer's bundle metadata. When
3566    // `Some(_)`, the Kernel arm allocates a single Storage sized to
3567    // fit every slot and attaches the bundle via
3568    // `Storage::with_bundle` so downstream Op::View/Op::ViewOwned
3569    // resolve correctly.
3570    let output_bundle = graph.output_views_arc(id);
3571    Ok(WorkItem {
3572        node_id: id,
3573        inputs,
3574        elem_count,
3575        dtype: node.dtype,
3576        target_backend,
3577        kind: WorkItemKind::Kernel,
3578        compiled: Some(compiled),
3579        output_layout,
3580        destructive_input,
3581        output_bundle,
3582    })
3583}
3584
3585/// Build the per-operand dtype list used as the binding-table lookup
3586/// key. Inputs in order, then the output. Variadic-uniform ops
3587/// (Concat) collapse to the canonical `[T_in, T_out]` shorthand to
3588/// match how those wrappers are registered (otherwise an N-way concat
3589/// would need N+1 distinct registrations per dtype).
3590///
3591/// `pub(crate)` — `crate::plan::compile_plan` (step 9b) reuses this
3592/// to key the route picker's binding-table lookup the same way the
3593/// pipelined path does.
3594pub(crate) fn build_lookup_dtypes(graph: &Graph, node: &Node) -> Vec<DType> {
3595    if matches!(node.op, Op::Concat { .. }) {
3596        // Concat: all inputs share node.dtype by construction.
3597        let in_dt = node
3598            .inputs
3599            .first()
3600            .map(|&id| graph.node(id).dtype)
3601            .unwrap_or(node.dtype);
3602        return vec![in_dt, node.dtype];
3603    }
3604    if matches!(node.op, Op::WriteSlice { .. }) {
3605        // WriteSlice: the destination (inputs[0]) is exposed to the
3606        // executor as the OUTPUT slot (in-place adoption), not as an
3607        // input the kernel reads. Canonicalize the binding-table key
3608        // to `[T_source, T_out]` so registrations match the kernel's
3609        // actual surface (one input slab + one output buffer).
3610        let src_dt = node
3611            .inputs
3612            .get(1)
3613            .map(|&id| graph.node(id).dtype)
3614            .unwrap_or(node.dtype);
3615        return vec![src_dt, node.dtype];
3616    }
3617    if matches!(node.op, Op::WriteSliceRotating { .. }) {
3618        // Same canonicalization as WriteSlice: dest = output slot;
3619        // position (inputs[2]) is read by the kernel via the
3620        // position-input parameter, not the binding-table key.
3621        let src_dt = node
3622            .inputs
3623            .get(1)
3624            .map(|&id| graph.node(id).dtype)
3625            .unwrap_or(node.dtype);
3626        return vec![src_dt, node.dtype];
3627    }
3628    if matches!(node.op, Op::WriteSliceDoff { .. }) {
3629        // Same canonicalization as WriteSlice: dest = output slot;
3630        // offset (inputs[2], I64) is a non-key runtime operand read by
3631        // the kernel via its device pointer, not the binding-table key.
3632        let src_dt = node
3633            .inputs
3634            .get(1)
3635            .map(|&id| graph.node(id).dtype)
3636            .unwrap_or(node.dtype);
3637        return vec![src_dt, node.dtype];
3638    }
3639    let mut dts: Vec<DType> = node.inputs.iter().map(|&id| graph.node(id).dtype).collect();
3640    dts.push(node.dtype);
3641    dts
3642}
3643
3644/// SoftmaxLastDim is reachable only through `Op::Fused(FusedOps::
3645/// SOFTMAX_LAST_DIM, _)` post-step-5 (the legacy `Op::SoftmaxLastDim`
3646/// primitive variant was retired). This helper collapses the
3647/// op-to-OpKind/OpParams shapes for callers that want a single-arm
3648/// match.
3649fn op_is_softmax_last_dim(op: &Op) -> bool {
3650    matches!(op, Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM)
3651}
3652
3653/// FusedLinear is reachable only through `Op::Fused(FusedOps::
3654/// FUSED_LINEAR, _)` post-step-5.
3655fn op_is_fused_linear(op: &Op) -> bool {
3656    matches!(op, Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::FUSED_LINEAR)
3657}
3658
3659/// Map a `fuel_graph::Op` to a `fuel_ir::dispatch::OpKind`.
3660/// Returns `None` for ops that haven't been wired into the new
3661/// dispatch path yet — Phase C extends this as op families migrate.
3662///
3663/// `pub(crate)` — `crate::plan::compile_plan` (step 9b) reuses this
3664/// to skip nodes the binding-table doesn't index (view ops,
3665/// `Op::Const`, not-yet-migrated ops) when building bindings.
3666pub(crate) fn op_to_op_kind(op: &Op) -> Option<OpKind> {
3667    match op {
3668        Op::Add => Some(OpKind::AddElementwise),
3669        Op::Sub => Some(OpKind::SubElementwise),
3670        Op::Mul => Some(OpKind::MulElementwise),
3671        Op::Div => Some(OpKind::DivElementwise),
3672        Op::Relu => Some(OpKind::ReluElementwise),
3673        Op::Neg => Some(OpKind::NegElementwise),
3674        Op::Sqr => Some(OpKind::SqrElementwise),
3675        Op::Sqrt => Some(OpKind::SqrtElementwise),
3676        Op::Tanh => Some(OpKind::TanhElementwise),
3677        Op::Exp => Some(OpKind::ExpElementwise),
3678        Op::Log => Some(OpKind::LogElementwise),
3679        Op::Sin => Some(OpKind::SinElementwise),
3680        Op::Cos => Some(OpKind::CosElementwise),
3681        Op::Sigmoid => Some(OpKind::SigmoidElementwise),
3682        Op::Silu => Some(OpKind::SiluElementwise),
3683        Op::GeluTanh => Some(OpKind::GeluTanhElementwise),
3684        Op::Step => Some(OpKind::StepElementwise),
3685        Op::Recip => Some(OpKind::RecipElementwise),
3686        Op::Abs => Some(OpKind::AbsElementwise),
3687        Op::Equal => Some(OpKind::EqualElementwise),
3688        Op::Ne => Some(OpKind::NotEqualElementwise),
3689        Op::Lt => Some(OpKind::LessElementwise),
3690        Op::Le => Some(OpKind::LessEqualElementwise),
3691        Op::Gt => Some(OpKind::GreaterElementwise),
3692        Op::Ge => Some(OpKind::GreaterEqualElementwise),
3693        Op::Where => Some(OpKind::Where),
3694        Op::Floor => Some(OpKind::FloorElementwise),
3695        Op::Ceil => Some(OpKind::CeilElementwise),
3696        Op::Round => Some(OpKind::RoundElementwise),
3697        Op::Sign => Some(OpKind::SignElementwise),
3698        Op::Erf => Some(OpKind::ErfElementwise),
3699        Op::Gelu => Some(OpKind::GeluElementwise),
3700        Op::Pow => Some(OpKind::PowElementwise),
3701        Op::Rsqrt => Some(OpKind::RsqrtElementwise),
3702        Op::Rem => Some(OpKind::RemElementwise),
3703        Op::Flip { .. } => Some(OpKind::Flip),
3704        Op::Roll { .. } => Some(OpKind::Roll),
3705        Op::CumSum { .. } => Some(OpKind::CumSum),
3706        Op::Triu { .. } => Some(OpKind::Triu),
3707        Op::Tril { .. } => Some(OpKind::Tril),
3708        Op::LogSoftmaxLastDim => Some(OpKind::LogSoftmaxLastDim),
3709        Op::LogSoftmaxLastDimBackward => Some(OpKind::LogSoftmaxLastDimBackward),
3710        Op::MaskedFill { .. } => Some(OpKind::MaskedFill),
3711        Op::Pad { .. } => Some(OpKind::Pad),
3712        Op::PadBackward { .. } => Some(OpKind::PadBackward),
3713        Op::SumDim(_) => Some(OpKind::SumReduce),
3714        Op::MaxDim(_) => Some(OpKind::MaxReduce),
3715        Op::MinDim(_) => Some(OpKind::MinReduce),
3716        Op::MeanDim(_) => Some(OpKind::MeanReduce),
3717        Op::SumAll => Some(OpKind::SumReduce),
3718        Op::MaxAll => Some(OpKind::MaxReduce),
3719        Op::MinAll => Some(OpKind::MinReduce),
3720        Op::MeanAll => Some(OpKind::MeanReduce),
3721        Op::MatMul => Some(OpKind::MatMul),
3722        Op::Cast(_) => Some(OpKind::Cast),
3723        // Phase 7.6 step 5: fused-op dispatch routes through
3724        // `Op::Fused(fid, _)`; the legacy `Op::Conv2D` /
3725        // `Op::FusedLinear` / `Op::SoftmaxLastDim` /
3726        // `Op::RmsNormLastDim` / `Op::LayerNormLastDim` / `Op::Rope`
3727        // arms were dropped together with the variants.
3728        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::CONV2D => Some(OpKind::Conv2D),
3729        // Phase 7.6 step 5 (final): legacy `Op::ConvTranspose2D` /
3730        // `Op::FlashAttn` / `Op::PagedAttn` arms dropped with the
3731        // variants; dispatch flows only through `Op::Fused`.
3732        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D => {
3733            Some(OpKind::ConvTranspose2D)
3734        }
3735        Op::ReduceSumTo(_) => Some(OpKind::ReduceSumTo),
3736        Op::ReduceMaxTo(_) => Some(OpKind::ReduceMaxTo),
3737        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::FLASH_ATTN => {
3738            Some(OpKind::FlashAttn)
3739        }
3740        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::PAGED_ATTN => {
3741            Some(OpKind::PagedAttn)
3742        }
3743        Op::AddScalar(_) => Some(OpKind::Affine),
3744        Op::MulScalar(_) => Some(OpKind::Affine),
3745        Op::Clamp { .. } => Some(OpKind::ClampElementwise),
3746        Op::PowI(_) => Some(OpKind::PowIElementwise),
3747        Op::Maximum => Some(OpKind::MaximumElementwise),
3748        Op::Minimum => Some(OpKind::MinimumElementwise),
3749        Op::Concat { .. } => Some(OpKind::Concat),
3750        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM => {
3751            Some(OpKind::SoftmaxLastDim)
3752        }
3753        // Phase 7.6 step 6 follow-up: backward helpers now route
3754        // through the byte-level binding table too.
3755        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM_BACKWARD => {
3756            Some(OpKind::SoftmaxLastDimBackward)
3757        }
3758        Op::Fused(fid, _)
3759            if *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM_BACKWARD =>
3760        {
3761            Some(OpKind::LayerNormLastDimBackward)
3762        }
3763        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM_BACKWARD => {
3764            Some(OpKind::RmsNormLastDimBackward)
3765        }
3766        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::REDUCE_MAX_TO_BACKWARD => {
3767            Some(OpKind::ReduceMaxToBackward)
3768        }
3769        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::POWI_BACKWARD => {
3770            Some(OpKind::PowIElementwiseBackward)
3771        }
3772        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::FUSED_LINEAR => {
3773            Some(OpKind::FusedLinear)
3774        }
3775        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM => {
3776            Some(OpKind::RmsNormLastDim)
3777        }
3778        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM => {
3779            Some(OpKind::LayerNormLastDim)
3780        }
3781        Op::IndexSelect { .. } => Some(OpKind::IndexSelect),
3782        Op::Gather { .. } => Some(OpKind::Gather),
3783        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::ROPE => Some(OpKind::Rope),
3784        Op::IndexAdd { .. } => Some(OpKind::IndexAdd),
3785        Op::ScatterAdd { .. } => Some(OpKind::ScatterAdd),
3786        Op::NonZeroIndices { .. } => Some(OpKind::NonZeroIndices),
3787        Op::ArgMaxDim(_) => Some(OpKind::ArgMaxDim),
3788        Op::ArgMinDim(_) => Some(OpKind::ArgMinDim),
3789        // Phase 7.6 step 5 (final): legacy `Op::QMatMul` arm dropped.
3790        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::QMATMUL => {
3791            Some(OpKind::QMatMul)
3792        }
3793        Op::WriteSlice { .. } => Some(OpKind::WriteSlice),
3794        Op::WriteSliceRotating { .. } => Some(OpKind::WriteSliceRotating),
3795        Op::WriteSliceDoff { .. } => Some(OpKind::WriteSliceDoff),
3796        // Phase 2 of bridge-retirement (post-9c): Op::Copy dispatches
3797        // through the binding table at OpKind::Copy. The BackendId
3798        // axis encodes the source backend (the kernel runs there —
3799        // download from local memory). The executor handles output
3800        // allocation on the target via a dedicated WorkItemKind::Copy
3801        // arm, since target_location differs from target_backend for
3802        // this op (the only one with that property today).
3803        Op::Copy { .. } => Some(OpKind::Copy),
3804        // Op::Move dispatches the same data-movement kernel as
3805        // Op::Copy — the destructive release of the source is
3806        // realize-loop bookkeeping (`destructive_input` cleanup), not
3807        // a kernel. Same OpKind, same source-backend key convention.
3808        // `compile_plan` skips both (residency-determined, not a
3809        // picker decision).
3810        Op::Move { .. } => Some(OpKind::Copy),
3811        // Phase 3 of the in-place ops infrastructure: each in-place Op
3812        // variant maps to its OpKind so the binding-table dispatch can
3813        // resolve a kernel. The executor's dedicated WorkItemKind
3814        // arms (added alongside) handle the storage-Arc adoption.
3815        Op::ReluInplace => Some(OpKind::ReluInplace),
3816        Op::SiluInplace => Some(OpKind::SiluInplace),
3817        Op::GeluTanhInplace => Some(OpKind::GeluTanhInplace),
3818        Op::TanhInplace => Some(OpKind::TanhInplace),
3819        Op::SigmoidInplace => Some(OpKind::SigmoidInplace),
3820        Op::NegInplace => Some(OpKind::NegInplace),
3821        Op::AbsInplace => Some(OpKind::AbsInplace),
3822        Op::SqrInplace => Some(OpKind::SqrInplace),
3823        Op::SqrtInplace => Some(OpKind::SqrtInplace),
3824        Op::RsqrtInplace => Some(OpKind::RsqrtInplace),
3825        Op::RecipInplace => Some(OpKind::RecipInplace),
3826        Op::ExpInplace => Some(OpKind::ExpInplace),
3827        Op::LogInplace => Some(OpKind::LogInplace),
3828        Op::SinInplace => Some(OpKind::SinInplace),
3829        Op::CosInplace => Some(OpKind::CosInplace),
3830        Op::SignInplace => Some(OpKind::SignInplace),
3831        Op::FloorInplace => Some(OpKind::FloorInplace),
3832        Op::CeilInplace => Some(OpKind::CeilInplace),
3833        Op::RoundInplace => Some(OpKind::RoundInplace),
3834        Op::ErfInplace => Some(OpKind::ErfInplace),
3835        Op::GeluInplace => Some(OpKind::GeluInplace),
3836        Op::ClampInplace { .. } => Some(OpKind::ClampInplace),
3837        Op::PowIInplace(_) => Some(OpKind::PowIInplace),
3838        // In-place binary variants (Add/Sub/Mul/Div/MaskedFill) and
3839        // their OpKind siblings are tracked by a parallel session and
3840        // toggle in and out of the Op enum as that work progresses.
3841        // No multi-output arm references them; nothing to map here in
3842        // the current HEAD.
3843        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::INPLACE_AFFINE => {
3844            Some(OpKind::InplaceAffine)
3845        }
3846        Op::Fused(fid, _)
3847            if *fid == fuel_graph::registry::FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY =>
3848        {
3849            Some(OpKind::FusedSoftmaxCrossEntropy)
3850        }
3851        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::CAUSAL_CONV1D => {
3852            Some(OpKind::CausalConv1d)
3853        }
3854        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SELECTIVE_SCAN => {
3855            Some(OpKind::SelectiveScan)
3856        }
3857        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SSD_CHUNK_SCAN => {
3858            Some(OpKind::SsdChunkScan)
3859        }
3860        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::NF4_MATMUL => {
3861            Some(OpKind::Nf4Matmul)
3862        }
3863        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::AWQ_MATMUL => {
3864            Some(OpKind::AwqMatmul)
3865        }
3866        // Phase 3a (post-9c): Op::Alloc + Op::ZeroFill are structural
3867        // ops dispatched directly via `WorkItemKind::Alloc` /
3868        // `WorkItemKind::ZeroFill` (no binding-table lookup).
3869        // `compile_plan` skips these.
3870        Op::Alloc { .. } | Op::ZeroFill => None,
3871        _ => None,
3872    }
3873}
3874
3875/// Build the [`OpParams`] for `node`'s op. Most ops use
3876/// `OpParams::None`; reductions / matmul / conv / slice carry their
3877/// op-specific extras here. The graph is consulted to read input
3878/// shapes (e.g. reductions need the input shape to walk the
3879/// multi-index — Storage only carries bytes + dtype).
3880///
3881/// Phase C — extends as op families migrate. Returns Err if a
3882/// graph-shape lookup fails (currently can't, but the signature is
3883/// `Result` so future cases needing validation slot in cleanly).
3884/// Encode an `f64` value into the byte pattern of `dtype`. Used by
3885/// `Op::Pad` (Constant mode) to pre-convert the fill value once at
3886/// op_params time, so the kernel itself stays dtype-agnostic.
3887fn encode_value_to_bytes(dtype: DType, value: f64) -> Result<Vec<u8>> {
3888    match dtype {
3889        DType::F32 => Ok((value as f32).to_le_bytes().to_vec()),
3890        DType::F64 => Ok(value.to_le_bytes().to_vec()),
3891        DType::BF16 => Ok(half::bf16::from_f32(value as f32).to_le_bytes().to_vec()),
3892        DType::F16 => Ok(half::f16::from_f32(value as f32).to_le_bytes().to_vec()),
3893        DType::U8 => Ok(vec![value as u8]),
3894        DType::U32 => Ok((value as u32).to_le_bytes().to_vec()),
3895        other => Err(Error::Msg(format!(
3896            "encode_value_to_bytes: dtype {other:?} not yet supported for Pad fill",
3897        ))
3898        .bt()),
3899    }
3900}
3901
3902/// Encode a typed `Scalar` to its little-endian byte representation.
3903/// Used by Op::MaskedFill so the kernel only sees bytes — never has
3904/// to know the value's dtype.
3905fn scalar_to_bytes(s: fuel_ir::Scalar) -> Vec<u8> {
3906    use fuel_ir::Scalar;
3907    match s {
3908        Scalar::U8(v) => vec![v],
3909        Scalar::I8(v) => vec![v as u8],
3910        Scalar::U32(v) => v.to_le_bytes().to_vec(),
3911        Scalar::I16(v) => v.to_le_bytes().to_vec(),
3912        Scalar::I32(v) => v.to_le_bytes().to_vec(),
3913        Scalar::I64(v) => v.to_le_bytes().to_vec(),
3914        Scalar::BF16(v) => v.to_le_bytes().to_vec(),
3915        Scalar::F16(v) => v.to_le_bytes().to_vec(),
3916        Scalar::F32(v) => v.to_le_bytes().to_vec(),
3917        Scalar::F64(v) => v.to_le_bytes().to_vec(),
3918        Scalar::Bool(b) => vec![b as u8],
3919        Scalar::F8E4M3(v) => vec![v.to_bits()],
3920        Scalar::F8E5M2(v) => vec![v.to_bits()],
3921        // OCP-MX E8M0 block scale is a raw byte on the wire (`2^(X-127)`,
3922        // decoded kernel-side); a single byte is its own LE encoding.
3923        Scalar::F8E8M0(v) => vec![v],
3924    }
3925}
3926
3927fn op_to_op_params(
3928    graph: &Graph,
3929    node: &Node,
3930    node_id: NodeId,
3931    layout_cache: &HashMap<NodeId, Layout>,
3932    sym_env: &SymEnv,
3933) -> Result<OpParams> {
3934    // Helper: read an input's layout from the compiler-thread-local
3935    // cache (which is current within the realize call), falling back
3936    // to the graph's side-table if the input wasn't visited (which
3937    // shouldn't happen in topo order, but the fallback keeps the
3938    // path safe).
3939    let input_layout = |input_id: NodeId| -> Layout {
3940        layout_cache
3941            .get(&input_id)
3942            .cloned()
3943            .unwrap_or_else(|| graph.layout(input_id))
3944    };
3945    Ok(match &node.op {
3946        // Phase 7.6 step 5 (final): legacy `Op::QMatMul` arm dropped.
3947        Op::Fused(_, fuel_graph::registry::FusedOpParams::QMatMul { quant_type, k, n }) => {
3948            // Inputs: (activations f32 [..., m, k], weight_bytes
3949            // u32-typed). Output shape (this Node's shape) is
3950            // [..., m, n]. Flatten leading dims into batch_count.
3951            if node.inputs.len() != 2 {
3952                return Err(Error::Msg(format!(
3953                    "Op::QMatMul expects 2 inputs (activations, weight_bytes), got {}",
3954                    node.inputs.len(),
3955                ))
3956                .bt());
3957            }
3958            let act_layout = input_layout(node.inputs[0]);
3959            let act_dims = act_layout.shape().dims();
3960            if act_dims.len() < 2 {
3961                return Err(Error::Msg(format!(
3962                    "Op::QMatMul: activations must be rank ≥ 2, got {act_dims:?}",
3963                ))
3964                .bt());
3965            }
3966            let m = act_dims[act_dims.len() - 2];
3967            let k_act = act_dims[act_dims.len() - 1];
3968            if k_act != *k {
3969                return Err(Error::Msg(format!(
3970                    "Op::QMatMul: activation last dim ({k_act}) must equal Op's k ({k})",
3971                ))
3972                .bt());
3973            }
3974            let batch_count: usize = act_dims[..act_dims.len() - 2].iter().product();
3975            OpParams::QMatMul {
3976                quant_type: *quant_type,
3977                batch_count,
3978                m,
3979                n: *n,
3980                k: *k,
3981            }
3982        }
3983        Op::ArgMaxDim(d) | Op::ArgMinDim(d) => {
3984            // Reuse OpParams::Reduce — same shape contract; the
3985            // single reduce dim is the argmax/argmin axis. Input
3986            // layout flows through KernelRef's `layouts[0]`.
3987            OpParams::Reduce {
3988                dims: vec![*d],
3989                keepdim: false,
3990            }
3991        }
3992        Op::SumDim(d) | Op::MaxDim(d) | Op::MinDim(d) | Op::MeanDim(d) => OpParams::Reduce {
3993            dims: vec![*d],
3994            keepdim: false,
3995        },
3996        Op::SumAll | Op::MaxAll | Op::MinAll | Op::MeanAll => {
3997            let il = input_layout(node.inputs[0]);
3998            let rank = il.shape().rank();
3999            OpParams::Reduce {
4000                dims: (0..rank).collect(),
4001                keepdim: false,
4002            }
4003        }
4004        Op::MatMul => {
4005            // Batched matmul: lhs `[..lhs_batch.., m, k]` @
4006            // rhs `[..rhs_batch.., k, n]` → out `[..lhs_batch.., m, n]`.
4007            // Per-axis the batch dims either match or follow GQA-style
4008            // divisibility (lhs_dim > rhs_dim && lhs_dim % rhs_dim == 0);
4009            // the kernel honors the latter via `rhs_idx = lhs_idx / n_rep`.
4010            if node.inputs.len() != 2 {
4011                return Err(Error::Msg(format!(
4012                    "Op::MatMul expects 2 inputs, got {}",
4013                    node.inputs.len(),
4014                ))
4015                .bt());
4016            }
4017            let lhs = input_layout(node.inputs[0]);
4018            let rhs = input_layout(node.inputs[1]);
4019            let lhs_dims = lhs.shape().dims();
4020            let rhs_dims = rhs.shape().dims();
4021            if lhs_dims.len() < 2 || rhs_dims.len() < 2 {
4022                return Err(Error::Msg(format!(
4023                    "Op::MatMul requires both inputs rank ≥ 2; got lhs={:?} rhs={:?}",
4024                    lhs_dims, rhs_dims,
4025                ))
4026                .bt());
4027            }
4028            if lhs_dims.len() != rhs_dims.len() {
4029                return Err(Error::Msg(format!(
4030                    "Op::MatMul: ranks must match (auto-broadcast happens at \
4031                     graph construction time); got lhs rank {} vs rhs rank {}",
4032                    lhs_dims.len(),
4033                    rhs_dims.len(),
4034                ))
4035                .bt());
4036            }
4037            let rank = lhs_dims.len();
4038            let batch_rank = rank - 2;
4039            // Per-axis validation: equal or GQA-divisible.
4040            for i in 0..batch_rank {
4041                let la = lhs_dims[i];
4042                let ra = rhs_dims[i];
4043                let ok = la == ra || (ra > 0 && la > ra && la % ra == 0);
4044                if !ok {
4045                    return Err(Error::Msg(format!(
4046                        "Op::MatMul: batch dim {i} disallowed combination \
4047                         (lhs={la}, rhs={ra}); must be equal or \
4048                         GQA-divisible (lhs > rhs && lhs % rhs == 0)",
4049                    ))
4050                    .bt());
4051                }
4052            }
4053            let lhs_batch_dims: Vec<usize> = lhs_dims[..batch_rank].to_vec();
4054            let rhs_batch_dims: Vec<usize> = rhs_dims[..batch_rank].to_vec();
4055            let (m, k_lhs) = (lhs_dims[rank - 2], lhs_dims[rank - 1]);
4056            let (k_rhs, n) = (rhs_dims[rank - 2], rhs_dims[rank - 1]);
4057            if k_lhs != k_rhs {
4058                return Err(Error::Msg(format!(
4059                    "Op::MatMul: contracting dims disagree — lhs trailing is \
4060                     [{m}, {k_lhs}], rhs trailing is [{k_rhs}, {n}]",
4061                ))
4062                .bt());
4063            }
4064            // Data-determined-M (sparse-MoE): a side-table row count makes
4065            // `m` the capacity and this the compute count. Dual-path,
4066            // mirroring WriteSlice: resolve in the compile-time SymEnv
4067            // (static / input-determined) now; else DEFER a producer-bound
4068            // sym to execute; else it is a genuine caller error.
4069            let m_compute = match graph.matmul_row_count(node_id) {
4070                None => MatmulM::All,
4071                Some(dyn_m) => match dyn_m.resolve(sym_env) {
4072                    Some(c) => {
4073                        if c > m {
4074                            return Err(Error::Msg(format!(
4075                                "Op::MatMul: resolved row count {c} exceeds capacity {m}",
4076                            ))
4077                            .bt());
4078                        }
4079                        MatmulM::Rows(c)
4080                    }
4081                    None => match dyn_m {
4082                        fuel_ir::DynScalar::Sym(s) if graph.binds_data_determined_sym(s) => {
4083                            MatmulM::Deferred(dyn_m)
4084                        }
4085                        _ => {
4086                            return Err(Error::Msg(format!(
4087                                "Op::MatMul: dynamic row count {dyn_m:?} is unbound in the \
4088                                 SymEnv at compile and no producer binds it (not \
4089                                 data-determined)",
4090                            ))
4091                            .bt());
4092                        }
4093                    },
4094                },
4095            };
4096            OpParams::Matmul {
4097                lhs_batch_dims,
4098                rhs_batch_dims,
4099                m,
4100                n,
4101                k: k_lhs,
4102                m_compute,
4103            }
4104        }
4105        // Phase 7.6 step 4: legacy `Op::FusedLinear` and registry-extended
4106        // `Op::Fused(FUSED_LINEAR, _)` share the same shape contract and
4107        // params encoding (reuses OpParams::Matmul). One body covers both.
4108        op if op_is_fused_linear(op) => {
4109            // Inputs: [a, b, bias]. Same shape semantics as MatMul on
4110            // a/b; bias is rank-1 [N] and broadcasts along all leading
4111            // dims. We reuse OpParams::Matmul (kernel reads bias from
4112            // inputs[2] directly).
4113            if node.inputs.len() != 3 {
4114                return Err(Error::Msg(format!(
4115                    "Op::FusedLinear expects 3 inputs (a, b, bias), got {}",
4116                    node.inputs.len(),
4117                ))
4118                .bt());
4119            }
4120            let lhs = input_layout(node.inputs[0]);
4121            let rhs = input_layout(node.inputs[1]);
4122            let bias = input_layout(node.inputs[2]);
4123            let lhs_dims = lhs.shape().dims();
4124            let rhs_dims = rhs.shape().dims();
4125            let bias_dims = bias.shape().dims();
4126            if lhs_dims.len() < 2 || rhs_dims.len() < 2 {
4127                return Err(Error::Msg(format!(
4128                    "Op::FusedLinear requires both a, b rank ≥ 2; got a={:?} b={:?}",
4129                    lhs_dims, rhs_dims,
4130                ))
4131                .bt());
4132            }
4133            if lhs_dims.len() != rhs_dims.len() {
4134                return Err(Error::Msg(format!(
4135                    "Op::FusedLinear: ranks must match (auto-broadcast happens at \
4136                     graph construction time); got a rank {} vs b rank {}",
4137                    lhs_dims.len(),
4138                    rhs_dims.len(),
4139                ))
4140                .bt());
4141            }
4142            let rank = lhs_dims.len();
4143            let batch_rank = rank - 2;
4144            for i in 0..batch_rank {
4145                let la = lhs_dims[i];
4146                let ra = rhs_dims[i];
4147                let ok = la == ra || (ra > 0 && la > ra && la % ra == 0);
4148                if !ok {
4149                    return Err(Error::Msg(format!(
4150                        "Op::FusedLinear: batch dim {i} disallowed (a={la}, b={ra})",
4151                    ))
4152                    .bt());
4153                }
4154            }
4155            let lhs_batch_dims: Vec<usize> = lhs_dims[..batch_rank].to_vec();
4156            let rhs_batch_dims: Vec<usize> = rhs_dims[..batch_rank].to_vec();
4157            let (m, k_lhs) = (lhs_dims[rank - 2], lhs_dims[rank - 1]);
4158            let (k_rhs, n) = (rhs_dims[rank - 2], rhs_dims[rank - 1]);
4159            if k_lhs != k_rhs {
4160                return Err(Error::Msg(format!(
4161                    "Op::FusedLinear: contracting dims disagree — a trailing is \
4162                     [{m}, {k_lhs}], b trailing is [{k_rhs}, {n}]",
4163                ))
4164                .bt());
4165            }
4166            if bias_dims.len() != 1 || bias_dims[0] != n {
4167                return Err(Error::Msg(format!(
4168                    "Op::FusedLinear: bias must be rank-1 [{n}], got {bias_dims:?}",
4169                ))
4170                .bt());
4171            }
4172            OpParams::Matmul {
4173                lhs_batch_dims,
4174                rhs_batch_dims,
4175                m,
4176                n,
4177                k: k_lhs,
4178                // FusedLinear is always static-M (dense linear layer).
4179                m_compute: MatmulM::All,
4180            }
4181        }
4182        // FusedSoftmaxCrossEntropy: flatten logits `[..., V]` to
4183        // `[n_rows, V]` for the kernel. n_rows is the product of all
4184        // leading dims (≥1 even for rank-1 logits, where targets are
4185        // a scalar). The kernel walks rows internally.
4186        Op::Fused(
4187            _,
4188            fuel_graph::registry::FusedOpParams::FusedSoftmaxCrossEntropy {
4189                reduction,
4190                ignore_index,
4191            },
4192        ) => {
4193            if node.inputs.len() != 2 {
4194                return Err(Error::Msg(format!(
4195                    "FusedSoftmaxCrossEntropy expects 2 inputs (logits, targets), got {}",
4196                    node.inputs.len(),
4197                ))
4198                .bt());
4199            }
4200            let logits_layout = input_layout(node.inputs[0]);
4201            let logits_dims = logits_layout.shape().dims();
4202            if logits_dims.is_empty() {
4203                return Err(Error::Msg(
4204                    "FusedSoftmaxCrossEntropy: logits must have rank ≥ 1".to_string(),
4205                )
4206                .bt());
4207            }
4208            let vocab = *logits_dims.last().unwrap();
4209            let n_rows: usize = logits_dims[..logits_dims.len() - 1]
4210                .iter()
4211                .product::<usize>()
4212                .max(1);
4213            let targets_layout = input_layout(node.inputs[1]);
4214            let target_count: usize = targets_layout
4215                .shape()
4216                .dims()
4217                .iter()
4218                .product::<usize>()
4219                .max(1);
4220            if target_count != n_rows {
4221                return Err(Error::Msg(format!(
4222                    "FusedSoftmaxCrossEntropy: targets element count {target_count} must \
4223                     equal logits row count {n_rows} (logits {logits_dims:?}, targets {:?})",
4224                    targets_layout.shape().dims(),
4225                ))
4226                .bt());
4227            }
4228            OpParams::FusedSoftmaxCrossEntropy {
4229                n_rows,
4230                vocab,
4231                reduction: *reduction,
4232                ignore_index: *ignore_index,
4233            }
4234        }
4235        // CausalConv1d: derive (batch, channels, seq_in, seq_out, kernel)
4236        // from the input layouts. x is `[batch, channels, seq_in]`
4237        // (caller pre-pads with kernel-1 zeros), weight is
4238        // `[channels, 1, kernel]`. seq_out = seq_in - (kernel - 1).
4239        Op::Fused(_, fuel_graph::registry::FusedOpParams::CausalConv1d { use_silu }) => {
4240            if node.inputs.len() != 3 {
4241                return Err(Error::Msg(format!(
4242                    "CausalConv1d expects 3 inputs (x, weight, bias), got {}",
4243                    node.inputs.len(),
4244                ))
4245                .bt());
4246            }
4247            let x_layout = input_layout(node.inputs[0]);
4248            let w_layout = input_layout(node.inputs[1]);
4249            let x_dims = x_layout.shape().dims();
4250            let w_dims = w_layout.shape().dims();
4251            if x_dims.len() != 3 {
4252                return Err(Error::Msg(format!(
4253                    "CausalConv1d: x must be rank 3 [batch, channels, seq+pad], got {x_dims:?}",
4254                ))
4255                .bt());
4256            }
4257            if w_dims.len() != 3 {
4258                return Err(Error::Msg(format!(
4259                    "CausalConv1d: weight must be rank 3 [channels, 1, kernel], got {w_dims:?}",
4260                ))
4261                .bt());
4262            }
4263            let batch = x_dims[0];
4264            let channels = x_dims[1];
4265            let seq_in = x_dims[2];
4266            let kernel = w_dims[2];
4267            if seq_in < kernel - 1 {
4268                return Err(Error::Msg(format!(
4269                    "CausalConv1d: x time dim {seq_in} must be ≥ kernel-1 = {} \
4270                     (caller must pre-pad with kernel-1 zeros)",
4271                    kernel - 1,
4272                ))
4273                .bt());
4274            }
4275            let seq_out = seq_in - (kernel - 1);
4276            OpParams::CausalConv1d {
4277                batch,
4278                channels,
4279                seq_in,
4280                seq_out,
4281                kernel,
4282                use_silu: *use_silu,
4283            }
4284        }
4285        // SelectiveScan: derive (batch, seqlen, dim, dstate) from the
4286        // input layouts. u: [batch, seqlen, dim]; a: [dim, dstate].
4287        Op::Fused(_, fuel_graph::registry::FusedOpParams::SelectiveScan { delta_softplus }) => {
4288            if node.inputs.len() != 5 {
4289                return Err(Error::Msg(format!(
4290                    "SelectiveScan expects 5 inputs (u, delta, a, b, c), got {}",
4291                    node.inputs.len(),
4292                ))
4293                .bt());
4294            }
4295            let u_layout = input_layout(node.inputs[0]);
4296            let a_layout = input_layout(node.inputs[2]);
4297            let u_dims = u_layout.shape().dims();
4298            let a_dims = a_layout.shape().dims();
4299            if u_dims.len() != 3 {
4300                return Err(Error::Msg(format!(
4301                    "SelectiveScan: u must be rank 3 [batch, seqlen, dim], got {u_dims:?}",
4302                ))
4303                .bt());
4304            }
4305            if a_dims.len() != 2 {
4306                return Err(Error::Msg(format!(
4307                    "SelectiveScan: a must be rank 2 [dim, dstate], got {a_dims:?}",
4308                ))
4309                .bt());
4310            }
4311            let batch = u_dims[0];
4312            let seqlen = u_dims[1];
4313            let dim = u_dims[2];
4314            let dstate = a_dims[1];
4315            if a_dims[0] != dim {
4316                return Err(Error::Msg(format!(
4317                    "SelectiveScan: a's first dim {} must equal dim {dim}",
4318                    a_dims[0],
4319                ))
4320                .bt());
4321            }
4322            OpParams::SelectiveScan {
4323                batch,
4324                seqlen,
4325                dim,
4326                dstate,
4327                delta_softplus: *delta_softplus,
4328            }
4329        }
4330        // SsdChunkScan: derive (batch, seqlen, heads, head_dim,
4331        // state_dim) from x and b layouts. x: [batch, seqlen, heads,
4332        // head_dim]; b: [batch, seqlen, heads, state_dim].
4333        Op::Fused(_, fuel_graph::registry::FusedOpParams::SsdChunkScan { chunk_size }) => {
4334            if node.inputs.len() != 5 {
4335                return Err(Error::Msg(format!(
4336                    "SsdChunkScan expects 5 inputs (x, dt, a, b, c), got {}",
4337                    node.inputs.len(),
4338                ))
4339                .bt());
4340            }
4341            let x_layout = input_layout(node.inputs[0]);
4342            let b_layout = input_layout(node.inputs[3]);
4343            let x_dims = x_layout.shape().dims();
4344            let b_dims = b_layout.shape().dims();
4345            if x_dims.len() != 4 {
4346                return Err(Error::Msg(format!(
4347                    "SsdChunkScan: x must be rank 4 [batch, seqlen, heads, head_dim], got {x_dims:?}",
4348                ))
4349                .bt());
4350            }
4351            if b_dims.len() != 4 {
4352                return Err(Error::Msg(format!(
4353                    "SsdChunkScan: b must be rank 4 [batch, seqlen, heads, state_dim], got {b_dims:?}",
4354                ))
4355                .bt());
4356            }
4357            let batch = x_dims[0];
4358            let seqlen = x_dims[1];
4359            let heads = x_dims[2];
4360            let head_dim = x_dims[3];
4361            let state_dim = b_dims[3];
4362            OpParams::SsdChunkScan {
4363                batch,
4364                seqlen,
4365                heads,
4366                head_dim,
4367                state_dim,
4368                chunk_size: *chunk_size,
4369            }
4370        }
4371        // Nf4Matmul: derive (batch, m, n, k) from activations + w_packed
4372        // layouts. activations: [..., m, k] (leading dims flatten into
4373        // batch); w_packed: [n, k/2] U8.
4374        Op::Fused(_, fuel_graph::registry::FusedOpParams::Nf4Matmul { block_size }) => {
4375            if node.inputs.len() != 3 {
4376                return Err(Error::Msg(format!(
4377                    "Nf4Matmul expects 3 inputs (activations, w_packed, absmax), got {}",
4378                    node.inputs.len(),
4379                ))
4380                .bt());
4381            }
4382            let a_layout = input_layout(node.inputs[0]);
4383            let w_layout = input_layout(node.inputs[1]);
4384            let a_dims = a_layout.shape().dims();
4385            let w_dims = w_layout.shape().dims();
4386            if a_dims.len() < 2 {
4387                return Err(Error::Msg(format!(
4388                    "Nf4Matmul: activations must be rank ≥ 2, got {a_dims:?}",
4389                ))
4390                .bt());
4391            }
4392            if w_dims.len() != 2 {
4393                return Err(Error::Msg(format!(
4394                    "Nf4Matmul: w_packed must be rank 2 [n, k/2], got {w_dims:?}",
4395                ))
4396                .bt());
4397            }
4398            let m = a_dims[a_dims.len() - 2];
4399            let k = a_dims[a_dims.len() - 1];
4400            let n = w_dims[0];
4401            let batch: usize = a_dims[..a_dims.len() - 2].iter().product::<usize>().max(1);
4402            if k % 2 != 0 {
4403                return Err(Error::Msg(format!(
4404                    "Nf4Matmul: k={k} must be even (w_packed holds 2 nibbles per byte along k)",
4405                ))
4406                .bt());
4407            }
4408            if k % *block_size != 0 {
4409                return Err(Error::Msg(format!(
4410                    "Nf4Matmul: k={k} must be a multiple of block_size={block_size}",
4411                ))
4412                .bt());
4413            }
4414            if w_dims[1] != k / 2 {
4415                return Err(Error::Msg(format!(
4416                    "Nf4Matmul: w_packed second dim {} must equal k/2 = {}",
4417                    w_dims[1],
4418                    k / 2,
4419                ))
4420                .bt());
4421            }
4422            OpParams::Nf4Matmul {
4423                batch,
4424                m,
4425                n,
4426                k,
4427                block_size: *block_size,
4428            }
4429        }
4430        // AwqMatmul: (batch, m, n, k) from activations [..., m, k] and the
4431        // kernel-layout weight [n, k/8]; the padded zeros/scales widths are the
4432        // op's own build-time invariant (checked by `awq_matmul`).
4433        Op::Fused(
4434            _,
4435            fuel_graph::registry::FusedOpParams::AwqMatmul {
4436                group_size,
4437                split_k_iters,
4438            },
4439        ) => {
4440            if node.inputs.len() != 4 {
4441                return Err(Error::Msg(format!(
4442                    "AwqMatmul expects 4 inputs (activations, weight, zeros, scales), got {}",
4443                    node.inputs.len(),
4444                ))
4445                .bt());
4446            }
4447            let a_layout = input_layout(node.inputs[0]);
4448            let w_layout = input_layout(node.inputs[1]);
4449            let a_dims = a_layout.shape().dims();
4450            let w_dims = w_layout.shape().dims();
4451            if a_dims.len() < 2 {
4452                return Err(Error::Msg(format!(
4453                    "AwqMatmul: activations must be rank ≥ 2, got {a_dims:?}",
4454                ))
4455                .bt());
4456            }
4457            if w_dims.len() != 2 {
4458                return Err(Error::Msg(format!(
4459                    "AwqMatmul: weight must be rank 2 [n, k/8], got {w_dims:?}",
4460                ))
4461                .bt());
4462            }
4463            let m = a_dims[a_dims.len() - 2];
4464            let k = a_dims[a_dims.len() - 1];
4465            let n = w_dims[0];
4466            let batch: usize = a_dims[..a_dims.len() - 2].iter().product::<usize>().max(1);
4467            if k % 8 != 0 || w_dims[1] != k / 8 {
4468                return Err(Error::Msg(format!(
4469                    "AwqMatmul: weight second dim {} must equal k/8 for k={k} (a multiple of 8)",
4470                    w_dims[1],
4471                ))
4472                .bt());
4473            }
4474            OpParams::AwqMatmul {
4475                batch,
4476                m,
4477                n,
4478                k,
4479                group_size: *group_size,
4480                split_k_iters: *split_k_iters,
4481            }
4482        }
4483        // Phase 7.6 step 3: SoftmaxLastDim flows through
4484        // `Op::Fused(FusedOps::SOFTMAX_LAST_DIM, _)`. The
4485        // SOFTMAX_LAST_DIM_BACKWARD variant added in step 6
4486        // follow-up shares the same `outer × last_dim` shape
4487        // contract (input 0 is `y` for forward / forward-output
4488        // for backward; both rank-≥1 with last-dim as the
4489        // reduction axis).
4490        op if op_is_softmax_last_dim(op)
4491            || matches!(op, Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM_BACKWARD) =>
4492        {
4493            let il = input_layout(node.inputs[0]);
4494            let dims = il.shape().dims();
4495            if dims.is_empty() {
4496                return Err(Error::Msg("Op::SoftmaxLastDim requires rank ≥ 1".to_string()).bt());
4497            }
4498            let last_dim = *dims.last().unwrap();
4499            let outer_count: usize = dims[..dims.len() - 1].iter().product();
4500            OpParams::SoftmaxLastDim {
4501                outer_count,
4502                last_dim,
4503            }
4504        }
4505        Op::Flip { dim } => {
4506            // Single input. Precompute the flat-3-axis split
4507            // (outer × dim × inner) from the input shape.
4508            if node.inputs.len() != 1 {
4509                return Err(Error::Msg(format!(
4510                    "Op::Flip expects 1 input, got {}",
4511                    node.inputs.len(),
4512                ))
4513                .bt());
4514            }
4515            let in_layout = input_layout(node.inputs[0]);
4516            let in_dims = in_layout.shape().dims();
4517            if *dim >= in_dims.len() {
4518                return Err(Error::Msg(format!(
4519                    "Op::Flip: dim {dim} out of range for rank {}",
4520                    in_dims.len(),
4521                ))
4522                .bt());
4523            }
4524            let outer_count: usize = in_dims[..*dim].iter().product();
4525            let dim_size = in_dims[*dim];
4526            let inner_count: usize = in_dims[*dim + 1..].iter().product();
4527            OpParams::Flip {
4528                outer_count,
4529                dim_size,
4530                inner_count,
4531                axis: *dim,
4532            }
4533        }
4534        Op::Roll { dim, shift } => {
4535            if node.inputs.len() != 1 {
4536                return Err(Error::Msg(format!(
4537                    "Op::Roll expects 1 input, got {}",
4538                    node.inputs.len(),
4539                ))
4540                .bt());
4541            }
4542            let in_layout = input_layout(node.inputs[0]);
4543            let in_dims = in_layout.shape().dims();
4544            if *dim >= in_dims.len() {
4545                return Err(Error::Msg(format!(
4546                    "Op::Roll: dim {dim} out of range for rank {}",
4547                    in_dims.len(),
4548                ))
4549                .bt());
4550            }
4551            let outer_count: usize = in_dims[..*dim].iter().product();
4552            let dim_size = in_dims[*dim];
4553            let inner_count: usize = in_dims[*dim + 1..].iter().product();
4554            OpParams::Roll {
4555                outer_count,
4556                dim_size,
4557                inner_count,
4558                shift: *shift,
4559                axis: *dim,
4560            }
4561        }
4562        Op::CumSum { dim } => {
4563            if node.inputs.len() != 1 {
4564                return Err(Error::Msg(format!(
4565                    "Op::CumSum expects 1 input, got {}",
4566                    node.inputs.len(),
4567                ))
4568                .bt());
4569            }
4570            let in_layout = input_layout(node.inputs[0]);
4571            let in_dims = in_layout.shape().dims();
4572            if *dim >= in_dims.len() {
4573                return Err(Error::Msg(format!(
4574                    "Op::CumSum: dim {dim} out of range for rank {}",
4575                    in_dims.len(),
4576                ))
4577                .bt());
4578            }
4579            let outer_count: usize = in_dims[..*dim].iter().product();
4580            let dim_size = in_dims[*dim];
4581            let inner_count: usize = in_dims[*dim + 1..].iter().product();
4582            OpParams::CumSum {
4583                outer_count,
4584                dim_size,
4585                inner_count,
4586                axis: *dim,
4587            }
4588        }
4589        Op::Triu { diagonal } | Op::Tril { diagonal } => {
4590            if node.inputs.len() != 1 {
4591                return Err(Error::Msg(format!(
4592                    "Op::Triu/Tril expects 1 input, got {}",
4593                    node.inputs.len(),
4594                ))
4595                .bt());
4596            }
4597            let in_layout = input_layout(node.inputs[0]);
4598            let in_dims = in_layout.shape().dims();
4599            if in_dims.len() < 2 {
4600                return Err(Error::Msg(format!(
4601                    "Op::Triu/Tril requires rank >= 2, got {}",
4602                    in_dims.len(),
4603                ))
4604                .bt());
4605            }
4606            let rows = in_dims[in_dims.len() - 2];
4607            let cols = in_dims[in_dims.len() - 1];
4608            let batch_count: usize = in_dims[..in_dims.len() - 2]
4609                .iter()
4610                .product::<usize>()
4611                .max(1);
4612            OpParams::Triangular {
4613                batch_count,
4614                rows,
4615                cols,
4616                diagonal: *diagonal,
4617            }
4618        }
4619        Op::LogSoftmaxLastDim => {
4620            if node.inputs.len() != 1 {
4621                return Err(Error::Msg(format!(
4622                    "Op::LogSoftmaxLastDim expects 1 input, got {}",
4623                    node.inputs.len(),
4624                ))
4625                .bt());
4626            }
4627            let in_layout = input_layout(node.inputs[0]);
4628            let in_dims = in_layout.shape().dims();
4629            if in_dims.is_empty() {
4630                return Err(Error::Msg("Op::LogSoftmaxLastDim requires rank ≥ 1".to_string()).bt());
4631            }
4632            let last_dim = *in_dims.last().unwrap();
4633            let outer_count: usize = in_dims[..in_dims.len() - 1].iter().product();
4634            OpParams::LogSoftmaxLastDim {
4635                outer_count,
4636                last_dim,
4637            }
4638        }
4639        Op::LogSoftmaxLastDimBackward => {
4640            // Inputs: (forward_output_y, upstream_grad). Same shape contract
4641            // as SoftmaxLastDimBackward — last-dim row-wise dispatch.
4642            if node.inputs.len() != 2 {
4643                return Err(Error::Msg(format!(
4644                    "Op::LogSoftmaxLastDimBackward expects 2 inputs, got {}",
4645                    node.inputs.len(),
4646                ))
4647                .bt());
4648            }
4649            let in_layout = input_layout(node.inputs[0]);
4650            let in_dims = in_layout.shape().dims();
4651            if in_dims.is_empty() {
4652                return Err(Error::Msg(
4653                    "Op::LogSoftmaxLastDimBackward requires rank ≥ 1".to_string(),
4654                )
4655                .bt());
4656            }
4657            let last_dim = *in_dims.last().unwrap();
4658            let outer_count: usize = in_dims[..in_dims.len() - 1].iter().product();
4659            OpParams::LogSoftmaxLastDim {
4660                outer_count,
4661                last_dim,
4662            }
4663        }
4664        Op::MaskedFill { value } => {
4665            if node.inputs.len() != 2 {
4666                return Err(Error::Msg(format!(
4667                    "Op::MaskedFill expects 2 inputs (x, mask), got {}",
4668                    node.inputs.len(),
4669                ))
4670                .bt());
4671            }
4672            let fill_bytes = scalar_to_bytes(*value);
4673            OpParams::MaskedFill { fill_bytes }
4674        }
4675        // Op::MaskedFillInplace tracked by the parallel in-place
4676        // binary family session — not in HEAD's Op enum right now.
4677        Op::PadBackward {
4678            in_shape,
4679            padding,
4680            mode,
4681        } => {
4682            // Single input is the upstream gradient; output is the
4683            // input gradient (shape == `in_shape`).
4684            if node.inputs.len() != 1 {
4685                return Err(Error::Msg(format!(
4686                    "Op::PadBackward expects 1 input, got {}",
4687                    node.inputs.len(),
4688                ))
4689                .bt());
4690            }
4691            let in_dims: Vec<usize> = in_shape.dims().to_vec();
4692            // Output of the original forward Pad is the input shape
4693            // of the backward (== upstream's shape).
4694            let out_dims: Vec<usize> = in_dims
4695                .iter()
4696                .zip(padding.iter())
4697                .map(|(&d, &(b, a))| d + b + a)
4698                .collect();
4699            let mode_tag: u8 = match mode {
4700                fuel_graph::PadMode::Constant => 0,
4701                fuel_graph::PadMode::Reflect => 1,
4702                fuel_graph::PadMode::Replicate => 2,
4703            };
4704            OpParams::PadBackward {
4705                in_shape: in_dims,
4706                out_shape: out_dims,
4707                padding: padding.clone(),
4708                mode_tag,
4709            }
4710        }
4711        Op::Pad {
4712            padding,
4713            mode,
4714            value,
4715        } => {
4716            if node.inputs.len() != 1 {
4717                return Err(Error::Msg(format!(
4718                    "Op::Pad expects 1 input, got {}",
4719                    node.inputs.len(),
4720                ))
4721                .bt());
4722            }
4723            let in_layout = input_layout(node.inputs[0]);
4724            let in_dims: Vec<usize> = in_layout.shape().dims().to_vec();
4725            if padding.len() != in_dims.len() {
4726                return Err(Error::Msg(format!(
4727                    "Op::Pad: padding.len() ({}) != input rank ({})",
4728                    padding.len(),
4729                    in_dims.len(),
4730                ))
4731                .bt());
4732            }
4733            let out_dims: Vec<usize> = in_dims
4734                .iter()
4735                .zip(padding.iter())
4736                .map(|(&d, &(b, a))| d + b + a)
4737                .collect();
4738            let mode_tag: u8 = match mode {
4739                fuel_graph::PadMode::Constant => 0,
4740                fuel_graph::PadMode::Reflect => 1,
4741                fuel_graph::PadMode::Replicate => 2,
4742            };
4743            // Encode fill value as bytes for the output dtype. The
4744            // kernel is dtype-agnostic — it just memcopies the
4745            // pattern. Conversion happens once here per node, not
4746            // per element in the kernel.
4747            let fill_bytes = encode_value_to_bytes(node.dtype, *value)?;
4748            OpParams::Pad {
4749                in_shape: in_dims,
4750                out_shape: out_dims,
4751                padding: padding.clone(),
4752                mode_tag,
4753                fill_bytes,
4754            }
4755        }
4756        Op::IndexAdd { dim } => {
4757            // Inputs: (base, indices, src). All same dtype except
4758            // indices is U32. Output shape == base shape.
4759            if node.inputs.len() != 3 {
4760                return Err(Error::Msg(format!(
4761                    "Op::IndexAdd expects 3 inputs (base, indices, src), got {}",
4762                    node.inputs.len(),
4763                ))
4764                .bt());
4765            }
4766            let base_layout = input_layout(node.inputs[0]);
4767            let idx_layout = input_layout(node.inputs[1]);
4768            let src_layout = input_layout(node.inputs[2]);
4769            let base_dims = base_layout.shape().dims();
4770            let idx_dims = idx_layout.shape().dims();
4771            let src_dims = src_layout.shape().dims();
4772            if *dim >= base_dims.len() {
4773                return Err(Error::Msg(format!(
4774                    "Op::IndexAdd: dim {dim} out of range for base rank {}",
4775                    base_dims.len(),
4776                ))
4777                .bt());
4778            }
4779            if idx_dims.len() != 1 {
4780                return Err(Error::Msg(format!(
4781                    "Op::IndexAdd: indices must be rank 1, got {idx_dims:?}",
4782                ))
4783                .bt());
4784            }
4785            if base_dims.len() != src_dims.len() {
4786                return Err(Error::Msg(format!(
4787                    "Op::IndexAdd: base rank ({}) != src rank ({})",
4788                    base_dims.len(),
4789                    src_dims.len(),
4790                ))
4791                .bt());
4792            }
4793            let outer_count: usize = base_dims[..*dim].iter().product();
4794            let base_dim_size = base_dims[*dim];
4795            let inner_count: usize = base_dims[*dim + 1..].iter().product();
4796            let n_indices = idx_dims[0];
4797            OpParams::IndexAdd {
4798                outer_count,
4799                base_dim_size,
4800                n_indices,
4801                inner_count,
4802            }
4803        }
4804        Op::ScatterAdd { dim } => {
4805            if node.inputs.len() != 3 {
4806                return Err(Error::Msg(format!(
4807                    "Op::ScatterAdd 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 src_layout = input_layout(node.inputs[2]);
4814            let base_shape: Vec<usize> = base_layout.shape().dims().to_vec();
4815            let src_shape: Vec<usize> = src_layout.shape().dims().to_vec();
4816            if base_shape.len() != src_shape.len() {
4817                return Err(Error::Msg(format!(
4818                    "Op::ScatterAdd: base rank ({}) != src rank ({})",
4819                    base_shape.len(),
4820                    src_shape.len(),
4821                ))
4822                .bt());
4823            }
4824            if *dim >= base_shape.len() {
4825                return Err(Error::Msg(format!(
4826                    "Op::ScatterAdd: dim {dim} out of range for rank {}",
4827                    base_shape.len(),
4828                ))
4829                .bt());
4830            }
4831            OpParams::ScatterAdd {
4832                base_shape,
4833                src_shape,
4834                dim: *dim,
4835            }
4836        }
4837        // Phase 7.6 step 5: Rope routes through the registry; the
4838        // legacy `Op::Rope` arm was retired with the variant.
4839        Op::Fused(_, fuel_graph::registry::FusedOpParams::Rope) => {
4840            // Inputs: (x, cos, sin). x is [..., seq, head_dim];
4841            // cos/sin are [seq, head_dim] (validated at graph build).
4842            if node.inputs.len() != 3 {
4843                return Err(Error::Msg(format!(
4844                    "Op::Rope expects 3 inputs (x, cos, sin), got {}",
4845                    node.inputs.len(),
4846                ))
4847                .bt());
4848            }
4849            let x_layout = input_layout(node.inputs[0]);
4850            let x_dims = x_layout.shape().dims();
4851            if x_dims.len() < 2 {
4852                return Err(
4853                    Error::Msg(format!("Op::Rope: x must have rank ≥ 2, got {x_dims:?}",)).bt(),
4854                );
4855            }
4856            let head_dim = *x_dims.last().unwrap();
4857            let seq = x_dims[x_dims.len() - 2];
4858            let outer_count: usize = x_dims[..x_dims.len() - 2].iter().product();
4859            OpParams::Rope {
4860                outer_count,
4861                seq,
4862                head_dim,
4863            }
4864        }
4865        Op::Gather { dim } => {
4866            // inputs[0] = source, inputs[1] = U32 indices (same rank).
4867            if node.inputs.len() != 2 {
4868                return Err(Error::Msg(format!(
4869                    "Op::Gather expects 2 inputs (source, indices), got {}",
4870                    node.inputs.len(),
4871                ))
4872                .bt());
4873            }
4874            let src_layout = input_layout(node.inputs[0]);
4875            let idx_layout = input_layout(node.inputs[1]);
4876            let source_shape: Vec<usize> = src_layout.shape().dims().to_vec();
4877            let output_shape: Vec<usize> = idx_layout.shape().dims().to_vec();
4878            if source_shape.len() != output_shape.len() {
4879                return Err(Error::Msg(format!(
4880                    "Op::Gather: source rank ({}) != indices rank ({})",
4881                    source_shape.len(),
4882                    output_shape.len(),
4883                ))
4884                .bt());
4885            }
4886            if *dim >= source_shape.len() {
4887                return Err(Error::Msg(format!(
4888                    "Op::Gather: dim {dim} out of range for rank {}",
4889                    source_shape.len(),
4890                ))
4891                .bt());
4892            }
4893            OpParams::Gather {
4894                source_shape,
4895                output_shape,
4896                dim: *dim,
4897            }
4898        }
4899        Op::NonZeroIndices { count_sym } => {
4900            // inputs[0] = x (the value tensor). capacity == x.elem_count();
4901            // the bundled output is [indices [capacity] U32 ; count [1] U32].
4902            if node.inputs.len() != 1 {
4903                return Err(Error::Msg(format!(
4904                    "Op::NonZeroIndices expects 1 input, got {}",
4905                    node.inputs.len(),
4906                ))
4907                .bt());
4908            }
4909            let x_layout = input_layout(node.inputs[0]);
4910            let capacity = x_layout.shape().elem_count();
4911            OpParams::NonZeroIndices {
4912                capacity,
4913                count_sym: *count_sym,
4914            }
4915        }
4916        Op::IndexSelect { dim } => {
4917            // inputs[0] = source, inputs[1] = U32 indices (rank 1).
4918            if node.inputs.len() != 2 {
4919                return Err(Error::Msg(format!(
4920                    "Op::IndexSelect expects 2 inputs (source, indices), got {}",
4921                    node.inputs.len(),
4922                ))
4923                .bt());
4924            }
4925            let src_layout = input_layout(node.inputs[0]);
4926            let idx_layout = input_layout(node.inputs[1]);
4927            let src_dims = src_layout.shape().dims();
4928            let idx_dims = idx_layout.shape().dims();
4929            if *dim >= src_dims.len() {
4930                return Err(Error::Msg(format!(
4931                    "Op::IndexSelect: dim {dim} out of range for source rank {}",
4932                    src_dims.len(),
4933                ))
4934                .bt());
4935            }
4936            if idx_dims.len() != 1 {
4937                return Err(Error::Msg(format!(
4938                    "Op::IndexSelect: indices must be rank 1, got shape {idx_dims:?}",
4939                ))
4940                .bt());
4941            }
4942            let outer_count: usize = src_dims[..*dim].iter().product();
4943            let source_dim_size = src_dims[*dim];
4944            let inner_count: usize = src_dims[*dim + 1..].iter().product();
4945            let n_indices = idx_dims[0];
4946            OpParams::IndexSelect {
4947                outer_count,
4948                source_dim_size,
4949                n_indices,
4950                inner_count,
4951            }
4952        }
4953        // Phase 7.6 step 5: legacy `Op::RmsNormLastDim` /
4954        // `Op::LayerNormLastDim` arms retired with the variants;
4955        // both now route through `Op::Fused(NORM_LAST_DIM, _)`.
4956        // Step 6 follow-up extends this arm to also cover the
4957        // backward variants (same outer × last_dim + eps geometry).
4958        Op::Fused(fid, params)
4959            if *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM
4960                || *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM
4961                || *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM_BACKWARD
4962                || *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM_BACKWARD =>
4963        {
4964            let eps = match params {
4965                fuel_graph::registry::FusedOpParams::RmsNormLastDim { eps } => *eps,
4966                fuel_graph::registry::FusedOpParams::LayerNormLastDim { eps } => *eps,
4967                fuel_graph::registry::FusedOpParams::RmsNormLastDimBackward { eps } => *eps,
4968                fuel_graph::registry::FusedOpParams::LayerNormLastDimBackward { eps } => *eps,
4969                _ => {
4970                    return Err(Error::Msg(format!(
4971                        "Op::Fused(NORM_LAST_DIM[_BACKWARD], _) expected \
4972                     RmsNormLastDim[Backward] or LayerNormLastDim[Backward] params, got {params:?}",
4973                    ))
4974                    .bt());
4975                }
4976            };
4977            let il = input_layout(node.inputs[0]);
4978            let dims = il.shape().dims();
4979            if dims.is_empty() {
4980                return Err(Error::Msg(
4981                    "Op::Fused(NORM_LAST_DIM[_BACKWARD], _) requires rank ≥ 1".to_string(),
4982                )
4983                .bt());
4984            }
4985            let last_dim = *dims.last().unwrap();
4986            let outer_count: usize = dims[..dims.len() - 1].iter().product();
4987            OpParams::NormLastDim {
4988                outer_count,
4989                last_dim,
4990                eps,
4991            }
4992        }
4993        // ReduceMaxToBackward: shape pair via the new
4994        // OpParams::ReduceMaxToBackward variant. x's shape is
4995        // `input_shape`; upstream's shape is `output_shape`.
4996        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::REDUCE_MAX_TO_BACKWARD => {
4997            if node.inputs.len() != 2 {
4998                return Err(Error::Msg(format!(
4999                    "Op::Fused(REDUCE_MAX_TO_BACKWARD) expects 2 inputs, got {}",
5000                    node.inputs.len(),
5001                ))
5002                .bt());
5003            }
5004            let x_layout = input_layout(node.inputs[0]);
5005            let up_layout = input_layout(node.inputs[1]);
5006            let input_shape: Vec<usize> = x_layout.shape().dims().to_vec();
5007            let output_shape: Vec<usize> = up_layout.shape().dims().to_vec();
5008            OpParams::ReduceMaxToBackward {
5009                input_shape,
5010                output_shape,
5011            }
5012        }
5013        Op::Concat { dim } => {
5014            // Output's shape: [..., total_dim, ...]. Compute outer
5015            // and inner counts from output_shape[..dim] and
5016            // [dim+1..]; per-input dim sizes from each input's
5017            // layout shape at index `dim`.
5018            if node.inputs.is_empty() {
5019                return Err(Error::Msg("Op::Concat requires at least 1 input".to_string()).bt());
5020            }
5021            let out_dims = node.shape.dims();
5022            if *dim >= out_dims.len() {
5023                return Err(Error::Msg(format!(
5024                    "Op::Concat: dim {dim} out of range for output rank {}",
5025                    out_dims.len(),
5026                ))
5027                .bt());
5028            }
5029            let outer_count: usize = out_dims[..*dim].iter().product();
5030            let inner_count: usize = out_dims[*dim + 1..].iter().product();
5031            let mut input_dim_sizes: Vec<usize> = Vec::with_capacity(node.inputs.len());
5032            for in_id in &node.inputs {
5033                let il = input_layout(*in_id);
5034                let il_dims = il.shape().dims();
5035                if *dim >= il_dims.len() {
5036                    return Err(Error::Msg(format!(
5037                        "Op::Concat: input {in_id:?} has rank {} but concat dim is {dim}",
5038                        il_dims.len(),
5039                    ))
5040                    .bt());
5041                }
5042                input_dim_sizes.push(il_dims[*dim]);
5043            }
5044            OpParams::Concat {
5045                outer_count,
5046                input_dim_sizes,
5047                inner_count,
5048                axis: *dim,
5049            }
5050        }
5051        Op::AddScalar(c) => OpParams::Affine { mul: 1.0, add: *c },
5052        Op::MulScalar(c) => OpParams::Affine { mul: *c, add: 0.0 },
5053        Op::Clamp { min, max } => OpParams::Clamp {
5054            min: *min,
5055            max: *max,
5056        },
5057        Op::PowI(exp) => OpParams::PowI { exp: *exp },
5058        Op::ClampInplace { min, max } => OpParams::Clamp {
5059            min: *min,
5060            max: *max,
5061        },
5062        Op::PowIInplace(exp) => OpParams::PowI { exp: *exp },
5063        // PowI backward — `(x, upstream) → grad_x = exp · x^(exp-1) ·
5064        // upstream`. Pulls the same `exp` as the forward through
5065        // FusedOpParams::PowIBackward (autograd carries it across).
5066        Op::Fused(_, fuel_graph::registry::FusedOpParams::PowIBackward { exp }) => {
5067            OpParams::PowI { exp: *exp }
5068        }
5069        // In-place affine (Phase 3 of the in-place ops infrastructure):
5070        // reuse the existing `OpParams::Affine` payload — the kernel
5071        // side doesn't care whether the destination is fresh or aliases
5072        // the input; the structural decision lives in the executor's
5073        // dedicated `WorkItemKind::InplaceKernel` arm.
5074        Op::Fused(_, fuel_graph::registry::FusedOpParams::InplaceAffine { mul, add }) => {
5075            OpParams::Affine {
5076                mul: *mul,
5077                add: *add,
5078            }
5079        }
5080        // Phase 7.6 step 5: legacy `Op::Conv2D` arm retired with the
5081        // variant; Conv2D routes through `Op::Fused(CONV2D, _)`.
5082        Op::Fused(
5083            _,
5084            fuel_graph::registry::FusedOpParams::Conv2D {
5085                stride,
5086                padding,
5087                groups,
5088            },
5089        ) => {
5090            // Inputs[0] = x [N, Cin, Hin, Win]; inputs[1] = weight
5091            // [Cout, Cin/groups, Kh, Kw]; inputs[2] (optional) = bias [Cout].
5092            // Output (this Node's shape) = [N, Cout, Hout, Wout].
5093            if node.inputs.len() != 2 && node.inputs.len() != 3 {
5094                return Err(Error::Msg(format!(
5095                    "Op::Conv2D expects 2 or 3 inputs, got {}",
5096                    node.inputs.len(),
5097                ))
5098                .bt());
5099            }
5100            let x_layout = input_layout(node.inputs[0]);
5101            let w_layout = input_layout(node.inputs[1]);
5102            let x_dims = x_layout.shape().dims();
5103            let w_dims = w_layout.shape().dims();
5104            if x_dims.len() != 4 || w_dims.len() != 4 {
5105                return Err(Error::Msg(format!(
5106                    "Op::Conv2D requires rank-4 x and weight; got x={x_dims:?} w={w_dims:?}",
5107                ))
5108                .bt());
5109            }
5110            let out_dims = node.shape.dims();
5111            if out_dims.len() != 4 {
5112                return Err(Error::Msg(format!(
5113                    "Op::Conv2D output must be rank 4, got {out_dims:?}",
5114                ))
5115                .bt());
5116            }
5117            let x_shape = [x_dims[0], x_dims[1], x_dims[2], x_dims[3]];
5118            let w_shape = [w_dims[0], w_dims[1], w_dims[2], w_dims[3]];
5119            let out_shape = [out_dims[0], out_dims[1], out_dims[2], out_dims[3]];
5120            OpParams::Conv2D {
5121                x_shape,
5122                w_shape,
5123                out_shape,
5124                stride: *stride,
5125                padding: *padding,
5126                dilation: (1, 1),
5127                groups: *groups,
5128            }
5129        }
5130        // Phase 7.6 step 5 (final): legacy `Op::PagedAttn` arm dropped.
5131        Op::Fused(
5132            _,
5133            fuel_graph::registry::FusedOpParams::PagedAttn {
5134                softmax_scale,
5135                block_size,
5136                softcap,
5137            },
5138        ) => {
5139            // Inputs[0]=q [B,Hq,Sq,D], inputs[1]=k_cache [num_blocks,
5140            // block_size, Hkv, D], inputs[2]=v_cache same shape,
5141            // inputs[3]=block_table [B, max_blocks_per_seq] U32,
5142            // inputs[4]=context_lens [B] U32, inputs[5]=alibi [Hq] (optional).
5143            if node.inputs.len() != 5 && node.inputs.len() != 6 {
5144                return Err(Error::Msg(format!(
5145                    "Op::PagedAttn expects 5 or 6 inputs, got {}",
5146                    node.inputs.len(),
5147                ))
5148                .bt());
5149            }
5150            let q_layout = input_layout(node.inputs[0]);
5151            let kc_layout = input_layout(node.inputs[1]);
5152            let vc_layout = input_layout(node.inputs[2]);
5153            let bt_layout = input_layout(node.inputs[3]);
5154            let q_dims = q_layout.shape().dims();
5155            let kc_dims = kc_layout.shape().dims();
5156            let vc_dims = vc_layout.shape().dims();
5157            let bt_dims = bt_layout.shape().dims();
5158            if q_dims.len() != 4 || kc_dims.len() != 4 || vc_dims.len() != 4 {
5159                return Err(Error::Msg(format!(
5160                    "Op::PagedAttn requires rank-4 q/k_cache/v_cache; \
5161                     got q={q_dims:?} k_cache={kc_dims:?} v_cache={vc_dims:?}",
5162                ))
5163                .bt());
5164            }
5165            if kc_dims != vc_dims {
5166                return Err(Error::Msg(format!(
5167                    "Op::PagedAttn: k_cache {kc_dims:?} and v_cache {vc_dims:?} must match",
5168                ))
5169                .bt());
5170            }
5171            if bt_dims.len() != 2 {
5172                return Err(Error::Msg(format!(
5173                    "Op::PagedAttn: block_table must be rank 2 [B, max_blocks_per_seq], got {bt_dims:?}",
5174                ))
5175                .bt());
5176            }
5177            if kc_dims[1] != *block_size {
5178                return Err(Error::Msg(format!(
5179                    "Op::PagedAttn: k_cache block_size dim ({}) must equal Op's block_size ({})",
5180                    kc_dims[1], block_size,
5181                ))
5182                .bt());
5183            }
5184            OpParams::PagedAttn {
5185                b: q_dims[0],
5186                hq: q_dims[1],
5187                hkv: kc_dims[2],
5188                sq: q_dims[2],
5189                d: q_dims[3],
5190                block_size: *block_size,
5191                max_blocks_per_seq: bt_dims[1],
5192                num_blocks: kc_dims[0],
5193                softmax_scale: *softmax_scale,
5194                softcap: *softcap,
5195            }
5196        }
5197        // Phase 7.6 step 5 (final): legacy `Op::FlashAttn` arm dropped.
5198        Op::Fused(
5199            _,
5200            fuel_graph::registry::FusedOpParams::FlashAttn {
5201                softmax_scale,
5202                causal,
5203                window_size_left,
5204                window_size_right,
5205                softcap,
5206                k_len,
5207            },
5208        ) => {
5209            // Inputs[0]=q [B,Hq,Sq,D], inputs[1]=k [B,Hkv,Sk,D],
5210            // inputs[2]=v [B,Hkv,Sk,D], inputs[3]=alibi_slopes [Hq] (optional).
5211            // `sk` is the PHYSICAL K extent (capacity, for strides/bytes);
5212            // `k_len` (resolved below) is the LOGICAL attended length.
5213            if node.inputs.len() != 3 && node.inputs.len() != 4 {
5214                return Err(Error::Msg(format!(
5215                    "Op::FlashAttn expects 3 or 4 inputs, got {}",
5216                    node.inputs.len(),
5217                ))
5218                .bt());
5219            }
5220            let q_layout = input_layout(node.inputs[0]);
5221            let k_layout = input_layout(node.inputs[1]);
5222            let v_layout = input_layout(node.inputs[2]);
5223            let q_dims = q_layout.shape().dims();
5224            let k_dims = k_layout.shape().dims();
5225            let v_dims = v_layout.shape().dims();
5226            if q_dims.len() != 4 || k_dims.len() != 4 || v_dims.len() != 4 {
5227                return Err(Error::Msg(format!(
5228                    "Op::FlashAttn requires rank-4 q/k/v; got q={q_dims:?} k={k_dims:?} v={v_dims:?}",
5229                ))
5230                .bt());
5231            }
5232            if k_dims != v_dims {
5233                return Err(Error::Msg(format!(
5234                    "Op::FlashAttn: k {k_dims:?} and v {v_dims:?} must share shape",
5235                ))
5236                .bt());
5237            }
5238            if q_dims[0] != k_dims[0] || q_dims[3] != k_dims[3] {
5239                return Err(Error::Msg(format!(
5240                    "Op::FlashAttn: q {q_dims:?} and k {k_dims:?} must share B and D",
5241                ))
5242                .bt());
5243            }
5244            let sk = k_dims[2];
5245            // Resolve the logical attended length. `None` ⇒ attend the
5246            // full K extent (today's behavior). `Some(dyn)` ⇒ resolve
5247            // against the per-pass SymEnv; the resolved length must fit
5248            // the capacity and cover Sq (a valid causal prefix).
5249            let attended_k_len = match k_len {
5250                None => sk,
5251                Some(dyn_k) => {
5252                    let kl = dyn_k.resolve(sym_env).ok_or_else(|| {
5253                        Error::Msg(format!(
5254                            "Op::FlashAttn: dynamic k_len {dyn_k:?} is unbound in the SymEnv at realize",
5255                        ))
5256                        .bt()
5257                    })?;
5258                    if kl > sk {
5259                        return Err(Error::Msg(format!(
5260                            "Op::FlashAttn: resolved k_len ({kl}) exceeds K capacity ({sk})",
5261                        ))
5262                        .bt());
5263                    }
5264                    if kl < q_dims[2] {
5265                        return Err(Error::Msg(format!(
5266                            "Op::FlashAttn: resolved k_len ({kl}) < Sq ({}) — not a valid causal prefix",
5267                            q_dims[2],
5268                        ))
5269                        .bt());
5270                    }
5271                    kl
5272                }
5273            };
5274            OpParams::FlashAttn {
5275                b: q_dims[0],
5276                hq: q_dims[1],
5277                hkv: k_dims[1],
5278                sq: q_dims[2],
5279                sk,
5280                d: q_dims[3],
5281                k_len: attended_k_len,
5282                softmax_scale: *softmax_scale,
5283                causal: *causal,
5284                window_size_left: *window_size_left,
5285                window_size_right: *window_size_right,
5286                softcap: *softcap,
5287            }
5288        }
5289        Op::ReduceSumTo(target_shape) => {
5290            if node.inputs.len() != 1 {
5291                return Err(Error::Msg(format!(
5292                    "Op::ReduceSumTo expects 1 input, got {}",
5293                    node.inputs.len(),
5294                ))
5295                .bt());
5296            }
5297            let in_layout = input_layout(node.inputs[0]);
5298            let input_shape: Vec<usize> = in_layout.shape().dims().to_vec();
5299            let output_shape: Vec<usize> = target_shape.dims().to_vec();
5300            OpParams::ReduceSumTo {
5301                input_shape,
5302                output_shape,
5303            }
5304        }
5305        Op::ReduceMaxTo(target_shape) => {
5306            if node.inputs.len() != 1 {
5307                return Err(Error::Msg(format!(
5308                    "Op::ReduceMaxTo expects 1 input, got {}",
5309                    node.inputs.len(),
5310                ))
5311                .bt());
5312            }
5313            let in_layout = input_layout(node.inputs[0]);
5314            let input_shape: Vec<usize> = in_layout.shape().dims().to_vec();
5315            let output_shape: Vec<usize> = target_shape.dims().to_vec();
5316            OpParams::ReduceMaxTo {
5317                input_shape,
5318                output_shape,
5319            }
5320        }
5321        // Phase 7.6 step 5 (final): legacy `Op::ConvTranspose2D` arm dropped.
5322        Op::Fused(
5323            _,
5324            fuel_graph::registry::FusedOpParams::ConvTranspose2D {
5325                stride,
5326                padding,
5327                output_padding,
5328                dilation,
5329                groups,
5330            },
5331        ) => {
5332            // Inputs[0] = x [N, Cin, Hin, Win]; inputs[1] = weight
5333            // [Cin, Cout/groups, Kh, Kw]; inputs[2] (optional) = bias [Cout].
5334            // Output (this Node's shape) = [N, Cout, Hout, Wout].
5335            if node.inputs.len() != 2 && node.inputs.len() != 3 {
5336                return Err(Error::Msg(format!(
5337                    "Op::ConvTranspose2D expects 2 or 3 inputs, got {}",
5338                    node.inputs.len(),
5339                ))
5340                .bt());
5341            }
5342            let x_layout = input_layout(node.inputs[0]);
5343            let w_layout = input_layout(node.inputs[1]);
5344            let x_dims = x_layout.shape().dims();
5345            let w_dims = w_layout.shape().dims();
5346            if x_dims.len() != 4 || w_dims.len() != 4 {
5347                return Err(Error::Msg(format!(
5348                    "Op::ConvTranspose2D requires rank-4 x and weight; got x={x_dims:?} w={w_dims:?}",
5349                ))
5350                .bt());
5351            }
5352            let out_dims = node.shape.dims();
5353            if out_dims.len() != 4 {
5354                return Err(Error::Msg(format!(
5355                    "Op::ConvTranspose2D output must be rank 4, got {out_dims:?}",
5356                ))
5357                .bt());
5358            }
5359            let x_shape = [x_dims[0], x_dims[1], x_dims[2], x_dims[3]];
5360            let w_shape = [w_dims[0], w_dims[1], w_dims[2], w_dims[3]];
5361            let out_shape = [out_dims[0], out_dims[1], out_dims[2], out_dims[3]];
5362            OpParams::ConvTranspose2D {
5363                x_shape,
5364                w_shape,
5365                out_shape,
5366                stride: *stride,
5367                padding: *padding,
5368                output_padding: *output_padding,
5369                dilation: *dilation,
5370                groups: *groups,
5371            }
5372        }
5373        Op::WriteSlice { ranges, dyn_offset } => {
5374            // inputs[0] = destination (its shape == this node's shape
5375            // since WriteSlice's output adopts the destination's
5376            // Layout). inputs[1] = source slab; its shape is implied
5377            // by `ranges`. The kernel needs the destination shape to
5378            // compute strides for the slab walk.
5379            if node.inputs.len() != 2 {
5380                return Err(Error::Msg(format!(
5381                    "Op::WriteSlice expects 2 inputs (destination, source), got {}",
5382                    node.inputs.len(),
5383                ))
5384                .bt());
5385            }
5386            let dest_dims = node.shape.dims().to_vec();
5387            if ranges.len() != dest_dims.len() {
5388                return Err(Error::Msg(format!(
5389                    "Op::WriteSlice: ranges.len() ({}) must equal destination rank ({})",
5390                    ranges.len(),
5391                    dest_dims.len(),
5392                ))
5393                .bt());
5394            }
5395            // Phase D symbolic extents: when present, resolve the runtime
5396            // start offset against the per-pass SymEnv, overriding
5397            // `ranges[axis].0`. The slab WIDTH on that axis stays
5398            // `ranges[axis].1 - ranges[axis].0`, so the effective range
5399            // becomes `(base, base + width)`. `None` ⇒ fully static, and
5400            // the SymEnv is never consulted (empty-env realize unchanged).
5401            //
5402            // DUAL-PATH (increment 2b — data-determined dynamic shapes):
5403            //  - The offset resolves in the compile-time `sym_env` (static,
5404            //    or an INPUT-determined `cached_len`): bake it into `ranges`
5405            //    now, exactly as before.
5406            //  - It is UNBOUND at compile AND a producer in this graph binds
5407            //    it (`Op::NonZeroIndices`'s count, etc.): it is
5408            //    DATA-DETERMINED — leave `ranges[axis]` as the static
5409            //    placeholder and DEFER, carrying the `DynScalar` in
5410            //    `deferred_dyn_offset`. The `WorkItemKind::WriteSlice`
5411            //    executor arm resolves it from `produced_syms` (after the
5412            //    producer runs) and bounds-checks the resolved range there.
5413            //  - It is unbound AND no producer binds it: a genuine caller
5414            //    error → surface it here (preserves the unbound-error path).
5415            let mut ranges = ranges.clone();
5416            let mut deferred_dyn_offset: Option<(usize, fuel_ir::DynScalar)> = None;
5417            if let Some((axis, off)) = dyn_offset {
5418                if *axis >= ranges.len() {
5419                    return Err(Error::Msg(format!(
5420                        "Op::WriteSlice: dyn_offset axis ({axis}) out of bounds for rank {}",
5421                        ranges.len(),
5422                    ))
5423                    .bt());
5424                }
5425                match off.resolve(sym_env) {
5426                    Some(base) => {
5427                        let (start, end) = ranges[*axis];
5428                        let width = end - start;
5429                        ranges[*axis] = (base, base + width);
5430                    }
5431                    None => {
5432                        let is_data_determined = matches!(off, fuel_ir::DynScalar::Sym(s)
5433                            if graph.binds_data_determined_sym(*s));
5434                        if is_data_determined {
5435                            deferred_dyn_offset = Some((*axis, *off));
5436                        } else {
5437                            return Err(Error::Msg(format!(
5438                                "Op::WriteSlice: dynamic offset {off:?} on axis {axis} is \
5439                                 unbound in the SymEnv at realize (and no producer in the \
5440                                 graph binds it, so it is not data-determined)",
5441                            ))
5442                            .bt());
5443                        }
5444                    }
5445                }
5446            }
5447            for (i, &(start, end)) in ranges.iter().enumerate() {
5448                // The deferred axis still holds its static placeholder; the
5449                // executor bounds-checks the resolved range after producing
5450                // the count. Every other axis is fully known now.
5451                if deferred_dyn_offset.is_some_and(|(a, _)| a == i) {
5452                    continue;
5453                }
5454                if end < start || end > dest_dims[i] {
5455                    return Err(Error::Msg(format!(
5456                        "Op::WriteSlice: ranges[{i}] = ({start}, {end}) invalid \
5457                         for destination dim {i} = {}",
5458                        dest_dims[i],
5459                    ))
5460                    .bt());
5461                }
5462            }
5463            OpParams::WriteSlice {
5464                dest_shape: dest_dims,
5465                ranges,
5466                deferred_dyn_offset,
5467            }
5468        }
5469        Op::WriteSliceRotating {
5470            axis,
5471            modulus,
5472            ranges,
5473        } => {
5474            // inputs[0] = destination, inputs[1] = source slab,
5475            // inputs[2] = dynamic position scalar (U32). The builder
5476            // already validated rank / dtype / shape parity; the
5477            // exec-time check below mirrors WriteSlice for the
5478            // structural invariants the executor depends on.
5479            if node.inputs.len() != 3 {
5480                return Err(Error::Msg(format!(
5481                    "Op::WriteSliceRotating expects 3 inputs (destination, source, position), got {}",
5482                    node.inputs.len(),
5483                ))
5484                .bt());
5485            }
5486            let dest_dims = node.shape.dims().to_vec();
5487            if ranges.len() != dest_dims.len() {
5488                return Err(Error::Msg(format!(
5489                    "Op::WriteSliceRotating: ranges.len() ({}) must equal destination rank ({})",
5490                    ranges.len(),
5491                    dest_dims.len(),
5492                ))
5493                .bt());
5494            }
5495            if *axis >= dest_dims.len() {
5496                return Err(Error::Msg(format!(
5497                    "Op::WriteSliceRotating: axis {axis} out of bounds for rank {}",
5498                    dest_dims.len(),
5499                ))
5500                .bt());
5501            }
5502            if *modulus == 0 || *modulus > dest_dims[*axis] {
5503                return Err(Error::Msg(format!(
5504                    "Op::WriteSliceRotating: modulus {modulus} invalid for dest_shape[{axis}] = {}",
5505                    dest_dims[*axis],
5506                ))
5507                .bt());
5508            }
5509            OpParams::WriteSliceRotating {
5510                dest_shape: dest_dims,
5511                axis: *axis,
5512                modulus: *modulus,
5513                ranges: ranges.clone(),
5514            }
5515        }
5516        Op::WriteSliceDoff { axis, ranges } => {
5517            // inputs[0] = destination, inputs[1] = source slab,
5518            // inputs[2] = device-resident I64 offset scalar. The
5519            // builder validated rank / dtype / static-width parity; the
5520            // exec-time check below mirrors WriteSliceRotating minus the
5521            // modulus (no wrap). Bounds on the *dynamic* offset are the
5522            // caller's contract (device-only, un-checkable here).
5523            if node.inputs.len() != 3 {
5524                return Err(Error::Msg(format!(
5525                    "Op::WriteSliceDoff expects 3 inputs (destination, source, offset), got {}",
5526                    node.inputs.len(),
5527                ))
5528                .bt());
5529            }
5530            let dest_dims = node.shape.dims().to_vec();
5531            if ranges.len() != dest_dims.len() {
5532                return Err(Error::Msg(format!(
5533                    "Op::WriteSliceDoff: ranges.len() ({}) must equal destination rank ({})",
5534                    ranges.len(),
5535                    dest_dims.len(),
5536                ))
5537                .bt());
5538            }
5539            if *axis >= dest_dims.len() {
5540                return Err(Error::Msg(format!(
5541                    "Op::WriteSliceDoff: axis {axis} out of bounds for rank {}",
5542                    dest_dims.len(),
5543                ))
5544                .bt());
5545            }
5546            OpParams::WriteSliceDoff {
5547                dest_shape: dest_dims,
5548                axis: *axis,
5549                ranges: ranges.clone(),
5550            }
5551        }
5552        _ => OpParams::None,
5553    })
5554}
5555
5556/// Execute one work item. Three branches by `WorkItemKind`:
5557///
5558/// - `ConstAdopt` — verify cache has an entry pre-seeded by the
5559///   caller; record the layout from the WorkItem.
5560/// - `ViewOf { input }` — clone the input's Storage Arc into the
5561///   output slot (bytes are shared); record the strided layout
5562///   from the WorkItem.
5563/// - `Kernel` — gather input Arcs, allocate the output, run the
5564///   compiled kernel, store the result; record the contiguous
5565///   layout from the WorkItem.
5566///
5567/// Best-effort: prefix a realize-time node error with the failing node's graph
5568/// location — `Graph::describe_node` renders `Node#N (op, out shape, dtype,
5569/// inputs=[...])`, enough to grep-locate the offending op in a large graph. The
5570/// legacy per-node executors (`fuel-graph-executor`, the retired
5571/// `fuel-reference-backend`) wrapped panics this way; the PipelinedExecutor
5572/// surfaces the raw kernel error, so a dtype/shape/OOB failure deep in a model
5573/// arrived with no graph coordinate. On a graph read-lock failure the original
5574/// error passes through unchanged — the location is a navigation aid, never
5575/// worth masking the real error with a lock issue. Zero happy-path cost: only
5576/// the error branch touches the graph.
5577fn with_node_location(graph: &Arc<RwLock<Graph>>, node_id: NodeId, err: Error) -> Error {
5578    match graph.read() {
5579        Ok(g) => err.context(g.describe_node(node_id)),
5580        Err(_) => err,
5581    }
5582}
5583
5584/// Execute one [`WorkItem`] against the cache, returning the node's
5585/// [`CompletionHandle`].
5586///
5587/// Step E A4b-1: the producing arms (Kernel / WriteSlice / WriteSliceRotating /
5588/// in-place / cross-device Copy alloc) return the handle from `execute_compiled`
5589/// *without* waiting it inline — the realize loop stores it in its per-node
5590/// handle map and drains at realize-end. Non-producing arms (const adopt, view,
5591/// slot projection, release marker, contiguize) are pure Arc-clones / host
5592/// allocs whose work is already complete → [`CompletionHandle::Ready`].
5593/// Read a data-determined runtime count from bundle slot 1 of a
5594/// just-realized producer and bind it into the per-pass `SymEnv` under
5595/// `count_sym` — the data-dependent dynamic-shapes seam (increment 2a).
5596/// The producer's bundle is `[indices [capacity] U32 ; count [1] U32]`;
5597/// slot 1's single U32 starts at byte `capacity * 4` (after the
5598/// `capacity`-element U32 primary slot). CPU only for now — device
5599/// backends need a D2H after the completion handle is waited (a documented
5600/// follow-up; the whole data-dependent path is CPU-first). Called AFTER
5601/// `execute_compiled`, whose CPU path returns a `Ready` handle, so the
5602/// bytes are already valid.
5603fn bind_data_determined_count(
5604    arc: &Arc<RwLock<Storage>>,
5605    capacity: usize,
5606    count_sym: fuel_ir::SymId,
5607    produced_syms: &mut SymEnv,
5608) -> Result<()> {
5609    let guard = arc
5610        .read()
5611        .map_err(|_| poisoned("NonZeroIndices output storage"))?;
5612    let count_byte_off = capacity * std::mem::size_of::<u32>();
5613    let end = count_byte_off + std::mem::size_of::<u32>();
5614    // The non-CPU `BackendStorage` variants are cfg-gated; with GPU
5615    // features off, `Cpu` is the only variant and the fallback arm is
5616    // unreachable (a documented CPU-first limitation, not dead logic).
5617    #[allow(unreachable_patterns)]
5618    let count = match &guard.inner {
5619        fuel_memory::BackendStorage::Cpu(cpu_bytes) => {
5620            let bytes = cpu_bytes.bytes();
5621            if end > bytes.len() {
5622                return Err(Error::Msg(format!(
5623                    "NonZeroIndices: count slot byte range [{count_byte_off}..{end}) \
5624                     exceeds bundle byte length {}",
5625                    bytes.len(),
5626                ))
5627                .bt());
5628            }
5629            u32::from_le_bytes(
5630                bytes[count_byte_off..end]
5631                    .try_into()
5632                    .expect("4 bytes → u32"),
5633            )
5634        }
5635        other => {
5636            return Err(Error::Msg(format!(
5637                "NonZeroIndices: data-determined count read is CPU-only today; got \
5638                 BackendStorage::{:?} (device backends need a D2H after the completion \
5639                 handle is waited — a documented follow-up)",
5640                other.backend_id(),
5641            ))
5642            .bt());
5643        }
5644    };
5645    produced_syms.bind(count_sym, count as usize)?;
5646    Ok(())
5647}
5648
5649/// Increment 2b — the consumer half of data-dependent dynamic shapes. When
5650/// a `WriteSlice`'s offset is DATA-DETERMINED (its `SymId` is produced
5651/// mid-pass, so `op_to_op_params` deferred it into
5652/// `OpParams::WriteSlice::deferred_dyn_offset` instead of baking it at
5653/// compile), resolve it HERE from `produced_syms` — populated by the
5654/// producer's execute step (single-threaded topological order guarantees
5655/// the producer already ran). Returns a patched clone of the `CompiledNode`
5656/// with the resolved `ranges` (and `deferred_dyn_offset` cleared) for the
5657/// kernel; `None` when there is nothing to defer (the common path — no
5658/// clone). Bounds-checks the resolved range (deferred past compile).
5659fn resolve_deferred_write_slice(
5660    compiled: &CompiledNode,
5661    produced_syms: &SymEnv,
5662    node_id: NodeId,
5663) -> Result<Option<CompiledNode>> {
5664    let OpParams::WriteSlice {
5665        dest_shape,
5666        ranges,
5667        deferred_dyn_offset,
5668    } = &compiled.op_params
5669    else {
5670        return Ok(None);
5671    };
5672    let Some((axis, off)) = deferred_dyn_offset else {
5673        return Ok(None);
5674    };
5675    let base = off.resolve(produced_syms).ok_or_else(|| {
5676        Error::Msg(format!(
5677            "Op::WriteSlice {node_id:?}: data-determined offset {off:?} on axis {axis} is \
5678             unbound in produced_syms at execute (its producer did not run / bind it)",
5679        ))
5680        .bt()
5681    })?;
5682    let mut ranges = ranges.clone();
5683    let (start, end) = ranges[*axis];
5684    let width = end - start;
5685    let resolved = (base, base + width);
5686    if resolved.1 > dest_shape[*axis] {
5687        return Err(Error::Msg(format!(
5688            "Op::WriteSlice {node_id:?}: resolved data-determined range {resolved:?} on axis \
5689             {axis} exceeds destination dim = {}",
5690            dest_shape[*axis],
5691        ))
5692        .bt());
5693    }
5694    ranges[*axis] = resolved;
5695    let mut patched = compiled.clone();
5696    patched.op_params = OpParams::WriteSlice {
5697        dest_shape: dest_shape.clone(),
5698        ranges,
5699        deferred_dyn_offset: None,
5700    };
5701    Ok(Some(patched))
5702}
5703
5704/// Dynamic-M matmul: when a matmul's row count is DATA-DETERMINED
5705/// (`MatmulM::Deferred`, deferred by `op_to_op_params` because a producer
5706/// binds its `SymId` mid-pass), resolve it HERE from `produced_syms` and
5707/// run the kernel against a patched clone whose `m_compute` is
5708/// `MatmulM::Rows(count)`. Mirrors `resolve_deferred_write_slice`. `None`
5709/// when nothing is deferred (the common path — no clone). The kernel then
5710/// computes exactly `count` rows of the `m`-row capacity buffer.
5711fn resolve_deferred_matmul(
5712    compiled: &CompiledNode,
5713    produced_syms: &SymEnv,
5714    node_id: NodeId,
5715) -> Result<Option<CompiledNode>> {
5716    let OpParams::Matmul {
5717        lhs_batch_dims,
5718        rhs_batch_dims,
5719        m,
5720        n,
5721        k,
5722        m_compute,
5723    } = &compiled.op_params
5724    else {
5725        return Ok(None);
5726    };
5727    let MatmulM::Deferred(dyn_m) = m_compute else {
5728        return Ok(None);
5729    };
5730    let rows = dyn_m.resolve(produced_syms).ok_or_else(|| {
5731        Error::Msg(format!(
5732            "Op::MatMul {node_id:?}: data-determined row count {dyn_m:?} is unbound in \
5733             produced_syms at execute (its producer did not run / bind it)",
5734        ))
5735        .bt()
5736    })?;
5737    if rows > *m {
5738        return Err(Error::Msg(format!(
5739            "Op::MatMul {node_id:?}: resolved row count {rows} exceeds capacity {m}",
5740        ))
5741        .bt());
5742    }
5743    let mut patched = compiled.clone();
5744    patched.op_params = OpParams::Matmul {
5745        lhs_batch_dims: lhs_batch_dims.clone(),
5746        rhs_batch_dims: rhs_batch_dims.clone(),
5747        m: *m,
5748        n: *n,
5749        k: *k,
5750        m_compute: MatmulM::Rows(rows),
5751    };
5752    Ok(Some(patched))
5753}
5754
5755fn execute_work_item(
5756    item: &WorkItem,
5757    cache: &mut StorageCache,
5758    #[cfg_attr(
5759        not(any(feature = "cuda", feature = "vulkan")),
5760        allow(unused_variables)
5761    )]
5762    devices: &mut DeviceRegistry,
5763    layout_cache: &mut HashMap<NodeId, Layout>,
5764    produced_syms: &mut SymEnv,
5765    // Step E A4b open question #4 — "event only where waited": whether
5766    // THIS item's node id is in the realize's `WaitSet` (`will_be_waited`
5767    // in `pipelined.rs`, computed once per item by the caller). Forwarded
5768    // to every `execute_compiled_with_wait_hint` call below so a CUDA
5769    // kernel with no mid-walk reader skips its `Event` entirely.
5770    will_be_waited: bool,
5771    // CapturedRun executor build-out: persistent-output mode. `None` on
5772    // every existing realize path ⇒ byte-identical (fresh alloc, nothing
5773    // recorded). `Some(Record)` records each Kernel output's fixed Arc;
5774    // `Some(Reuse)` reuses the recorded buffer (no alloc — capture-safe)
5775    // and the write-into kernel path writes into it in place. Only the
5776    // `Kernel` arm consults it; every other arm ignores it.
5777    mut persistent: Option<&mut PersistentOutputs>,
5778) -> Result<CompletionHandle> {
5779    match &item.kind {
5780        WorkItemKind::ConstAdopt => {
5781            if !cache.contains_key(&item.node_id) {
5782                return Err(Error::Msg(format!(
5783                    "PipelinedExecutor: Const node {:?} not in input cache",
5784                    item.node_id
5785                ))
5786                .bt());
5787            }
5788            // Layout for input cache entries was seeded at realize
5789            // start; refresh from the WorkItem in case the side-table
5790            // was set after seeding.
5791            layout_cache.insert(item.node_id, item.output_layout.clone());
5792            Ok(CompletionHandle::Ready)
5793        }
5794        WorkItemKind::ViewOf { input } => {
5795            let input_arc = cache.get(input).cloned().ok_or_else(|| {
5796                Error::Msg(format!(
5797                    "PipelinedExecutor: view-op input {:?} of {:?} not realized",
5798                    input, item.node_id,
5799                ))
5800                .bt()
5801            })?;
5802            cache.insert(item.node_id, input_arc);
5803            layout_cache.insert(item.node_id, item.output_layout.clone());
5804            Ok(CompletionHandle::Ready)
5805        }
5806        WorkItemKind::SlotView { producer } => {
5807            // Op::View — multi-output projection. Same realization
5808            // shape as ViewOf: clone the producer's Storage Arc into
5809            // the View's cache slot. The WorkItem's output_layout was
5810            // computed at graph-build time by `Tensor::view`, with
5811            // the slot's byte_offset baked into start_offset (in
5812            // slot-dtype-element units). Downstream kernels reading
5813            // the producer's bytes as the slot's dtype starting at
5814            // that offset see the slot's typed window.
5815            let producer_arc = cache.get(producer).cloned().ok_or_else(|| {
5816                Error::Msg(format!(
5817                    "PipelinedExecutor: Op::View producer {:?} of {:?} not realized",
5818                    producer, item.node_id,
5819                ))
5820                .bt()
5821            })?;
5822            cache.insert(item.node_id, producer_arc);
5823            layout_cache.insert(item.node_id, item.output_layout.clone());
5824            Ok(CompletionHandle::Ready)
5825        }
5826        WorkItemKind::SlotOwn { producer, slot } => {
5827            // Op::ViewOwned — allocate a fresh Storage of the slot's
5828            // (shape, dtype) on the producer's device and copy the
5829            // slot's bytes in. Per-backend fast paths:
5830            //   - CPU:    direct &[u8]→&mut[u8] memcpy via CpuStorageBytes
5831            //   - CUDA:   D2D via CudaStorageBytes::slot_copy_to_new
5832            //             (cuMemcpyDtoDAsync with offset src pointer)
5833            //   - Vulkan: vkCmdCopyBuffer via
5834            //             VulkanBackend::slot_copy_to_new_handle
5835            //             (srcOffset/dstOffset/size)
5836            // For backends without a copy-with-offset hook we fall
5837            // back to a host round-trip (`to_host_buffer_dyn` →
5838            // slice → `storage_from_host_buffer_owned_dyn`), which
5839            // works but is wasteful.
5840            let producer_arc = cache.get(producer).cloned().ok_or_else(|| {
5841                Error::Msg(format!(
5842                    "PipelinedExecutor: Op::ViewOwned producer {:?} of {:?} not realized",
5843                    producer, item.node_id,
5844                ))
5845                .bt()
5846            })?;
5847            let new_storage = {
5848                let guard = producer_arc
5849                    .read()
5850                    .map_err(|_| poisoned("ViewOwned producer storage"))?;
5851                let bundle = guard.bundle().ok_or_else(|| {
5852                    Error::Msg(format!(
5853                        "Op::ViewOwned: producer {:?} has no bundle side-table \
5854                         — the multi-output authoring contract requires \
5855                         Storage::with_bundle / new_bundled at allocation \
5856                         time. Node {:?} slot {} cannot resolve its source.",
5857                        producer, item.node_id, slot,
5858                    ))
5859                    .bt()
5860                })?;
5861                let sv = bundle.get(*slot as usize).cloned().ok_or_else(|| {
5862                    Error::Msg(format!(
5863                        "Op::ViewOwned: slot {} out of range for producer {:?} \
5864                         (bundle has {} slots)",
5865                        slot,
5866                        producer,
5867                        bundle.len(),
5868                    ))
5869                    .bt()
5870                })?;
5871                use fuel_memory::BackendStorage;
5872                match &guard.inner {
5873                    BackendStorage::Cpu(cpu_bytes) => {
5874                        let src_bytes = cpu_bytes.bytes();
5875                        let end = sv.byte_offset + sv.len_bytes();
5876                        if end > src_bytes.len() {
5877                            return Err(Error::Msg(format!(
5878                                "Op::ViewOwned: slot {} byte range [{}..{}) \
5879                                 exceeds producer's CPU byte length {}",
5880                                slot,
5881                                sv.byte_offset,
5882                                end,
5883                                src_bytes.len(),
5884                            ))
5885                            .bt());
5886                        }
5887                        let owned = fuel_cpu_backend::CpuStorageBytes::from_bytes(
5888                            &src_bytes[sv.byte_offset..end],
5889                        );
5890                        fuel_memory::Storage::new(BackendStorage::Cpu(owned), sv.dtype)
5891                    }
5892                    #[cfg(feature = "cuda")]
5893                    BackendStorage::Cuda(cuda_bytes) => {
5894                        let dst = cuda_bytes.slot_copy_to_new(sv.byte_offset, sv.len_bytes())?;
5895                        fuel_memory::Storage::new(BackendStorage::Cuda(dst), sv.dtype)
5896                    }
5897                    #[cfg(feature = "vulkan")]
5898                    BackendStorage::Vulkan(vk_bytes) => {
5899                        let backend = vk_bytes.backend().ok_or_else(|| {
5900                            Error::Msg(format!(
5901                                "Op::ViewOwned: producer {:?} is on Vulkan but \
5902                                 its storage has no VulkanBackend handle. \
5903                                 Storages flowing through the pipelined executor \
5904                                 must be constructed via alloc_bytes_handle / \
5905                                 upload_bytes_handle so the bundle's slot extraction \
5906                                 path can reach the backend.",
5907                                producer,
5908                            ))
5909                            .bt()
5910                        })?;
5911                        let dst = backend.slot_copy_to_new_handle(
5912                            vk_bytes,
5913                            sv.byte_offset,
5914                            sv.len_bytes(),
5915                        )?;
5916                        fuel_memory::Storage::new(BackendStorage::Vulkan(dst), sv.dtype)
5917                    }
5918                    #[allow(unreachable_patterns)]
5919                    _ => {
5920                        return Err(Error::Msg(format!(
5921                            "Op::ViewOwned: producer {:?} is on a backend \
5922                             without a slot-copy-with-offset hook \
5923                             (CPU + CUDA + Vulkan wired). Add a per-backend \
5924                             `slot_copy_to_new`-equivalent and extend the \
5925                             match arm.",
5926                            producer,
5927                        ))
5928                        .bt());
5929                    }
5930                }
5931            };
5932            cache.insert(item.node_id, Arc::new(RwLock::new(new_storage)));
5933            layout_cache.insert(item.node_id, item.output_layout.clone());
5934            // A4b-1: Op::ViewOwned's slot copy (CUDA D2D) is same-stream; its
5935            // completion is carried by the realize-end full-stream sync in
5936            // `to_cpu_bytes` (unchanged) — `Ready` here is behavior-preserving.
5937            Ok(CompletionHandle::Ready)
5938        }
5939        WorkItemKind::WriteSlice { dest, source } => {
5940            let compiled = item.compiled.as_ref().ok_or_else(|| {
5941                Error::Msg(format!(
5942                    "PipelinedExecutor: WriteSlice work item {:?} has no compiled node",
5943                    item.node_id,
5944                ))
5945                .bt()
5946            })?;
5947            // Increment 2b: if the offset is DATA-DETERMINED, resolve it from
5948            // the producer-bound `produced_syms` and run the kernel against
5949            // the patched (resolved-range) node. `None` on the common path.
5950            let patched_ws = resolve_deferred_write_slice(compiled, produced_syms, item.node_id)?;
5951            let compiled = patched_ws.as_ref().unwrap_or(compiled);
5952            let dest_arc = cache.get(dest).cloned().ok_or_else(|| {
5953                Error::Msg(format!(
5954                    "PipelinedExecutor: WriteSlice destination {:?} of {:?} not realized",
5955                    dest, item.node_id,
5956                ))
5957                .bt()
5958            })?;
5959            let source_arc = cache.get(source).cloned().ok_or_else(|| {
5960                Error::Msg(format!(
5961                    "PipelinedExecutor: WriteSlice source {:?} of {:?} not realized",
5962                    source, item.node_id,
5963                ))
5964                .bt()
5965            })?;
5966            let dest_layout = layout_cache.get(dest).cloned().ok_or_else(|| {
5967                Error::Msg(format!(
5968                    "PipelinedExecutor: WriteSlice destination {:?} of {:?} has no cached layout",
5969                    dest, item.node_id,
5970                ))
5971                .bt()
5972            })?;
5973            let source_layout = layout_cache.get(source).cloned().ok_or_else(|| {
5974                Error::Msg(format!(
5975                    "PipelinedExecutor: WriteSlice source {:?} of {:?} has no cached layout",
5976                    source, item.node_id,
5977                ))
5978                .bt()
5979            })?;
5980            // v1 contract: destination must be contiguous + zero
5981            // offset. Strided dests would force the kernel to walk
5982            // both source and dest strides; defer until KV cache
5983            // exposes a non-contig dest. Source CAN be non-contig —
5984            // we auto-contiguize it here so the kernel sees a flat
5985            // slab.
5986            if !dest_layout.is_contiguous() || dest_layout.start_offset() != 0 {
5987                return Err(Error::Msg(format!(
5988                    "Op::WriteSlice (Phase E.3.2 v1): destination {:?} must be \
5989                     contiguous + zero-offset; got Layout {:?}",
5990                    dest, dest_layout,
5991                ))
5992                .bt());
5993            }
5994            let source_arc_contig = {
5995                let s_dtype = source_arc
5996                    .read()
5997                    .map_err(|_| poisoned("WriteSlice source storage"))?
5998                    .dtype;
5999                let s_len_bytes = source_arc
6000                    .read()
6001                    .map_err(|_| poisoned("WriteSlice source storage"))?
6002                    .inner
6003                    .len_bytes();
6004                let layout_bytes = source_layout.shape().elem_count() * s_dtype.size_in_bytes();
6005                let bytes_match_shape = s_len_bytes == layout_bytes;
6006                let already_contig = source_layout.is_contiguous()
6007                    && source_layout.start_offset() == 0
6008                    && bytes_match_shape;
6009                if already_contig {
6010                    source_arc
6011                } else {
6012                    auto_contiguize(&source_arc, &source_layout)?
6013                }
6014            };
6015            let source_layout_kernel = fuel_ir::Layout::contiguous(source_layout.shape().clone());
6016            // The kernel sees inputs=[source] and outputs=[dest_arc].
6017            // The dest input slot is intentionally absent — the kernel
6018            // doesn't read from dest; it only writes to its bytes
6019            // through the output slot's write lock.
6020            let input_arcs = vec![source_arc_contig];
6021            let mut output_arcs = vec![dest_arc.clone()];
6022            let kernel_layouts = vec![source_layout_kernel, dest_layout.clone()];
6023            // A4b-1: defer the wait — return the handle to the realize loop.
6024            let handle = execute_compiled_with_wait_hint(
6025                compiled,
6026                &input_arcs,
6027                &mut output_arcs,
6028                &kernel_layouts,
6029                will_be_waited,
6030            )?;
6031            // Adopt the dest Arc at this WriteSlice node's slot. The
6032            // realize loop's destructive_input cleanup evicts the
6033            // dest's own NodeId from the cache afterward — downstream
6034            // readers go through this node's NodeId.
6035            cache.insert(item.node_id, dest_arc);
6036            layout_cache.insert(item.node_id, item.output_layout.clone());
6037            Ok(handle)
6038        }
6039        WorkItemKind::WriteSliceRotating {
6040            dest,
6041            source,
6042            position,
6043        } => {
6044            // Same shape as WriteSlice but with a position input.
6045            // Kernel sees `[source, position]` as inputs; `dest` is the
6046            // pre-allocated output buffer (in-place adoption).
6047            let compiled = item.compiled.as_ref().ok_or_else(|| {
6048                Error::Msg(format!(
6049                    "PipelinedExecutor: WriteSliceRotating work item {:?} has no compiled node",
6050                    item.node_id,
6051                ))
6052                .bt()
6053            })?;
6054            let dest_arc = cache.get(dest).cloned().ok_or_else(|| {
6055                Error::Msg(format!(
6056                    "PipelinedExecutor: WriteSliceRotating destination {:?} of {:?} not realized",
6057                    dest, item.node_id,
6058                ))
6059                .bt()
6060            })?;
6061            let source_arc = cache.get(source).cloned().ok_or_else(|| {
6062                Error::Msg(format!(
6063                    "PipelinedExecutor: WriteSliceRotating source {:?} of {:?} not realized",
6064                    source, item.node_id,
6065                ))
6066                .bt()
6067            })?;
6068            let position_arc = cache.get(position).cloned().ok_or_else(|| {
6069                Error::Msg(format!(
6070                    "PipelinedExecutor: WriteSliceRotating position {:?} of {:?} not realized",
6071                    position, item.node_id,
6072                ))
6073                .bt()
6074            })?;
6075            let dest_layout = layout_cache.get(dest).cloned().ok_or_else(|| {
6076                Error::Msg(format!(
6077                    "PipelinedExecutor: WriteSliceRotating destination {:?} of {:?} has no cached layout",
6078                    dest, item.node_id,
6079                ))
6080                .bt()
6081            })?;
6082            let source_layout = layout_cache.get(source).cloned().ok_or_else(|| {
6083                Error::Msg(format!(
6084                    "PipelinedExecutor: WriteSliceRotating source {:?} of {:?} has no cached layout",
6085                    source, item.node_id,
6086                ))
6087                .bt()
6088            })?;
6089            // v1: destination contiguous + zero offset (same as WriteSlice).
6090            if !dest_layout.is_contiguous() || dest_layout.start_offset() != 0 {
6091                return Err(Error::Msg(format!(
6092                    "Op::WriteSliceRotating (v1): destination {:?} must be \
6093                     contiguous + zero-offset; got Layout {:?}",
6094                    dest, dest_layout,
6095                ))
6096                .bt());
6097            }
6098            let source_arc_contig = {
6099                let s_dtype = source_arc
6100                    .read()
6101                    .map_err(|_| poisoned("WriteSliceRotating source storage"))?
6102                    .dtype;
6103                let s_len_bytes = source_arc
6104                    .read()
6105                    .map_err(|_| poisoned("WriteSliceRotating source storage"))?
6106                    .inner
6107                    .len_bytes();
6108                let layout_bytes = source_layout.shape().elem_count() * s_dtype.size_in_bytes();
6109                let bytes_match_shape = s_len_bytes == layout_bytes;
6110                let already_contig = source_layout.is_contiguous()
6111                    && source_layout.start_offset() == 0
6112                    && bytes_match_shape;
6113                if already_contig {
6114                    source_arc
6115                } else {
6116                    auto_contiguize(&source_arc, &source_layout)?
6117                }
6118            };
6119            let source_layout_kernel = fuel_ir::Layout::contiguous(source_layout.shape().clone());
6120            let position_layout = fuel_ir::Layout::contiguous(fuel_ir::Shape::from_dims(&[]));
6121            let input_arcs = vec![source_arc_contig, position_arc];
6122            let mut output_arcs = vec![dest_arc.clone()];
6123            let kernel_layouts = vec![source_layout_kernel, position_layout, dest_layout.clone()];
6124            // A4b-1: defer the wait — return the handle to the realize loop.
6125            let handle = execute_compiled_with_wait_hint(
6126                compiled,
6127                &input_arcs,
6128                &mut output_arcs,
6129                &kernel_layouts,
6130                will_be_waited,
6131            )?;
6132            cache.insert(item.node_id, dest_arc);
6133            layout_cache.insert(item.node_id, item.output_layout.clone());
6134            Ok(handle)
6135        }
6136        WorkItemKind::WriteSliceDoff {
6137            dest,
6138            source,
6139            offset,
6140        } => {
6141            // Same shape as WriteSliceRotating: kernel sees
6142            // `[source, offset]` as inputs; `dest` is the pre-allocated
6143            // output buffer (in-place adoption). The offset (rank-0
6144            // I64) is passed through as a kernel input — the CUDA
6145            // wrapper threads its device pointer straight to the kernel
6146            // (no D2H), which is what makes a captured graph replay at
6147            // the host-updated position.
6148            let compiled = item.compiled.as_ref().ok_or_else(|| {
6149                Error::Msg(format!(
6150                    "PipelinedExecutor: WriteSliceDoff work item {:?} has no compiled node",
6151                    item.node_id,
6152                ))
6153                .bt()
6154            })?;
6155            let dest_arc = cache.get(dest).cloned().ok_or_else(|| {
6156                Error::Msg(format!(
6157                    "PipelinedExecutor: WriteSliceDoff destination {:?} of {:?} not realized",
6158                    dest, item.node_id,
6159                ))
6160                .bt()
6161            })?;
6162            let source_arc = cache.get(source).cloned().ok_or_else(|| {
6163                Error::Msg(format!(
6164                    "PipelinedExecutor: WriteSliceDoff source {:?} of {:?} not realized",
6165                    source, item.node_id,
6166                ))
6167                .bt()
6168            })?;
6169            let offset_arc = cache.get(offset).cloned().ok_or_else(|| {
6170                Error::Msg(format!(
6171                    "PipelinedExecutor: WriteSliceDoff offset {:?} of {:?} not realized",
6172                    offset, item.node_id,
6173                ))
6174                .bt()
6175            })?;
6176            let dest_layout = layout_cache.get(dest).cloned().ok_or_else(|| {
6177                Error::Msg(format!(
6178                    "PipelinedExecutor: WriteSliceDoff destination {:?} of {:?} has no cached layout",
6179                    dest, item.node_id,
6180                ))
6181                .bt()
6182            })?;
6183            let source_layout = layout_cache.get(source).cloned().ok_or_else(|| {
6184                Error::Msg(format!(
6185                    "PipelinedExecutor: WriteSliceDoff source {:?} of {:?} has no cached layout",
6186                    source, item.node_id,
6187                ))
6188                .bt()
6189            })?;
6190            // v1: destination contiguous + zero offset (same as WriteSlice).
6191            if !dest_layout.is_contiguous() || dest_layout.start_offset() != 0 {
6192                return Err(Error::Msg(format!(
6193                    "Op::WriteSliceDoff (v1): destination {:?} must be \
6194                     contiguous + zero-offset; got Layout {:?}",
6195                    dest, dest_layout,
6196                ))
6197                .bt());
6198            }
6199            let source_arc_contig = {
6200                let s_dtype = source_arc
6201                    .read()
6202                    .map_err(|_| poisoned("WriteSliceDoff source storage"))?
6203                    .dtype;
6204                let s_len_bytes = source_arc
6205                    .read()
6206                    .map_err(|_| poisoned("WriteSliceDoff source storage"))?
6207                    .inner
6208                    .len_bytes();
6209                let layout_bytes = source_layout.shape().elem_count() * s_dtype.size_in_bytes();
6210                let bytes_match_shape = s_len_bytes == layout_bytes;
6211                let already_contig = source_layout.is_contiguous()
6212                    && source_layout.start_offset() == 0
6213                    && bytes_match_shape;
6214                if already_contig {
6215                    source_arc
6216                } else {
6217                    auto_contiguize(&source_arc, &source_layout)?
6218                }
6219            };
6220            let source_layout_kernel = fuel_ir::Layout::contiguous(source_layout.shape().clone());
6221            let offset_layout = fuel_ir::Layout::contiguous(fuel_ir::Shape::from_dims(&[]));
6222            let input_arcs = vec![source_arc_contig, offset_arc];
6223            let mut output_arcs = vec![dest_arc.clone()];
6224            let kernel_layouts = vec![source_layout_kernel, offset_layout, dest_layout.clone()];
6225            // A4b-1: defer the wait — return the handle to the realize loop.
6226            let handle = execute_compiled_with_wait_hint(
6227                compiled,
6228                &input_arcs,
6229                &mut output_arcs,
6230                &kernel_layouts,
6231                will_be_waited,
6232            )?;
6233            cache.insert(item.node_id, dest_arc);
6234            layout_cache.insert(item.node_id, item.output_layout.clone());
6235            Ok(handle)
6236        }
6237        WorkItemKind::Alloc { target_location } => {
6238            // Op::Alloc { target }: allocate a fresh, zero-init storage
6239            // on target_location. No inputs, no kernel call — direct
6240            // executor dispatch. For non-CPU targets the per-backend
6241            // device handle comes from the `DeviceRegistry` the caller
6242            // handed the realize (a `*_with_devices` entry point).
6243            // Used only by the Vulkan arm below (alloc_bytes_handle); a
6244            // default-feature build sees it unused. GAP-229: 68161981's
6245            // unused_variables --fix renamed it `_n_bytes` at default
6246            // features and broke `--features vulkan` (E0425). Guard the
6247            // decline instead of the name so the binding stays usable.
6248            #[cfg_attr(not(feature = "vulkan"), allow(unused_variables))]
6249            let n_bytes = item.elem_count * item.dtype.size_in_bytes();
6250            let alloced: Storage = match target_location {
6251                // CPU has no separate uninit alloc primitive in safe
6252                // Rust (`vec![0; n]` is the canonical path). Op::Alloc
6253                // on CPU returns zero-init storage; the following
6254                // Op::ZeroFill is a redundant memset the optimizer
6255                // can elide and LLVM folds away regardless.
6256                DeviceLocation::Cpu => fuel_memory::alloc_cpu_zeroed(item.dtype, item.elem_count)?,
6257                #[cfg(feature = "cuda")]
6258                DeviceLocation::Cuda { gpu_id } => {
6259                    let cuda_dev = devices.cuda(*gpu_id).ok_or_else(|| {
6260                        Error::Msg(format!(
6261                            "Op::Alloc on Cuda {{ gpu_id: {} }}: no CUDA \
6262                             device registered for this place. Hand the device to \
6263                             the realize in a `DeviceRegistry` (a `*_with_devices` \
6264                             entry point).",
6265                            gpu_id,
6266                        ))
6267                        .bt()
6268                    })?;
6269                    // Phase 3a follow-up: true uninit alloc via
6270                    // baracuda alpha.30's unsafe alloc. The bytes are
6271                    // uninit until a subsequent Op::ZeroFill or full-
6272                    // overwrite op runs. The byte-storage Arc has no
6273                    // typed-slice accessor that would dereference
6274                    // uninit bytes.
6275                    let cuda_bytes =
6276                        fuel_cuda_backend::CudaStorageBytes::alloc_uninit(&cuda_dev, n_bytes)?;
6277                    Storage::new(fuel_memory::BackendStorage::Cuda(cuda_bytes), item.dtype)
6278                }
6279                #[cfg(not(feature = "cuda"))]
6280                DeviceLocation::Cuda { .. } => {
6281                    return Err(Error::Msg(
6282                        "Op::Alloc on Cuda but fuel-storage wasn't built \
6283                         with --features cuda"
6284                            .to_string(),
6285                    )
6286                    .bt());
6287                }
6288                #[cfg(feature = "vulkan")]
6289                DeviceLocation::Vulkan { gpu_id } => {
6290                    let backend = devices.vulkan(*gpu_id).ok_or_else(|| {
6291                        Error::Msg(format!(
6292                            "Op::Alloc on Vulkan {{ gpu_id: {} }}: no Vulkan \
6293                             device registered for this place. Hand the device to \
6294                             the realize in a `DeviceRegistry` (a `*_with_devices` \
6295                             entry point).",
6296                            gpu_id,
6297                        ))
6298                        .bt()
6299                    })?;
6300                    // Phase 3a follow-up: true uninit alloc. The old
6301                    // `upload_bytes_handle(vec![0u8; n])` host-staged
6302                    // zeros (~2× the bandwidth of a device-side fill);
6303                    // we now allocate uninit and rely on a paired
6304                    // Op::ZeroFill (vkCmdFillBuffer) for the
6305                    // initialization. Faster KV-cache init on Vulkan.
6306                    let vk_bytes = backend.alloc_bytes_handle(n_bytes)?;
6307                    Storage::new(fuel_memory::BackendStorage::Vulkan(vk_bytes), item.dtype)
6308                }
6309                #[cfg(not(feature = "vulkan"))]
6310                DeviceLocation::Vulkan { .. } => {
6311                    return Err(Error::Msg(
6312                        "Op::Alloc on Vulkan but fuel-storage wasn't built \
6313                         with --features vulkan"
6314                            .to_string(),
6315                    )
6316                    .bt());
6317                }
6318                other => {
6319                    return Err(Error::Msg(format!(
6320                        "Op::Alloc on {:?}: target not yet wired (CPU + \
6321                         CUDA + Vulkan land in Phase 3a of bridge-retirement; \
6322                         Metal extends when its byte-storage substrate is \
6323                         ready).",
6324                        other,
6325                    ))
6326                    .bt());
6327                }
6328            };
6329            cache.insert(item.node_id, Arc::new(RwLock::new(alloced)));
6330            layout_cache.insert(item.node_id, item.output_layout.clone());
6331            Ok(CompletionHandle::Ready)
6332        }
6333        WorkItemKind::Iota { len } => {
6334            // Op::Iota { len }: 0-input F32 position generator
6335            // [0.0, 1.0, …, (len-1)]. Direct executor dispatch (no kernel /
6336            // binding-table lookup), like WorkItemKind::Alloc. CPU-only
6337            // today — GPU flash-attn keeps its fused kernel, so the alibi
6338            // decomposition (the sole Iota consumer) realizes on CPU.
6339            if item.target_backend != BackendId::Cpu {
6340                return Err(Error::Msg(format!(
6341                    "WorkItemKind::Iota: only CPU is wired today, got {:?}",
6342                    item.target_backend,
6343                ))
6344                .bt());
6345            }
6346            let v: Vec<f32> = (0..*len).map(|i| i as f32).collect();
6347            let iota = fuel_memory::from_slice_cpu(&v);
6348            cache.insert(item.node_id, Arc::new(RwLock::new(iota)));
6349            layout_cache.insert(item.node_id, item.output_layout.clone());
6350            Ok(CompletionHandle::Ready)
6351        }
6352        WorkItemKind::ZeroFill => {
6353            // Op::ZeroFill: in-place zero the input's bytes. Output
6354            // adopts the input's Storage Arc (same Storage; bytes
6355            // are mutated). Direct per-backend dispatch — no kernel
6356            // call, no binding-table lookup.
6357            if item.inputs.len() != 1 {
6358                return Err(Error::Msg(format!(
6359                    "PipelinedExecutor: ZeroFill work item {:?} expects \
6360                     1 input, got {}",
6361                    item.node_id,
6362                    item.inputs.len(),
6363                ))
6364                .bt());
6365            }
6366            let src_id = item.inputs[0];
6367            let src_arc = cache.get(&src_id).cloned().ok_or_else(|| {
6368                Error::Msg(format!(
6369                    "PipelinedExecutor: ZeroFill input {:?} of {:?} \
6370                     not realized",
6371                    src_id, item.node_id,
6372                ))
6373                .bt()
6374            })?;
6375            // Per-backend in-place fill. Acquired the write lock once
6376            // for the duration of the fill — kernels on async backends
6377            // (CUDA / Vulkan) issue the memset and return; the fence
6378            // happens when downstream readers acquire the read lock
6379            // through the executor's standard synchronization path.
6380            {
6381                let mut guard = src_arc
6382                    .write()
6383                    .map_err(|_| poisoned("ZeroFill destination storage"))?;
6384                match &mut guard.inner {
6385                    fuel_memory::BackendStorage::Cpu(c) => {
6386                        let bytes = c.bytes_mut();
6387                        bytes.fill(0);
6388                    }
6389                    #[cfg(feature = "cuda")]
6390                    fuel_memory::BackendStorage::Cuda(c) => {
6391                        c.zero_async()?;
6392                    }
6393                    #[cfg(feature = "vulkan")]
6394                    fuel_memory::BackendStorage::Vulkan(v) => {
6395                        let backend = v
6396                            .backend()
6397                            .ok_or_else(|| {
6398                                Error::Msg(
6399                                    "Op::ZeroFill on Vulkan: input has no \
6400                                 attached backend handle. Storage must \
6401                                 come from VulkanBackend::alloc_bytes_handle \
6402                                 / upload_bytes_handle."
6403                                        .to_string(),
6404                                )
6405                                .bt()
6406                            })?
6407                            .clone();
6408                        backend.fill_bytes_zero(v)?;
6409                    }
6410                    #[allow(unreachable_patterns)]
6411                    other => {
6412                        return Err(Error::Msg(format!(
6413                            "Op::ZeroFill: backend not wired ({other:?}); \
6414                             CPU + CUDA + Vulkan covered, Metal extends \
6415                             when its byte-storage substrate is ready.",
6416                        ))
6417                        .bt());
6418                    }
6419                }
6420            }
6421            // Adopt the (now-zero) Storage Arc at this node's slot.
6422            // Downstream readers go through `node_id`; the original
6423            // input's NodeId is evicted from the cache by the
6424            // realize loop's destructive_input cleanup.
6425            cache.insert(item.node_id, src_arc);
6426            layout_cache.insert(item.node_id, item.output_layout.clone());
6427            // A4b-1: ZeroFill's CUDA memset is same-stream (and Op::Alloc
6428            // typically zero-inits, so this is usually elided). Its completion
6429            // is carried by the realize-end full-stream sync in `to_cpu_bytes`
6430            // (unchanged) and same-stream ordering — `Ready` is behavior-preserving.
6431            Ok(CompletionHandle::Ready)
6432        }
6433        WorkItemKind::Copy { target_location } | WorkItemKind::Move { target_location } => {
6434            // Op::Copy / Op::Move { target }: kernel lookup at
6435            // (OpKind::Copy, [dt, dt], source_backend) — the wrapper
6436            // downloads from its own residency into a freshly-
6437            // allocated output on `target_location`. We auto-
6438            // contiguize the input first so the kernel always sees
6439            // the logical view's bytes (a transpose-view source
6440            // materializes into a contiguous buffer before download).
6441            //
6442            // Move shares this entire data-movement half; its
6443            // destructive half (release the source) is driven by the
6444            // realize loop's `destructive_input` cleanup after this
6445            // arm returns — see `WorkItemKind::Move`.
6446            let op_label = if matches!(item.kind, WorkItemKind::Move { .. }) {
6447                "Move"
6448            } else {
6449                "Copy"
6450            };
6451            let compiled = item.compiled.as_ref().ok_or_else(|| {
6452                Error::Msg(format!(
6453                    "PipelinedExecutor: {op_label} work item {:?} has no compiled node",
6454                    item.node_id,
6455                ))
6456                .bt()
6457            })?;
6458            if item.inputs.len() != 1 {
6459                return Err(Error::Msg(format!(
6460                    "PipelinedExecutor: {op_label} work item {:?} expects 1 input, got {}",
6461                    item.node_id,
6462                    item.inputs.len(),
6463                ))
6464                .bt());
6465            }
6466            let src_id = item.inputs[0];
6467            let src_arc = cache.get(&src_id).cloned().ok_or_else(|| {
6468                Error::Msg(format!(
6469                    "PipelinedExecutor: {op_label} input {:?} of {:?} not realized",
6470                    src_id, item.node_id,
6471                ))
6472                .bt()
6473            })?;
6474            // Multi-output Option C guard: Op::Copy on a bundled
6475            // producer would silently drop the bundle metadata on
6476            // the destination, and the auto-contiguize step below
6477            // would treat the bundle as a flat slot-0-shaped buffer
6478            // and corrupt non-primary slots. Until the per-backend
6479            // whole-bundle-Copy hook lands, point callers at the
6480            // supported per-slot path:
6481            // Op::View → Op::Copy → Op::ViewOwned.
6482            //
6483            // Exception: when the immediate input is an Op::View
6484            // projection (its layout's byte extent is strictly less
6485            // than the bundle's total bytes), the View has already
6486            // narrowed the slab. auto-contiguize walks the View's
6487            // layout and produces a flat slot-shaped buffer that's
6488            // correctly sized — no data loss, no slot corruption.
6489            // The guard only fires when the Copy targets the bundle
6490            // root directly.
6491            {
6492                let guard = src_arc
6493                    .read()
6494                    .map_err(|_| poisoned("Copy source storage"))?;
6495                if guard.is_bundled() {
6496                    let layout_bytes_for_guard = layout_cache
6497                        .get(&src_id)
6498                        .map(|l| l.shape().elem_count() * guard.dtype.size_in_bytes())
6499                        .unwrap_or(usize::MAX);
6500                    let bundle_bytes = guard.inner.len_bytes();
6501                    let is_whole_bundle = layout_bytes_for_guard >= bundle_bytes;
6502                    if is_whole_bundle {
6503                        return Err(Error::Msg(format!(
6504                            "PipelinedExecutor: Op::{op_label} on a bundled producer \
6505                             ({:?}) is not yet supported (Option C followup). \
6506                             Use Op::View → Op::Copy → Op::ViewOwned for \
6507                             per-slot cross-device moves, or wait for the \
6508                             per-backend whole-bundle-Copy hook.",
6509                            src_id,
6510                        ))
6511                        .bt());
6512                    }
6513                }
6514            }
6515            let src_layout = layout_cache.get(&src_id).cloned().ok_or_else(|| {
6516                Error::Msg(format!(
6517                    "PipelinedExecutor: {op_label} input {:?} of {:?} has no cached layout",
6518                    src_id, item.node_id,
6519                ))
6520                .bt()
6521            })?;
6522            let src_dtype = src_arc
6523                .read()
6524                .map_err(|_| poisoned("Copy source storage"))?
6525                .dtype;
6526            let src_len_bytes = src_arc
6527                .read()
6528                .map_err(|_| poisoned("Copy source storage"))?
6529                .inner
6530                .len_bytes();
6531            let layout_bytes = src_layout.shape().elem_count() * src_dtype.size_in_bytes();
6532            let bytes_match_shape = src_len_bytes == layout_bytes;
6533            let already_contig =
6534                src_layout.is_contiguous() && src_layout.start_offset() == 0 && bytes_match_shape;
6535            let src_input = if already_contig {
6536                src_arc
6537            } else {
6538                auto_contiguize(&src_arc, &src_layout)?
6539            };
6540            let kernel_input_layout = fuel_ir::Layout::contiguous(src_layout.shape().clone());
6541            // CapturedRun build-out (4b-ζ): in Reuse (capture/replay) mode,
6542            // reuse the fixed-address buffer recorded during the warm run
6543            // instead of allocating — device allocation is illegal inside a
6544            // capture scope. Only a same-device CUDA target_location ever
6545            // reaches Reuse mode for a Copy node in practice: capture_decode's
6546            // validation loop rejects every Cpu/Vulkan target_location before
6547            // a capture scope is ever entered (Move is rejected unconditionally
6548            // there too), so this arm trusts that invariant rather than
6549            // re-deriving it — the `DeviceLocation::Cuda` guard below is just
6550            // belt-and-suspenders for any other Reuse-mode caller.
6551            let reuse_arc = match &persistent {
6552                Some(p) if p.mode == PersistentMode::Reuse => match target_location {
6553                    DeviceLocation::Cuda { .. } => p.map.get(&item.node_id).cloned(),
6554                    _ => None,
6555                },
6556                _ => None,
6557            };
6558            // Allocate the output on `target_location`. Phase 2
6559            // covered D2H (target=Cpu); Phase 3b extends to H2D
6560            // (target=Cuda / Vulkan from a CPU source). For non-CPU
6561            // targets the device handle comes from the caller's
6562            // `DeviceRegistry` (a `*_with_devices` entry point), as for
6563            // Op::Alloc.
6564            // Used only by the Vulkan arm below (alloc_bytes_handle); a
6565            // default-feature build sees it unused. GAP-229: 68161981's
6566            // unused_variables --fix renamed it `_n_bytes` at default
6567            // features and broke `--features vulkan` (E0425). Guard the
6568            // decline instead of the name so the binding stays usable.
6569            #[cfg_attr(not(feature = "vulkan"), allow(unused_variables))]
6570            let n_bytes = item.elem_count * item.dtype.size_in_bytes();
6571            let input_arcs = vec![src_input];
6572            let mut output_arcs = if let Some(arc) = reuse_arc {
6573                vec![arc]
6574            } else {
6575                let output = match target_location {
6576                    DeviceLocation::Cpu => {
6577                        fuel_memory::alloc_cpu_zeroed(item.dtype, item.elem_count)?
6578                    }
6579                    #[cfg(feature = "cuda")]
6580                    DeviceLocation::Cuda { gpu_id } => {
6581                        let cuda_dev = devices.cuda(*gpu_id).ok_or_else(|| {
6582                            Error::Msg(format!(
6583                                "Op::{op_label} on Cuda {{ gpu_id: {} }}: no CUDA \
6584                                 device registered for this place. Hand the device to \
6585                                 the realize in a `DeviceRegistry` (a `*_with_devices` \
6586                                 entry point) before an H2D Op::{op_label}.",
6587                                gpu_id,
6588                            ))
6589                            .bt()
6590                        })?;
6591                        let cuda_bytes =
6592                            fuel_cuda_backend::CudaStorageBytes::alloc_uninit(&cuda_dev, n_bytes)?;
6593                        Storage::new(fuel_memory::BackendStorage::Cuda(cuda_bytes), item.dtype)
6594                    }
6595                    #[cfg(not(feature = "cuda"))]
6596                    DeviceLocation::Cuda { .. } => {
6597                        return Err(Error::Msg(format!(
6598                            "Op::{op_label} target Cuda but fuel-storage wasn't built \
6599                             with --features cuda",
6600                        ))
6601                        .bt());
6602                    }
6603                    #[cfg(feature = "vulkan")]
6604                    DeviceLocation::Vulkan { gpu_id } => {
6605                        let backend = devices.vulkan(*gpu_id).ok_or_else(|| {
6606                            Error::Msg(format!(
6607                                "Op::{op_label} on Vulkan {{ gpu_id: {} }}: no Vulkan \
6608                                 device registered for this place. Hand the device to \
6609                                 the realize in a `DeviceRegistry` (a `*_with_devices` \
6610                                 entry point) before an H2D Op::{op_label}.",
6611                                gpu_id,
6612                            ))
6613                            .bt()
6614                        })?;
6615                        let vk_bytes = backend.alloc_bytes_handle(n_bytes)?;
6616                        Storage::new(fuel_memory::BackendStorage::Vulkan(vk_bytes), item.dtype)
6617                    }
6618                    #[cfg(not(feature = "vulkan"))]
6619                    DeviceLocation::Vulkan { .. } => {
6620                        return Err(Error::Msg(format!(
6621                            "Op::{op_label} target Vulkan but fuel-storage wasn't built \
6622                             with --features vulkan",
6623                        ))
6624                        .bt());
6625                    }
6626                    other => {
6627                        return Err(Error::Msg(format!(
6628                            "PipelinedExecutor: Op::{op_label} target_location {:?} not yet \
6629                             wired (CPU + CUDA + Vulkan covered; Metal extends when \
6630                             its byte-storage substrate is ready).",
6631                            other
6632                        ))
6633                        .bt());
6634                    }
6635                };
6636                vec![Arc::new(RwLock::new(output))]
6637            };
6638            let kernel_layouts = vec![kernel_input_layout, item.output_layout.clone()];
6639            // A4b-1: defer the wait — return the handle to the realize loop.
6640            let handle = execute_compiled_with_wait_hint(
6641                compiled,
6642                &input_arcs,
6643                &mut output_arcs,
6644                &kernel_layouts,
6645                will_be_waited,
6646            )?;
6647            let arc = output_arcs.into_iter().next().expect("one output");
6648            // CapturedRun build-out (4b-ζ): Record (warm) mode remembers this
6649            // node's fixed output buffer so the capture run reuses the
6650            // identical device address. No-op in Reuse mode (the buffer came
6651            // FROM the map) and in None mode. Mirrors the Kernel arm's
6652            // Record-mode snapshot (above) exactly.
6653            if let Some(p) = persistent.as_deref_mut()
6654                && p.mode == PersistentMode::Record
6655            {
6656                p.map.insert(item.node_id, Arc::clone(&arc));
6657            }
6658            cache.insert(item.node_id, arc);
6659            layout_cache.insert(item.node_id, item.output_layout.clone());
6660            Ok(handle)
6661        }
6662        WorkItemKind::ReleaseMarker => {
6663            // Emit a zero-byte CPU storage at the Release node's
6664            // slot. Per Op::Release's contract the marker is never
6665            // read — this exists so any downstream cache lookup of
6666            // `release_id` resolves rather than failing. The actual
6667            // deallocation of `inputs[0]` is driven by the realize
6668            // loop's `destructive_input` cleanup (Phase B).
6669            let marker = fuel_memory::alloc_cpu_zeroed(item.dtype, 0)?;
6670            cache.insert(item.node_id, Arc::new(RwLock::new(marker)));
6671            layout_cache.insert(item.node_id, item.output_layout.clone());
6672            Ok(CompletionHandle::Ready)
6673        }
6674        WorkItemKind::ContiguizeOf { input } => {
6675            let input_arc = cache.get(input).cloned().ok_or_else(|| {
6676                Error::Msg(format!(
6677                    "PipelinedExecutor: reshape input {:?} of {:?} not realized",
6678                    input, item.node_id,
6679                ))
6680                .bt()
6681            })?;
6682            let input_layout = layout_cache.get(input).cloned().ok_or_else(|| {
6683                Error::Msg(format!(
6684                    "PipelinedExecutor: reshape input {:?} of {:?} has no cached layout",
6685                    input, item.node_id,
6686                ))
6687                .bt()
6688            })?;
6689            // CapturedRun build-out (4b-γ): in Reuse (capture/replay) mode,
6690            // reuse the fixed-address buffer recorded during the warm run —
6691            // device allocation is illegal inside a capture scope. Always
6692            // write-into when reusing (skip the zero-copy-vs-allocate
6693            // branch entirely): a given ContiguizeOf node's zero-copy-ness
6694            // is a static layout/stride property, identical across the warm
6695            // and capture passes (both replay the same compiled item list
6696            // with the same static layouts per capture_decode's own
6697            // design), so if this node ever needed the map entry it
6698            // allocated on warm too and the entry is guaranteed present.
6699            let reuse_arc = match &persistent {
6700                Some(p) if p.mode == PersistentMode::Reuse => p.map.get(&item.node_id).cloned(),
6701                _ => None,
6702            };
6703            let out_arc = if let Some(dest_arc) = reuse_arc {
6704                contiguize_into(&dest_arc, &input_arc, &input_layout)?;
6705                dest_arc
6706            } else if input_layout.is_contiguous() && input_layout.start_offset() == 0 {
6707                // Zero-copy when the input is already contiguous + zero
6708                // offset — never allocates, so Record mode has nothing to
6709                // record for this node (no fixed address to reuse).
6710                input_arc
6711            } else {
6712                // Allocate + copy via the contiguize kernel.
6713                let arc = auto_contiguize(&input_arc, &input_layout)?;
6714                if let Some(p) = persistent.as_deref_mut()
6715                    && p.mode == PersistentMode::Record
6716                {
6717                    p.map.insert(item.node_id, Arc::clone(&arc));
6718                }
6719                arc
6720            };
6721            cache.insert(item.node_id, out_arc);
6722            layout_cache.insert(item.node_id, item.output_layout.clone());
6723            // A4b-1: a materializing contiguize (CUDA) is same-stream; its
6724            // completion is carried by the realize-end full-stream sync in
6725            // `to_cpu_bytes` (unchanged) — `Ready` here is behavior-preserving.
6726            Ok(CompletionHandle::Ready)
6727        }
6728        WorkItemKind::Kernel => {
6729            let compiled = item.compiled.as_ref().ok_or_else(|| {
6730                Error::Msg(format!(
6731                    "PipelinedExecutor: Kernel work item {:?} has no compiled node",
6732                    item.node_id,
6733                ))
6734                .bt()
6735            })?;
6736            // Dynamic-M matmul (sparse MoE): resolve a DATA-DETERMINED row
6737            // count from the producer-bound `produced_syms` and run against
6738            // the patched (resolved-M) node. `None` on the common path.
6739            let patched_mm = resolve_deferred_matmul(compiled, produced_syms, item.node_id)?;
6740            let compiled = patched_mm.as_ref().unwrap_or(compiled);
6741            // Gather input Arcs from the cache, auto-contiguizing
6742            // any input whose layout is non-contiguous (typically
6743            // produced by an upstream metadata-only view op).
6744            // Today's kernels assume contiguous; this pass keeps
6745            // that invariant true at every kernel call site.
6746            //
6747            // We assemble a parallel `kernel_layouts` vec — the layout
6748            // of the bytes the kernel actually receives. After
6749            // auto-contiguize, that's `Layout::contiguous(shape)` for
6750            // the input's shape; for inputs already contiguous we use
6751            // the cached layout directly. Output layout comes last.
6752            let mut input_arcs: Vec<Arc<RwLock<Storage>>> = Vec::with_capacity(item.inputs.len());
6753            let mut kernel_layouts: Vec<fuel_ir::Layout> =
6754                Vec::with_capacity(item.inputs.len() + 1);
6755            // The kernel's `strided_input` cap lets non-contiguous
6756            // inputs (broadcast, transpose, etc.) flow through without
6757            // materialization — the kernel walks strides itself. Inputs
6758            // with non-zero `start_offset` still go through auto-
6759            // Contiguize today; offset honoring on the byte buffer is
6760            // a separate concern from stride support.
6761            let kernel_handles_strided = compiled.caps.strided_input;
6762            let t_gather = crate::compiled::op_profile::PhaseTimer::start("kernel.gather_inputs");
6763            for in_id in &item.inputs {
6764                let in_arc = cache.get(in_id).cloned().ok_or_else(|| {
6765                    Error::Msg(format!(
6766                        "PipelinedExecutor: input {:?} of {:?} not realized",
6767                        in_id, item.node_id,
6768                    ))
6769                    .bt()
6770                })?;
6771                let in_layout = layout_cache.get(in_id).cloned().ok_or_else(|| {
6772                    Error::Msg(format!(
6773                        "PipelinedExecutor: input {:?} of {:?} has no cached layout",
6774                        in_id, item.node_id,
6775                    ))
6776                    .bt()
6777                })?;
6778                // "Already contig" means more than `is_contiguous()`:
6779                // the LAYOUT's element count must also match the
6780                // STORAGE's byte count for shape-validating kernels
6781                // (concat_cpu, etc.) that read `storage.len_bytes()`.
6782                // A first-N slice view has `is_contiguous() == true`
6783                // (strides match canonical [1] for shape [N]) but its
6784                // storage is the parent's full bytes — too big. In
6785                // that case we auto-contiguize to materialize only
6786                // the view's portion as a fresh storage.
6787                //
6788                // Same constraint applies to strided_ok: kernels that
6789                // declare strided support can walk strided inputs, but
6790                // the byte count check at the kernel surface still
6791                // assumes storage.len_bytes() == layout.elem_count() *
6792                // dtype.size_bytes(). Until kernels universally trust
6793                // layout over storage, we conservatively materialize.
6794                let in_dtype = in_arc.read().map_err(|_| poisoned("input storage"))?.dtype;
6795                let in_len_bytes = in_arc
6796                    .read()
6797                    .map_err(|_| poisoned("input storage"))?
6798                    .inner
6799                    .len_bytes();
6800                let layout_bytes = in_layout.shape().elem_count() * in_dtype.size_in_bytes();
6801                let bytes_match_shape = in_len_bytes == layout_bytes;
6802                let already_contig =
6803                    in_layout.is_contiguous() && in_layout.start_offset() == 0 && bytes_match_shape;
6804                let strided_ok =
6805                    kernel_handles_strided && in_layout.start_offset() == 0 && bytes_match_shape;
6806                if already_contig || strided_ok {
6807                    input_arcs.push(in_arc);
6808                    kernel_layouts.push(in_layout);
6809                } else {
6810                    let contig_arc = auto_contiguize(&in_arc, &in_layout)?;
6811                    input_arcs.push(contig_arc);
6812                    kernel_layouts.push(fuel_ir::Layout::contiguous(in_layout.shape().clone()));
6813                }
6814            }
6815            drop(t_gather);
6816            kernel_layouts.push(item.output_layout.clone());
6817
6818            // Allocate output on the target backend. For GPU backends
6819            // we derive the device handle from the first input —
6820            // every kernel has ≥1 input (Op::Const is handled via
6821            // ConstAdopt, never via Kernel), and an input on the
6822            // target backend carries its own device. This avoids
6823            // threading a device handle through `realize`.
6824            //
6825            // Multi-output (Option C, item 3): when the WorkItem
6826            // carries an `output_bundle`, size the allocation to
6827            // span every slot's bytes (primary-dtype-element count
6828            // rounded up from the bundle's total byte span) and
6829            // attach the bundle metadata after allocation.
6830            let (alloc_elem_count, bundle_to_attach) = match &item.output_bundle {
6831                Some(bundle) => {
6832                    let dtype_bytes = item.dtype.size_in_bytes().max(1);
6833                    let total_bytes = bundle.iter().fold(0usize, |acc, s| {
6834                        let end = s.byte_offset.saturating_add(s.len_bytes());
6835                        acc.max(end)
6836                    });
6837                    let elems = total_bytes.div_ceil(dtype_bytes);
6838                    (elems, Some(Arc::clone(bundle)))
6839                }
6840                None => (item.elem_count, None),
6841            };
6842            // CapturedRun build-out: in Reuse (capture/replay) mode, reuse the
6843            // FIXED-ADDRESS buffer recorded during the warm run instead of
6844            // allocating — device allocation is illegal inside a capture scope,
6845            // and reusing the same address is what makes the captured graph's
6846            // baked kernel arguments valid on replay. In Record (warm) or None
6847            // mode, allocate as usual (below).
6848            let reuse_arc = match &persistent {
6849                Some(p) if p.mode == PersistentMode::Reuse => {
6850                    Some(p.map.get(&item.node_id).cloned().ok_or_else(|| {
6851                        Error::Msg(format!(
6852                            "PipelinedExecutor: capture (reuse) mode has no persistent \
6853                             output buffer for kernel node {:?}; the warm (record) run \
6854                             must realize every kernel node before capture",
6855                            item.node_id,
6856                        ))
6857                        .bt()
6858                    })?)
6859                }
6860                _ => None,
6861            };
6862            let t_alloc = crate::compiled::op_profile::PhaseTimer::start("kernel.alloc_output");
6863            let mut output_arcs = if let Some(arc) = reuse_arc {
6864                vec![arc]
6865            } else {
6866                let output = match item.target_backend {
6867                    BackendId::Cpu => fuel_memory::alloc_cpu_zeroed(item.dtype, alloc_elem_count)?,
6868                    #[cfg(feature = "cuda")]
6869                    BackendId::Cuda => {
6870                        let first_in = input_arcs.first().ok_or_else(|| {
6871                            Error::Msg(format!(
6872                                "PipelinedExecutor: kernel {:?} on Cuda has no inputs; \
6873                             cannot derive device for output allocation",
6874                                item.node_id,
6875                            ))
6876                            .bt()
6877                        })?;
6878                        let guard = first_in.read().map_err(|_| poisoned("input storage"))?;
6879                        let cuda_in = match &guard.inner {
6880                            fuel_memory::BackendStorage::Cuda(c) => c,
6881                            other => {
6882                                return Err(Error::Msg(format!(
6883                                    "PipelinedExecutor: kernel {:?} target_backend=Cuda but \
6884                                 input has BackendStorage::{:?}; mixed-backend kernels \
6885                                 require an explicit Op::Copy first",
6886                                    item.node_id,
6887                                    other.backend_id(),
6888                                ))
6889                                .bt());
6890                            }
6891                        };
6892                        let n_bytes = alloc_elem_count * item.dtype.size_in_bytes();
6893                        let cuda_bytes =
6894                            fuel_cuda_backend::CudaStorageBytes::alloc(cuda_in.device(), n_bytes)?;
6895                        fuel_memory::Storage::new(
6896                            fuel_memory::BackendStorage::Cuda(cuda_bytes),
6897                            item.dtype,
6898                        )
6899                    }
6900                    #[cfg(feature = "vulkan")]
6901                    BackendId::Vulkan => {
6902                        // Mirror the CUDA path: derive the backend handle
6903                        // from the first input's `VulkanStorageBytes::backend()`.
6904                        // Vulkan catch-up V.1.B (2026-05-21) — requires
6905                        // inputs constructed via `alloc_bytes_handle` /
6906                        // `upload_bytes_handle` so they carry the
6907                        // `Arc<VulkanBackend>` (mirroring CUDA's
6908                        // `Arc<CudaDevice>`).
6909                        let first_in = input_arcs.first().ok_or_else(|| {
6910                            Error::Msg(format!(
6911                                "PipelinedExecutor: kernel {:?} on Vulkan has no inputs; \
6912                             cannot derive backend handle for output allocation",
6913                                item.node_id,
6914                            ))
6915                            .bt()
6916                        })?;
6917                        let guard = first_in.read().map_err(|_| poisoned("input storage"))?;
6918                        let vk_in = match &guard.inner {
6919                            fuel_memory::BackendStorage::Vulkan(v) => v,
6920                            other => {
6921                                return Err(Error::Msg(format!(
6922                                    "PipelinedExecutor: kernel {:?} target_backend=Vulkan but \
6923                                 input has BackendStorage::{:?}; mixed-backend kernels \
6924                                 require an explicit Op::Copy first",
6925                                    item.node_id,
6926                                    other.backend_id(),
6927                                ))
6928                                .bt());
6929                            }
6930                        };
6931                        let backend = vk_in.backend().ok_or_else(|| {
6932                            Error::Msg(format!(
6933                                "PipelinedExecutor: Vulkan kernel {:?} input has no backend \
6934                             handle. Storages flowing through the pipelined executor's \
6935                             Vulkan path must be constructed via \
6936                             VulkanBackend::alloc_bytes_handle / upload_bytes_handle \
6937                             (not the legacy alloc_bytes / upload_bytes which leave \
6938                             VulkanStorageBytes::backend = None).",
6939                                item.node_id,
6940                            ))
6941                            .bt()
6942                        })?;
6943                        let n_bytes = alloc_elem_count * item.dtype.size_in_bytes();
6944                        let vk_bytes = backend.alloc_bytes_handle(n_bytes)?;
6945                        fuel_memory::Storage::new(
6946                            fuel_memory::BackendStorage::Vulkan(vk_bytes),
6947                            item.dtype,
6948                        )
6949                    }
6950                    other => {
6951                        return Err(Error::Msg(format!(
6952                            "PipelinedExecutor: target_backend {:?} output allocation \
6953                         not yet implemented (CPU + CUDA + Vulkan wired; Metal extends later)",
6954                            other
6955                        ))
6956                        .bt());
6957                    }
6958                };
6959                // Attach bundle metadata when this is a multi-output op.
6960                // The kernel sees the allocated bytes; the bundle lives
6961                // at the Storage wrapper level so downstream Op::View /
6962                // Op::ViewOwned can resolve their slot windows.
6963                let output = match bundle_to_attach {
6964                    Some(bundle) => output.with_bundle(bundle)?,
6965                    None => output,
6966                };
6967                vec![Arc::new(RwLock::new(output))]
6968            };
6969            drop(t_alloc);
6970
6971            // A4b-1: defer the wait — return the handle to the realize loop.
6972            let t_launch =
6973                crate::compiled::op_profile::PhaseTimer::start("kernel.execute_compiled");
6974            let handle = execute_compiled_with_wait_hint(
6975                compiled,
6976                &input_arcs,
6977                &mut output_arcs,
6978                &kernel_layouts,
6979                will_be_waited,
6980            )?;
6981            drop(t_launch);
6982
6983            let arc = output_arcs.into_iter().next().expect("one output");
6984
6985            // CapturedRun build-out: Record (warm) mode remembers this node's
6986            // fixed output buffer so the capture run reuses the identical
6987            // device address. No-op in Reuse mode (the buffer came FROM the
6988            // map) and in None mode.
6989            if let Some(p) = persistent
6990                && p.mode == PersistentMode::Record
6991            {
6992                p.map.insert(item.node_id, Arc::clone(&arc));
6993            }
6994
6995            // Data-determined dynamic-shapes seam (increment 2a): a
6996            // producer that computes a runtime count publishes it into the
6997            // per-pass `SymEnv` so downstream ops can consume it as a
6998            // dynamic extent. `Op::NonZeroIndices` writes its count into
6999            // bundle slot 1; read it back and bind `count_sym`. This is the
7000            // FIRST op to bind a *data-determined* symbol mid-realize (all
7001            // prior binds are host-known before realize). Single-threaded:
7002            // the executor runs items topologically, so this bind precedes
7003            // any consumer's execute-time resolution.
7004            if let OpParams::NonZeroIndices {
7005                capacity,
7006                count_sym,
7007            } = &compiled.op_params
7008            {
7009                bind_data_determined_count(&arc, *capacity, *count_sym, produced_syms)?;
7010            }
7011
7012            cache.insert(item.node_id, arc);
7013            layout_cache.insert(item.node_id, item.output_layout.clone());
7014            Ok(handle)
7015        }
7016        WorkItemKind::InplaceKernel { target_idx } => {
7017            let compiled = item.compiled.as_ref().ok_or_else(|| {
7018                Error::Msg(format!(
7019                    "PipelinedExecutor: InplaceKernel work item {:?} has no compiled node",
7020                    item.node_id,
7021                ))
7022                .bt()
7023            })?;
7024            let target_id = *item.inputs.get(*target_idx).ok_or_else(|| {
7025                Error::Msg(format!(
7026                    "PipelinedExecutor: InplaceKernel work item {:?} target_idx={} \
7027                     out of bounds (inputs.len()={})",
7028                    item.node_id,
7029                    target_idx,
7030                    item.inputs.len(),
7031                ))
7032                .bt()
7033            })?;
7034            let target_arc = cache.get(&target_id).cloned().ok_or_else(|| {
7035                Error::Msg(format!(
7036                    "PipelinedExecutor: InplaceKernel target {:?} of {:?} not realized",
7037                    target_id, item.node_id,
7038                ))
7039                .bt()
7040            })?;
7041            let target_layout = layout_cache.get(&target_id).cloned().ok_or_else(|| {
7042                Error::Msg(format!(
7043                    "PipelinedExecutor: InplaceKernel target {:?} of {:?} has no cached layout",
7044                    target_id, item.node_id,
7045                ))
7046                .bt()
7047            })?;
7048            // v1 contract: target must be contiguous + zero offset.
7049            // Strided in-place targets would force the kernel to walk
7050            // strides for writes too; defer until a concrete consumer
7051            // needs it (mirrors `Op::WriteSlice`'s v1 dest contract).
7052            if !target_layout.is_contiguous() || target_layout.start_offset() != 0 {
7053                return Err(Error::Msg(format!(
7054                    "InplaceKernel (Phase 3 v1): target {:?} must be contiguous + \
7055                     zero-offset; got Layout {:?}",
7056                    target_id, target_layout,
7057                ))
7058                .bt());
7059            }
7060            // Kernel sees inputs=[non-target IR inputs in order] and
7061            // outputs=[target_arc]. For unary in-place (1 IR input at
7062            // target_idx=0) the input vec is empty, matching the
7063            // original Phase 3e contract. For binary in-place
7064            // (target_idx=0, 2 IR inputs) the wrapper sees the
7065            // non-destructive RHS as `inputs[0]`. The wrapper acquires
7066            // outputs[0]'s write lock and mutates through its
7067            // bytes_mut(). Layout vector contains the kernel's
7068            // inputs+outputs layouts in that order.
7069            let mut input_arcs: Vec<Arc<RwLock<Storage>>> = Vec::new();
7070            let mut kernel_layouts: Vec<Layout> = Vec::new();
7071            for (i, &input_id) in item.inputs.iter().enumerate() {
7072                if i == *target_idx {
7073                    continue;
7074                }
7075                let arc = cache.get(&input_id).cloned().ok_or_else(|| {
7076                    Error::Msg(format!(
7077                        "PipelinedExecutor: InplaceKernel non-target input {:?} of {:?} \
7078                         not realized",
7079                        input_id, item.node_id,
7080                    ))
7081                    .bt()
7082                })?;
7083                let lay = layout_cache.get(&input_id).cloned().ok_or_else(|| {
7084                    Error::Msg(format!(
7085                        "PipelinedExecutor: InplaceKernel non-target input {:?} of {:?} \
7086                         has no cached layout",
7087                        input_id, item.node_id,
7088                    ))
7089                    .bt()
7090                })?;
7091                input_arcs.push(arc);
7092                kernel_layouts.push(lay);
7093            }
7094            let mut output_arcs = vec![target_arc.clone()];
7095            kernel_layouts.push(target_layout.clone());
7096            // A4b-1: defer the wait — return the handle to the realize loop.
7097            let handle = execute_compiled_with_wait_hint(
7098                compiled,
7099                &input_arcs,
7100                &mut output_arcs,
7101                &kernel_layouts,
7102                will_be_waited,
7103            )?;
7104            // Adopt the target Arc at this node's slot. The realize
7105            // loop's destructive_input cleanup evicts the target's own
7106            // NodeId from the cache afterward.
7107            cache.insert(item.node_id, target_arc);
7108            layout_cache.insert(item.node_id, item.output_layout.clone());
7109            Ok(handle)
7110        }
7111    }
7112}
7113
7114fn poisoned(what: &'static str) -> Error {
7115    Error::Msg(format!("PipelinedExecutor: {} poisoned", what)).bt()
7116}
7117
7118/// Step E A4b-1: record a node's [`CompletionHandle`] in the executor's
7119/// per-node handle map.
7120///
7121/// `Ready` handles (CPU / Vulkan / view-and-alloc arms) carry no async work, so
7122/// we DON'T store them — keeping the map to genuinely-pending entries makes the
7123/// realize-end empty-after-drain assert (open question #6) meaningful and keeps
7124/// the drain O(pending) rather than O(nodes). A re-used NodeId (in-place adopt
7125/// re-keys an existing slot) waits the prior handle first so nothing leaks.
7126#[inline]
7127fn store_handle(
7128    handles: &mut HashMap<NodeId, CompletionHandle>,
7129    node_id: NodeId,
7130    handle: CompletionHandle,
7131) {
7132    if matches!(handle, CompletionHandle::Ready) {
7133        // A prior pending handle at this slot must still be waited (don't drop a
7134        // Pending silently). In practice NodeIds are unique per realize, so this
7135        // is just defensive.
7136        if let Some(prev) = handles.remove(&node_id) {
7137            let _ = prev.wait();
7138        }
7139        return;
7140    }
7141    if let Some(prev) = handles.insert(node_id, handle) {
7142        let _ = prev.wait();
7143    }
7144}
7145
7146/// Step E A4b-3: the FINER cross-device producer wait.
7147///
7148/// Before dispatching a cross-device `Op::Copy` / `Op::Move` WorkItem, the
7149/// executor calls this on the copy's single source input. It removes the
7150/// source producer's [`CompletionHandle`] from the map and waits it — so the
7151/// specific producer P is complete before the D2H reads P's device buffer,
7152/// WITHOUT draining the whole source device (the conservative pre-A4b-3
7153/// behavior, where `to_cpu_bytes`'s `device.synchronize()` blocked on ALL
7154/// in-flight work on that device — including the OTHER sub-DAG's independent
7155/// work A4b-4 wants to overlap).
7156///
7157/// - **CUDA producer** → waits P's recorded `Event` (`cuEventSynchronize`):
7158///   fires after P + its already-ordered stream predecessors, nothing else.
7159/// - **Absent / `Ready` producer** (CPU producer, or a Vulkan producer — which
7160///   under A4b-2 is `Ready` mid-walk because nothing is submitted until
7161///   realize-end) → no-op. A Vulkan SOURCE's own ordering is handled inside
7162///   `download_bytes` (it `force_flush`es the open batch then reads), so there
7163///   is no mid-walk Vulkan handle to wait here; the cross-device Vulkan→CPU hop
7164///   stays correct without one.
7165///
7166/// Removing the handle here (rather than waiting it again at realize-end) keeps
7167/// `drain_handles`' post-drain empty-map assert meaningful and avoids a
7168/// double-wait. Waiting it twice would be harmless (`cuEventSynchronize` on an
7169/// already-signalled event is a fast no-op), but the consume-once contract is
7170/// cleaner. The producing node's *storage* stays in the cache for downstream
7171/// readers; only its completion handle is consumed.
7172fn wait_producer_handle(
7173    handles: &mut HashMap<NodeId, CompletionHandle>,
7174    producer: NodeId,
7175) -> Result<()> {
7176    if let Some(handle) = handles.remove(&producer) {
7177        handle.wait()?;
7178    }
7179    Ok(())
7180}
7181
7182/// Step E A4b-1: realize-end drain — wait every outstanding async handle, then
7183/// clear the map.
7184///
7185/// **Event-recording / wait strategy (A4b-1 §1.2).** CUDA has one stream per
7186/// device, and an `Event` recorded after a node's launch signals when that
7187/// node *and all prior stream work* have completed. So once the
7188/// latest-recorded event on a device has signalled, every earlier event on that
7189/// device is already signalled too: waiting them is a non-blocking
7190/// `cuEventQuery` fast-path, not N host stalls. We therefore wait every stored
7191/// handle (correct + simple).
7192///
7193/// **Open question #4 — "event only where waited" — RESOLVED.** Recording an
7194/// `Event` for every node was measured negligible on a 32-op synthetic, but
7195/// real decode graphs run 150-200+ ops; `pipelined`'s `WaitSet` pre-scan (see
7196/// `compiler_work_and_wait_set_for` / `build_wait_set`) now restricts event
7197/// production to the nodes some later cross-device `Copy`/`Move` will
7198/// individually wait — same-device-only ("elided") nodes get
7199/// `CompletionHandle::Ready` with no `cuEventCreate`/`cuEventRecord` at all
7200/// (`execute_compiled_with_wait_hint`). This drain therefore now retires only
7201/// the (typically few) wait-set handles that were never consumed mid-walk by
7202/// `wait_producer_handle`; it is no longer sufficient on its own to guarantee
7203/// every enqueued CUDA kernel has completed — `sync_active_cuda_devices` below
7204/// covers the elided remainder. We keep a per-node handle (rather than a
7205/// single per-device event) for the wait-set members because A4b-3's finer
7206/// cross-device wait needs to wait a *specific producer's* completion — the
7207/// per-node handle is that seam.
7208fn drain_handles(handles: &mut HashMap<NodeId, CompletionHandle>) -> Result<()> {
7209    for (_node, handle) in handles.drain() {
7210        handle.wait()?;
7211    }
7212    // Open question #6: once handles are stored instead of `wait`ed inline, the
7213    // `#[must_use]` on `CompletionHandle` can't catch a leaked (never-waited)
7214    // handle at the call site. The drain consumes the whole map, so it is empty
7215    // here by construction; assert it to catch a future leak (e.g. a new
7216    // dispatch path that forgets to thread its handle through `store_handle`).
7217    debug_assert!(
7218        handles.is_empty(),
7219        "A4b-1: handle map must be empty after drain"
7220    );
7221    Ok(())
7222}
7223
7224/// Step E A4b open question #4 step 3 — the realize-end complement to the
7225/// "event only where waited" elision. Because most CUDA nodes in a long
7226/// single-device chain no longer record an `Event` (see `drain_handles`'s
7227/// doc), this does ONE blanket `cuStreamSynchronize` per CUDA device that
7228/// still holds LIVE storage in `cache` — the realize target(s) plus any
7229/// surviving intermediates — instead of relying on per-node handles to cover
7230/// them.
7231///
7232/// **Why this is safe + sufficient.** CUDA has one stream per device, and
7233/// this executor dispatches strictly sequentially (one work item at a time,
7234/// in topological order) — so by the time a live node's own kernel was
7235/// launched, every same-device ancestor it depends on was ALREADY enqueued
7236/// earlier on the SAME stream. Stream ordering (not a host wait) guarantees
7237/// those ancestors run to completion no later than the live node's own
7238/// kernel. Syncing the live node's device therefore flushes its entire
7239/// same-device dependency chain, elided or not. Cross-device ancestors are
7240/// unaffected by elision — they always went through an `Op::Copy`/`Move`,
7241/// whose producer is in the `WaitSet` and was already waited explicitly at
7242/// the cross-device boundary (`wait_producer_handle`), mid-walk.
7243///
7244/// **Why evicted (non-live) intermediates don't need this.** A node whose
7245/// storage was evicted before realize-end (the `destructive_input` cleanup)
7246/// is never read by anything this realize returns; A3's stream-ordered
7247/// alloc/free already makes its eventual completion safe without a host
7248/// wait (the driver serializes the free after the freeing stream position,
7249/// same as any other stream-ordered op) — nothing to synchronize for.
7250///
7251/// No-op when `cache` holds no CUDA storage (CPU/Vulkan-only realize).
7252#[cfg(feature = "cuda")]
7253fn sync_active_cuda_devices(cache: &StorageCache) -> Result<()> {
7254    let mut devices: HashMap<fuel_ir::DeviceLocation, fuel_cuda_backend::CudaDevice> =
7255        HashMap::new();
7256    for arc in cache.values() {
7257        let guard = arc
7258            .read()
7259            .map_err(|_| poisoned("cache storage (cuda realize-end sync scan)"))?;
7260        if let fuel_memory::BackendStorage::Cuda(c) = &guard.inner {
7261            devices
7262                .entry(c.device().location())
7263                .or_insert_with(|| c.device().clone());
7264        }
7265    }
7266    for dev in devices.values() {
7267        dev.synchronize()?;
7268    }
7269    Ok(())
7270}
7271
7272/// Non-CUDA builds never produce CUDA storage, so there is nothing to sync —
7273/// keeps the call site unconditional across both feature configurations.
7274#[cfg(not(feature = "cuda"))]
7275fn sync_active_cuda_devices(_cache: &StorageCache) -> Result<()> {
7276    Ok(())
7277}
7278
7279/// Step E A4b-2: a Vulkan [`Completion`](crate::compiled::Completion) over an
7280/// in-flight (submitted, not-yet-waited) batch. `wait` blocks on the batch's
7281/// fence (`vkWaitForFences`) — which fires when the whole submitted command
7282/// buffer has retired on the single compute queue — then releases the batch
7283/// (frees the CB / descriptor sets / transient buffers / retired pool, all now
7284/// idle on the GPU).
7285///
7286/// The fence is per-BATCH, not per-node: one `submit_pending` flushes every op
7287/// recorded since the last submit, so this single handle covers a contiguous run
7288/// of Vulkan nodes (the A2 batching win, preserved — fewer fences, larger
7289/// submissions). `backend` keeps the [`VulkanBackend`] alive so the
7290/// post-fence pool retire + the `DeviceInner` the batch's resources reference
7291/// outlive the wait.
7292///
7293/// `Send` (required by `Completion`): every owned field is `Send` — `Fence` /
7294/// `CommandBuffer` / `DescriptorSet` / `Buffer` / `Allocation` / `CommandPool`
7295/// are all `Send` in vulkane (Arc-of-`DeviceInner` + explicit `unsafe impl`s),
7296/// and `Arc<VulkanBackend>` is `Send + Sync`.
7297/// Step E B1: `batch` is an `Option` ONLY so [`Drop`] can coexist with the
7298/// by-value `into_wait` consume. A type with a `Drop` impl cannot be
7299/// destructured by move (`let VulkanCompletion { backend, batch } = self`,
7300/// E0509), so `into_wait` `take()`s the batch out of the `Option` instead of
7301/// moving it out of the struct, then lets the normal `Drop` run. In every
7302/// reachable state the batch is `Some` until exactly one `into_wait` consumes it.
7303#[cfg(feature = "vulkan")]
7304struct VulkanCompletion {
7305    backend: Arc<fuel_vulkan_backend::VulkanBackend>,
7306    batch: Option<fuel_vulkan_backend::SubmittedBatch>,
7307    /// The device this submitted batch counts against in the in-flight counter
7308    /// (Step E B1). `Drop` decrements this slot.
7309    loc: fuel_ir::DeviceLocation,
7310}
7311
7312/// Step E A4b-4: the element type of the executor's in-flight-Vulkan-batch list.
7313/// A [`VulkanCompletion`] on a Vulkan build; a zero-sized placeholder otherwise
7314/// so the realize loops carry one `Vec<InflightVulkan>` local without `cfg` on
7315/// every use site (the helpers `eager_submit_all_vulkan` / `drain_inflight_vulkan`
7316/// are the only code that ever pushes/drains it, and they are `cfg`-gated).
7317#[cfg(feature = "vulkan")]
7318type InflightVulkan = VulkanCompletion;
7319#[cfg(not(feature = "vulkan"))]
7320type InflightVulkan = ();
7321
7322/// Step E A4b-4: is the cross-device copy's SOURCE buffer Vulkan-resident?
7323///
7324/// Used at the cross-device `Op::Copy`/`Op::Move` boundary to decide whether the
7325/// executor must wait the in-flight Vulkan batches before the copy. A Vulkan→CPU
7326/// D2H reads the source on the host, and the Vulkan `download` path only
7327/// `force_flush`es the OPEN batch (never the executor's eagerly-submitted
7328/// in-flight ones), so for a VULKAN source we must `drain_inflight_vulkan` first
7329/// to read completed data. For a CUDA / CPU source we must NOT wait Vulkan — the
7330/// copy doesn't read any Vulkan buffer, and waiting Vulkan there would needlessly
7331/// serialize the independent Vulkan sub-DAG (killing the overlap A4b-4 exists to
7332/// win). Returns `false` when the producer's storage isn't in the cache (treated
7333/// as not-Vulkan → no Vulkan wait; the CUDA/CPU producer handle still covers it).
7334#[cfg(feature = "vulkan")]
7335fn copy_source_is_vulkan(cache: &StorageCache, producer: NodeId) -> Result<bool> {
7336    if let Some(arc) = cache.get(&producer) {
7337        let guard = arc
7338            .read()
7339            .map_err(|_| poisoned("storage lock probing copy-source backend"))?;
7340        return Ok(matches!(
7341            guard.inner,
7342            fuel_memory::BackendStorage::Vulkan(_)
7343        ));
7344    }
7345    Ok(false)
7346}
7347
7348#[cfg(not(feature = "vulkan"))]
7349#[inline]
7350fn copy_source_is_vulkan(_cache: &StorageCache, _producer: NodeId) -> Result<bool> {
7351    Ok(false)
7352}
7353
7354#[cfg(feature = "vulkan")]
7355impl crate::compiled::Completion for VulkanCompletion {
7356    fn wait(self: Box<Self>) -> Result<()> {
7357        // Move the whole `VulkanCompletion` out of the `Box` (allowed even with a
7358        // `Drop` impl — it's a full move, not a destructure) and consume by value.
7359        (*self).into_wait()
7360    }
7361}
7362
7363#[cfg(feature = "vulkan")]
7364impl VulkanCompletion {
7365    /// Build the handle for an eagerly-submitted Vulkan batch and register it as
7366    /// one in-flight batch on `loc` (Step E B1). The matching decrement is in
7367    /// [`Drop`]. `loc` is the backend's `DeviceLocation::Vulkan { gpu_id }`.
7368    fn new(
7369        backend: Arc<fuel_vulkan_backend::VulkanBackend>,
7370        batch: fuel_vulkan_backend::SubmittedBatch,
7371        loc: fuel_ir::DeviceLocation,
7372    ) -> Self {
7373        crate::dispatch::inflight_inc(loc);
7374        Self {
7375            backend,
7376            batch: Some(batch),
7377            loc,
7378        }
7379    }
7380
7381    /// Block on this batch's fence, retire pools, then free the batch. Consumes
7382    /// `self` by value (the by-value sibling of the boxed `Completion::wait`),
7383    /// used by the executor's `inflight_vulkan` drain (A4b-4) where we hold the
7384    /// `VulkanCompletion` unboxed in a `Vec`.
7385    ///
7386    /// Step E B1: `take()`s the batch out of the `Option` (NOT a destructure
7387    /// move — that's illegal with a `Drop` impl) and waits it; the in-flight
7388    /// decrement then rides `self`'s `Drop` as this returns. So a wait-consume
7389    /// and a bare drop (e.g. an error unwinding before the wait) BOTH decrement
7390    /// exactly once, and `into_wait` never double-counts.
7391    fn into_wait(mut self) -> Result<()> {
7392        // `wait_submitted` consumes the batch by value: waits the fence, retires
7393        // pools, then drops the batch (UAF-safe — nothing the in-flight CB
7394        // references frees before the fence signals). After a `new` the batch is
7395        // always `Some`; `take` leaves `None` so `Drop` doesn't touch it again.
7396        if let Some(batch) = self.batch.take() {
7397            self.backend.wait_submitted(batch)?;
7398        }
7399        Ok(())
7400        // `self` drops here → `inflight_dec(self.loc)`.
7401    }
7402
7403    /// Step E A2.1 (deferred-deletion): retain an evicted DATA buffer until THIS
7404    /// in-flight batch's fence signals, then free it post-fence (on the batch's
7405    /// `Drop` — guaranteed post-fence by follow-on #2). Delegates to
7406    /// [`fuel_vulkan_backend::SubmittedBatch::retain_buffer`].
7407    ///
7408    /// The executor calls this for every in-flight batch when it evicts a Vulkan
7409    /// buffer those batches' CBs may read, INSTEAD of host-blocking on a drain.
7410    /// `batch` is `Some` in every reachable mid-walk state (it is `take`n only by
7411    /// `into_wait`/`wait`, which consume the whole `VulkanCompletion`), so the
7412    /// retain always lands on a live in-flight batch.
7413    fn retain_data(&mut self, buf: std::sync::Arc<fuel_vulkan_backend::VulkanBuffer>) {
7414        if let Some(batch) = self.batch.as_mut() {
7415            batch.retain_buffer(buf);
7416        }
7417    }
7418}
7419
7420#[cfg(feature = "vulkan")]
7421impl Drop for VulkanCompletion {
7422    fn drop(&mut self) {
7423        // The single in-flight decrement for a Vulkan batch — fires whether the
7424        // batch was waited (`into_wait` / `wait`) or merely dropped (error
7425        // unwind), so the per-device count returns to baseline. Relaxed +
7426        // saturating (a scheduling hint, never a correctness gate).
7427        crate::dispatch::inflight_dec(self.loc);
7428    }
7429}
7430
7431/// Step E A4b-4 — eager Vulkan submission during the walk (the OVERLAP enabler).
7432///
7433/// Submits each DISTINCT Vulkan backend's currently-open batch WITHOUT waiting,
7434/// pushing the resulting in-flight [`VulkanCompletion`]s onto `inflight` so the
7435/// executor waits them later (at the in-flight-lifetime guard / realize-end). An
7436/// empty open batch yields `None` and is skipped (idempotent).
7437///
7438/// This is what makes a Vulkan sub-DAG actually START on the iGPU while the
7439/// executor records/dispatches the next (CUDA) chunk — without it the Vulkan
7440/// batch sits merely *recorded* until realize-end and never overlaps the CUDA
7441/// stream (design §5). Called ONLY on a genuinely multi-backend realize (gated by
7442/// the executor's `multi_backend` flag); on a single-device graph it is never
7443/// reached, so pure-Vulkan stays byte-identical to A4b-2 (one realize-end submit).
7444///
7445/// **Whole-chunk granularity (UAF/race-safety, design §4 + the Vulkan
7446/// single-queue OOO-completion semantics).** We submit only at chunk boundaries
7447/// and before a cross-device wait — never mid-chunk — so the batch handed to the
7448/// GPU is a COMPLETE contiguous run of Vulkan nodes with all its intra-CB
7449/// dependency barriers (`recorder.rs` `vkCmdPipelineBarrier`) already in place.
7450/// Vulkan only guarantees that batches on one queue BEGIN in submission order;
7451/// they may overlap / complete out of order, so a split mid-chunk would lose the
7452/// write-before-read ordering for ops that read an earlier op's buffer in the
7453/// SAME chunk. By submitting whole chunks and re-syncing (`drain_inflight_vulkan`)
7454/// before any later Vulkan op records, before any cross-device copy, and before
7455/// any Vulkan-referenced eviction, no in-flight batch is ever read or freed while
7456/// still running.
7457#[cfg(feature = "vulkan")]
7458fn eager_submit_all_vulkan(
7459    cache: &StorageCache,
7460    inflight: &mut Vec<VulkanCompletion>,
7461) -> Result<()> {
7462    // Collect distinct Vulkan backends referenced by the cache (dedup by gpu_id).
7463    let mut seen: Vec<usize> = Vec::new();
7464    let mut backends: Vec<Arc<fuel_vulkan_backend::VulkanBackend>> = Vec::new();
7465    for arc in cache.values() {
7466        let guard = arc
7467            .read()
7468            .map_err(|_| poisoned("storage lock during eager vulkan submit"))?;
7469        if let fuel_memory::BackendStorage::Vulkan(v) = &guard.inner
7470            && let Some(backend) = v.backend()
7471            && !seen.contains(&backend.gpu_id)
7472        {
7473            seen.push(backend.gpu_id);
7474            backends.push(backend.clone());
7475        }
7476    }
7477    for backend in backends {
7478        // Step E B1: the per-device location for the in-flight counter. A batch
7479        // submitted here is one in-flight unit on this iGPU until its handle's
7480        // `Drop` (after `drain_inflight_vulkan` / realize-end).
7481        let loc = DeviceLocation::Vulkan {
7482            gpu_id: backend.gpu_id,
7483        };
7484        if let Some(batch) = backend.submit_pending()? {
7485            inflight.push(VulkanCompletion::new(backend, batch, loc));
7486        }
7487    }
7488    Ok(())
7489}
7490
7491#[cfg(not(feature = "vulkan"))]
7492#[inline]
7493fn eager_submit_all_vulkan(
7494    _cache: &StorageCache,
7495    _inflight: &mut Vec<InflightVulkan>,
7496) -> Result<()> {
7497    Ok(())
7498}
7499
7500/// Step E A4b-4 — wait every in-flight (eagerly-submitted) Vulkan batch, then
7501/// clear the list. The re-sync half of [`eager_submit_all_vulkan`].
7502///
7503/// Each `into_wait` blocks on the batch fence (`vkWaitForFences`), retires the
7504/// backend's descriptor pools, and frees the batch (CB / descriptor sets /
7505/// transient buffers / retired command pool — all now idle on the GPU). After
7506/// this returns, NO submitted Vulkan command buffer is still executing, so it is
7507/// safe to (a) record a new Vulkan op that may read a just-produced buffer,
7508/// (b) D2H-copy a Vulkan buffer on the host, or (c) free a buffer a batch read.
7509///
7510/// Because the eager submit happened at the PRIOR chunk boundary and an
7511/// intervening (e.g. CUDA) chunk has since been recorded/dispatched, the fence is
7512/// typically already signalled here — the wait is a fast no-op, and the iGPU work
7513/// genuinely overlapped the other device's stream. Waiting the Vulkan fence does
7514/// NOT touch the CUDA stream, so the other device keeps running (concurrency
7515/// preserved — design §5 "the per-device guards don't cross-stall").
7516#[cfg(feature = "vulkan")]
7517fn drain_inflight_vulkan(inflight: &mut Vec<VulkanCompletion>) -> Result<()> {
7518    for vc in inflight.drain(..) {
7519        vc.into_wait()?;
7520    }
7521    Ok(())
7522}
7523
7524#[cfg(not(feature = "vulkan"))]
7525#[inline]
7526fn drain_inflight_vulkan(_inflight: &mut Vec<InflightVulkan>) -> Result<()> {
7527    Ok(())
7528}
7529
7530/// Step E A4b-2: the realize-end Vulkan drain, SPLIT into submit-then-wait.
7531///
7532/// Replaces A2's `force_flush_all_vulkan` (which submitted + waited atomically
7533/// inside `force_flush`). For each DISTINCT Vulkan backend referenced by the
7534/// cache, `submit_pending` submits the still-open batch WITHOUT waiting (→ a
7535/// `SubmittedBatch`), wraps it in the executor's [`VulkanCompletion`] handle, and
7536/// `wait`s it. Net for a pure-Vulkan realize: the batch still accumulates across
7537/// the whole walk (the per-op path keeps returning `Ready`; no eager submit —
7538/// that is A4b-4) and is submitted ONCE here, then waited — **byte-identical to
7539/// A2**, same single submission at realize-end, just split through the handle.
7540///
7541/// Idempotent across repeated cache arcs: the first `submit_pending` on a backend
7542/// returns `Some(batch)`; subsequent calls on the same backend see an empty batch
7543/// and return `None` (skipped) — exactly the `force_flush` idempotence A2 relied
7544/// on. No-op for a non-Vulkan build.
7545#[cfg(feature = "vulkan")]
7546fn drain_vulkan_pending(cache: &StorageCache) -> Result<()> {
7547    use crate::compiled::CompletionHandle;
7548    for arc in cache.values() {
7549        let backend = {
7550            let guard = arc
7551                .read()
7552                .map_err(|_| poisoned("storage lock during vulkan submit_pending"))?;
7553            match &guard.inner {
7554                fuel_memory::BackendStorage::Vulkan(v) => v.backend().cloned(),
7555                _ => None,
7556            }
7557        };
7558        let Some(backend) = backend else { continue };
7559        // Submit the open batch (if any) without waiting, then wait via the
7560        // completion handle. Empty batch → None → nothing to wait.
7561        // Step E B1: `new` increments the in-flight counter for this device;
7562        // `handle.wait()` waits + drops the `VulkanCompletion`, decrementing it
7563        // — a balanced submit/retire even on this transient realize-end path.
7564        let loc = DeviceLocation::Vulkan {
7565            gpu_id: backend.gpu_id,
7566        };
7567        if let Some(batch) = backend.submit_pending()? {
7568            let handle: CompletionHandle =
7569                CompletionHandle::Pending(Box::new(VulkanCompletion::new(backend, batch, loc)));
7570            handle.wait()?;
7571        }
7572    }
7573    Ok(())
7574}
7575
7576#[cfg(not(feature = "vulkan"))]
7577fn drain_vulkan_pending(_cache: &StorageCache) -> Result<()> {
7578    Ok(())
7579}
7580
7581/// Step E A2: force the Vulkan backend behind `arc` (if any) to submit + WAIT
7582/// its open batch — the blocking drain before freeing a buffer the batch may
7583/// reference (a destructive eviction) so a recorded-but-unsubmitted command never
7584/// reads freed memory. No-op for non-Vulkan storage, an empty batch, or a
7585/// non-Vulkan build.
7586///
7587/// **Retained for the SINGLE-DEVICE path (byte-identical to pre-A2.1).** A2.1's
7588/// deferred-deletion ([`defer_evicted_vulkan_buffer`]) replaces this only on a
7589/// MULTI-backend realize, where eager-submit + in-flight tracking + the
7590/// realize-end `drain_inflight_vulkan` are all live. On a single-device Vulkan
7591/// realize the A4b machinery is gated off (`multi_backend == false`): the
7592/// cross-batch RAW guard (`pipelined.rs:832`) does not run, so a later Vulkan op
7593/// reading a buffer an eager-submitted batch wrote could race (separate
7594/// submissions only BEGIN in order, may overlap). The blocking `force_flush`
7595/// (submit + wait) is the coherent eviction drain there — exactly the original
7596/// behavior — so single-device stays byte-identical and UAF-safe.
7597#[cfg(feature = "vulkan")]
7598fn force_flush_vulkan(arc: &Arc<RwLock<Storage>>) -> Result<()> {
7599    let guard = arc
7600        .read()
7601        .map_err(|_| poisoned("storage lock during vulkan force_flush"))?;
7602    if let fuel_memory::BackendStorage::Vulkan(v) = &guard.inner
7603        && let Some(backend) = v.backend()
7604    {
7605        backend.force_flush()?;
7606    }
7607    Ok(())
7608}
7609
7610#[cfg(not(feature = "vulkan"))]
7611fn force_flush_vulkan(_arc: &Arc<RwLock<Storage>>) -> Result<()> {
7612    Ok(())
7613}
7614
7615/// Step E A2.1 — DEFERRED-DELETION of a Vulkan data buffer evicted while Vulkan
7616/// work is in flight (the throughput refinement that REPLACES the eviction-time
7617/// drain on a MULTI-backend realize). Called at the per-NodeId destructive
7618/// eviction (`Op::Release`/`Op::Move` cleanup) for the buffer about to leave the
7619/// cache, INSTEAD of `drain_inflight_vulkan` + `force_flush` (two host-blocking
7620/// fence waits) — so the iGPU work the executor was overlapping with CUDA is not
7621/// stalled at every eviction.
7622///
7623/// Two classes of Vulkan reader can hold a reference to `destroyed`'s buffer at
7624/// the eviction:
7625///   1. the **in-flight** `SubmittedBatch`es in `inflight` (submitted CBs, each
7626///      fenced), and
7627///   2. the **open**, not-yet-submitted recorder batch (recorded commands, NO
7628///      fence yet).
7629///
7630/// We make BOTH fence-gated without blocking the host:
7631///   - `eager_submit_all_vulkan` submits the open batch WITHOUT waiting, turning
7632///     it into one more in-flight `SubmittedBatch` (now fenced) pushed onto
7633///     `inflight`. (Whole-chunk granularity — UAF/race-safe per its contract; at a
7634///     destructive eviction the open batch is a contiguous Vulkan run.)
7635///   - We then move a refcount clone of the evicted buffer's `Arc<VulkanBuffer>`
7636///     into EVERY in-flight batch (conservative: we cannot cheaply map
7637///     buffer→batch, exactly the reason the old drain waited *all* of them). Each
7638///     batch frees its retained clone POST-fence on `Drop` (follow-on #2).
7639///
7640/// After this returns the caller `cache.remove`s `destroyed`; the cache's
7641/// `Arc<RwLock<Storage>>` drops, but the buffer's recycler
7642/// (`VulkanBuffer::drop`) reclaims it only when its LAST `Arc` drops — and the
7643/// retained clones keep it alive until their owning batches' fences signal. So the
7644/// GPU's last read of the buffer strictly precedes the free (NO use-after-free),
7645/// the host never blocks at the eviction (the iGPU keeps overlapping CUDA — the
7646/// throughput win), and every batch (hence every retained buffer) is drained by
7647/// realize-end at the latest (`drain_inflight_vulkan`, `pipelined.rs:916/1238`,
7648/// runs unconditionally → NO leak).
7649///
7650/// **Multi-backend only** (the call site gates `if multi_backend`). On a
7651/// single-device realize the open batch is drained by the blocking
7652/// [`force_flush_vulkan`] instead (byte-identical to pre-A2.1; see its doc for
7653/// why the deferred path is unsafe without the cross-batch RAW guard). No-op for a
7654/// non-Vulkan storage, an empty open + no in-flight batches, or a non-Vulkan build.
7655/// Open-batch size (dispatches) at which a deferred eviction submits the batch so the
7656/// GPU runs it while the host keeps recording.
7657#[cfg(feature = "vulkan")]
7658const EVICT_SUBMIT_MIN_DISPATCHES: usize = 48;
7659
7660#[cfg(feature = "vulkan")]
7661fn defer_evicted_vulkan_buffer(
7662    cache: &StorageCache,
7663    destroyed: NodeId,
7664    inflight: &mut Vec<VulkanCompletion>,
7665) -> Result<()> {
7666    // Pull the evicted buffer's device Arc (and its backend) out of the cache BEFORE
7667    // it is removed. Non-Vulkan storage, a host-evicted (no device buffer) Vulkan
7668    // storage, or an absent entry → nothing to retain (no Vulkan reader can hold a
7669    // device buffer).
7670    let (buf, backend) = {
7671        let Some(arc) = cache.get(&destroyed) else {
7672            return Ok(());
7673        };
7674        let guard = arc
7675            .read()
7676            .map_err(|_| poisoned("storage lock during deferred-eviction retain"))?;
7677        match &guard.inner {
7678            fuel_memory::BackendStorage::Vulkan(v) => (v.device_buffer_arc(), v.backend().cloned()),
7679            _ => (None, None),
7680        }
7681    };
7682    let Some(buf) = buf else { return Ok(()) };
7683
7684    // The OPEN batch may hold recorded-but-unsubmitted commands that read `destroyed`:
7685    // retain the buffer on the open batch itself (freed post-fence once that batch is
7686    // submitted and waited). This neither submits nor waits — it used to eager-submit
7687    // here, i.e. one queue submit per eviction (61 per Qwen3 decode step).
7688    // Whether the open batch held recorded work (so the retain above actually kept a reader's
7689    // buffer alive instead of blocking): read BEFORE the eager submit below empties it.
7690    let retained_in_open_batch = backend.as_ref().is_some_and(|b| b.open_batch_len() > 0);
7691    if let Some(backend) = &backend {
7692        backend.retain_in_open_batch(buf.clone());
7693    }
7694    // Retain a clone of the evicted buffer in EVERY in-flight batch. Each frees it
7695    // POST-fence on `Drop` — the buffer outlives the GPU's last read with no host
7696    // block. Conservative over all batches (no cheap buffer→batch map); over-retention
7697    // only lengthens the lifetime, never a UAF, and all batches drain by realize-end.
7698    for vc in inflight.iter_mut() {
7699        vc.retain_data(buf.clone());
7700    }
7701    // Keep the GPU fed: submit the open batch once it has grown by a chunk.
7702    if let Some(backend) = backend
7703        && backend.open_batch_len() >= EVICT_SUBMIT_MIN_DISPATCHES
7704    {
7705        eager_submit_all_vulkan(cache, inflight)?;
7706    }
7707    // Step E A2.1 — throughput-observability. Count a DEFERRED retain that
7708    // actually replaced a host block: an evicted Vulkan buffer retained onto ≥1
7709    // in-flight batch (the open-batch eager-submit and/or pre-existing in-flight
7710    // batches). Pre-A2.1 every such site host-blocked (`force_flush` and/or
7711    // `drain_inflight_vulkan`); now it does not. A test reads
7712    // [`deferred_eviction_retains`] to assert the deferred path fired without a
7713    // drain (deterministic — no wall-clock, which is noisy on this box). When
7714    // `inflight` is empty AND the open batch was empty there was genuinely no in-flight/open
7715    // Vulkan reader to wait for, so no host block was avoided (and none was needed) — not
7716    // counted. A retain onto a non-empty OPEN batch counts (GAP-371: the counter used to look
7717    // only at in-flight batches, so an eviction inside the still-open batch, which is the
7718    // common single-chunk case, never advanced it even though it avoided the host block).
7719    if retained_in_open_batch || !inflight.is_empty() {
7720        DEFERRED_EVICTION_RETAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7721    }
7722    Ok(())
7723}
7724
7725/// Step E A2.1 — cumulative count of deferred-deletion retains that replaced a
7726/// host-blocking eviction drain (an evicted Vulkan buffer retained onto ≥1
7727/// in-flight batch instead of waiting it). Process-global, `Relaxed` — a pure
7728/// test/telemetry observation, never a correctness gate (mirrors the B1 in-flight
7729/// counter idiom). Read by the live deferred-eviction throughput test.
7730#[cfg(feature = "vulkan")]
7731pub static DEFERRED_EVICTION_RETAINS: std::sync::atomic::AtomicUsize =
7732    std::sync::atomic::AtomicUsize::new(0);
7733
7734/// Read the A2.1 deferred-eviction-retain counter (see
7735/// [`DEFERRED_EVICTION_RETAINS`]). `pub` so the live throughput test can assert a
7736/// deferred retain fired (the eviction did NOT host-block on a Vulkan fence).
7737#[cfg(feature = "vulkan")]
7738pub fn deferred_eviction_retains() -> usize {
7739    DEFERRED_EVICTION_RETAINS.load(std::sync::atomic::Ordering::Relaxed)
7740}
7741
7742#[cfg(not(feature = "vulkan"))]
7743#[inline]
7744fn defer_evicted_vulkan_buffer(
7745    _cache: &StorageCache,
7746    _destroyed: NodeId,
7747    _inflight: &mut Vec<InflightVulkan>,
7748) -> Result<()> {
7749    Ok(())
7750}
7751
7752/// Materialize a contiguous Storage Arc from a non-contiguous one.
7753/// Allocates a fresh buffer on the input's backend and copies the
7754/// strided / offset / broadcast input into it via the backend's
7755/// contiguize kernel. The returned Arc is a brand-new buffer; the
7756/// caller is responsible for replacing the cache entry only for the
7757/// duration of one kernel call (the upstream view op's output stays
7758/// in the cache so other consumers still see the strided view).
7759///
7760/// Stage 4 of Layout-on-Node — auto-Contiguize.
7761fn auto_contiguize(arc: &Arc<RwLock<Storage>>, layout: &Layout) -> Result<Arc<RwLock<Storage>>> {
7762    let in_guard = arc
7763        .read()
7764        .map_err(|_| poisoned("input storage lock during auto_contiguize"))?;
7765    let dtype = in_guard.dtype;
7766    let dtype_size = dtype.size_in_bytes();
7767    let new_storage = match &in_guard.inner {
7768        fuel_memory::BackendStorage::Cpu(c) => {
7769            let new_bytes = fuel_cpu_backend::byte_kernels::contiguize_cpu(c, layout, dtype_size)?;
7770            Storage::new(fuel_memory::BackendStorage::Cpu(new_bytes), dtype)
7771        }
7772        #[cfg(feature = "cuda")]
7773        fuel_memory::BackendStorage::Cuda(c) => {
7774            // Native baracuda contiguize (alpha.29). Byte-width-
7775            // dispatched: 1/2/4/8/16 byte elements all route to the
7776            // appropriate kernel. Handles signed strides (Flip),
7777            // zero strides (BroadcastTo), and non-zero element offset.
7778            //
7779            // Three host-side fast paths bake into the baracuda
7780            // launchers: already-contiguous → single cuMemcpyDtoDAsync;
7781            // innermost-stride-1 → per-outer-coord run copy; generic
7782            // → one thread per output element. Retires the prior
7783            // D2H → CPU contiguize_cpu → H2D fallback (two device
7784            // round-trips per non-contig input).
7785            let contig = fuel_cuda_backend::baracuda::contiguize::contiguize_to_fresh(
7786                c, layout, dtype_size,
7787            )?;
7788            Storage::new(fuel_memory::BackendStorage::Cuda(contig), dtype)
7789        }
7790        #[cfg(feature = "vulkan")]
7791        fuel_memory::BackendStorage::Vulkan(v) => {
7792            // Native `strided_copy_signed_*` kernel when it applies (2/4/8-byte
7793            // elements; see `contiguize_vulkan`). Otherwise the V.1.B host round trip:
7794            // D2H → CPU contiguize_cpu → H2D, which forces a flush and a wait
7795            // per call.
7796            let backend = v.backend().ok_or_else(|| {
7797                Error::Msg(
7798                    "auto_contiguize: Vulkan input has no backend handle. \
7799                     Storages flowing through the pipelined executor's Vulkan \
7800                     path must be constructed via VulkanBackend::alloc_bytes_handle \
7801                     / upload_bytes_handle (not the legacy alloc_bytes / \
7802                     upload_bytes which leave VulkanStorageBytes::backend = None)."
7803                        .to_string(),
7804                )
7805                .bt()
7806            })?;
7807            if let Some(native) = fuel_vulkan_backend::contiguize_vulkan(v, layout, dtype_size)? {
7808                return Ok(Arc::new(RwLock::new(Storage::new(
7809                    fuel_memory::BackendStorage::Vulkan(native),
7810                    dtype,
7811                ))));
7812            }
7813            let _t = crate::compiled::op_profile::PhaseTimer::start(
7814                "auto_contiguize.vulkan_host_roundtrip",
7815            );
7816            let host_bytes = backend.download_bytes(v)?;
7817            let host_cpu = fuel_cpu_backend::byte_storage::CpuStorageBytes::from_bytes(&host_bytes);
7818            let contig_cpu =
7819                fuel_cpu_backend::byte_kernels::contiguize_cpu(&host_cpu, layout, dtype_size)?;
7820            let host_contig_bytes = contig_cpu.bytes().to_vec();
7821            let vk_bytes = backend.upload_bytes_handle(&host_contig_bytes)?;
7822            Storage::new(fuel_memory::BackendStorage::Vulkan(vk_bytes), dtype)
7823        }
7824        #[allow(unreachable_patterns)]
7825        _ => {
7826            return Err(Error::Msg(
7827                "auto_contiguize: backend not wired (CPU + CUDA + Vulkan are \
7828                 wired today; Metal extends this match when its byte-storage \
7829                 substrate lands)"
7830                    .to_string(),
7831            )
7832            .bt());
7833        }
7834    };
7835    Ok(Arc::new(RwLock::new(new_storage)))
7836}
7837
7838/// Write-into sibling of [`auto_contiguize`] (CapturedRun executor
7839/// build-out, 4b-γ): materializes a contiguous copy of `arc` at `layout`
7840/// INTO `dest`'s EXISTING buffer instead of allocating a fresh one — the
7841/// path `WorkItemKind::ContiguizeOf`'s Reuse-mode branch needs (device
7842/// allocation is illegal inside a capture scope). `dest` must already be
7843/// sized to the contiguized output's byte count — true by construction,
7844/// since the persistent map only ever holds a buffer THIS SAME code path
7845/// (the warm-run `auto_contiguize` allocation) sized.
7846///
7847/// CUDA-only today: `PersistentOutputs::reuse` (Reuse mode) is only ever
7848/// constructed inside [`PipelinedExecutor::capture_decode`], which is
7849/// `#[cfg(feature = "cuda")]`-gated and validates every compute node
7850/// targets `Cuda` — a CPU or Vulkan storage can never actually reach this
7851/// function in practice. Per this project's "never panic on production
7852/// paths" rule, the other backends still surface a typed gap rather than
7853/// silently mishandling it (never a crash).
7854#[cfg_attr(not(feature = "cuda"), allow(unused_variables))]
7855fn contiguize_into(
7856    dest: &Arc<RwLock<Storage>>,
7857    arc: &Arc<RwLock<Storage>>,
7858    layout: &Layout,
7859) -> Result<()> {
7860    let in_guard = arc
7861        .read()
7862        .map_err(|_| poisoned("input storage lock during contiguize_into"))?;
7863    match &in_guard.inner {
7864        #[cfg(feature = "cuda")]
7865        fuel_memory::BackendStorage::Cuda(src_cuda) => {
7866            let dtype_size = in_guard.dtype.size_in_bytes();
7867            let mut dest_guard = dest
7868                .write()
7869                .map_err(|_| poisoned("dest storage lock during contiguize_into"))?;
7870            let dest_cuda = match &mut dest_guard.inner {
7871                fuel_memory::BackendStorage::Cuda(d) => d,
7872                other => {
7873                    return Err(Error::Msg(format!(
7874                        "contiguize_into: dest is BackendStorage::{:?}, not Cuda",
7875                        other.backend_id(),
7876                    ))
7877                    .bt());
7878                }
7879            };
7880            fuel_cuda_backend::baracuda::contiguize::contiguize_into(
7881                src_cuda, layout, dest_cuda, dtype_size,
7882            )
7883        }
7884        #[allow(unreachable_patterns)]
7885        _ => Err(Error::Msg(
7886            "contiguize_into: only CUDA is wired (PersistentOutputs::reuse / \
7887             capture_decode is CUDA-only today — no CPU/Vulkan consumer exists \
7888             yet; extend this match if one appears)"
7889                .to_string(),
7890        )
7891        .bt()),
7892    }
7893}
7894
7895#[cfg(test)]
7896mod backend_neutral_tests {
7897    use super::*;
7898
7899    #[test]
7900    fn only_deviceless_items_are_backend_neutral() {
7901        let n = NodeId(0);
7902        // Adopting an input-cache entry or aliasing a producer touches no device.
7903        assert!(is_backend_neutral(&WorkItemKind::ConstAdopt));
7904        assert!(is_backend_neutral(&WorkItemKind::ViewOf { input: n }));
7905        assert!(is_backend_neutral(&WorkItemKind::SlotView { producer: n }));
7906        // Contiguize runs on its input's backend; its own `target_backend` is a
7907        // placeholder, so it must not count as a backend switch.
7908        assert!(is_backend_neutral(&WorkItemKind::ContiguizeOf { input: n }));
7909        // Sabotage siblings: anything that runs a kernel of its own or moves bytes
7910        // across devices is NOT, so a real backend switch still arms the
7911        // chunk-boundary logic.
7912        assert!(!is_backend_neutral(&WorkItemKind::Kernel));
7913        assert!(!is_backend_neutral(&WorkItemKind::Copy {
7914            target_location: DeviceLocation::Cpu
7915        }));
7916        assert!(!is_backend_neutral(&WorkItemKind::WriteSlice {
7917            dest: n,
7918            source: n
7919        }));
7920    }
7921}
7922
7923#[cfg(test)]
7924mod tests {
7925    use super::*;
7926    use fuel_graph::Node;
7927    use fuel_ir::Shape;
7928
7929    /// Task 5 (C6): `Op::Scan` has no native kernel in Phase 1 — it is
7930    /// always lowered/re-fused before execution — so `op_to_op_kind` must
7931    /// fall through its `_ => None` wildcard for it, exactly like any other
7932    /// not-yet-wired op. Regression lock, not born-red: this is expected to
7933    /// pass immediately.
7934    #[test]
7935    fn scan_has_no_dispatch_op_kind() {
7936        use fuel_graph::{Op, ScanEmit};
7937        assert_eq!(
7938            crate::pipelined::op_to_op_kind(&Op::Scan {
7939                n_carries: 1,
7940                n_xs: 0,
7941                bound: 2,
7942                emit: ScanEmit::All,
7943                early_exit: None
7944            }),
7945            None,
7946        );
7947    }
7948
7949    /// Step E A4b open question #4 — "event only where waited", step 1.
7950    /// `build_wait_set` collects exactly the producers of `Op::Copy`/`Move`
7951    /// nodes in the order: a same-device-only node (never copied/moved) must
7952    /// be ABSENT, and the Copy's own node id must not appear either (it is
7953    /// not its own producer).
7954    #[test]
7955    fn build_wait_set_collects_only_cross_device_copy_producers() {
7956        let mut g = Graph::new();
7957        let const_id = g.push(Node {
7958            op: Op::Const,
7959            inputs: vec![],
7960            shape: Shape::from_dims(&[4]),
7961            dtype: DType::F32,
7962        });
7963        // Same-device-only consumer of const_id — never fed into a Copy/Move.
7964        let same_device_id = g.push(Node {
7965            op: Op::Contiguize,
7966            inputs: vec![const_id],
7967            shape: Shape::from_dims(&[4]),
7968            dtype: DType::F32,
7969        });
7970        // A cross-device Copy whose producer is `same_device_id`.
7971        let copy_id = g.push(Node {
7972            op: Op::Copy {
7973                target: DeviceLocation::Cuda { gpu_id: 0 },
7974            },
7975            inputs: vec![same_device_id],
7976            shape: Shape::from_dims(&[4]),
7977            dtype: DType::F32,
7978        });
7979        let order = vec![const_id, same_device_id, copy_id];
7980
7981        let set = build_wait_set(&g, &order);
7982        assert!(
7983            set.contains(&same_device_id),
7984            "the Copy's producer must be in the wait set"
7985        );
7986        assert!(
7987            !set.contains(&const_id),
7988            "a node with no Copy/Move consumer must be absent from the wait set"
7989        );
7990        assert!(
7991            !set.contains(&copy_id),
7992            "the Copy node itself is not its own producer"
7993        );
7994        assert_eq!(
7995            set.len(),
7996            1,
7997            "only the one true cross-device producer is in the set"
7998        );
7999    }
8000
8001    /// A `Move` producer is collected the same way as a `Copy` producer.
8002    #[test]
8003    fn build_wait_set_collects_move_producers_too() {
8004        let mut g = Graph::new();
8005        let const_id = g.push(Node {
8006            op: Op::Const,
8007            inputs: vec![],
8008            shape: Shape::from_dims(&[4]),
8009            dtype: DType::F32,
8010        });
8011        let move_id = g.push(Node {
8012            op: Op::Move {
8013                target: DeviceLocation::Cpu,
8014            },
8015            inputs: vec![const_id],
8016            shape: Shape::from_dims(&[4]),
8017            dtype: DType::F32,
8018        });
8019        let order = vec![const_id, move_id];
8020
8021        let set = build_wait_set(&g, &order);
8022        assert!(
8023            set.contains(&const_id),
8024            "the Move's producer must be in the wait set"
8025        );
8026        assert_eq!(set.len(), 1);
8027    }
8028
8029    /// A CPU-only order (no `Op::Copy`/`Op::Move` anywhere) yields an empty
8030    /// wait set — every node in it is eligible for elision.
8031    #[test]
8032    fn build_wait_set_is_empty_for_cpu_only_order() {
8033        let mut g = Graph::new();
8034        let const_id = g.push(Node {
8035            op: Op::Const,
8036            inputs: vec![],
8037            shape: Shape::from_dims(&[4]),
8038            dtype: DType::F32,
8039        });
8040        let contig_id = g.push(Node {
8041            op: Op::Contiguize,
8042            inputs: vec![const_id],
8043            shape: Shape::from_dims(&[4]),
8044            dtype: DType::F32,
8045        });
8046        let order = vec![const_id, contig_id];
8047
8048        let set = build_wait_set(&g, &order);
8049        assert!(
8050            set.is_empty(),
8051            "a CPU-only order (no Copy/Move) yields an empty wait set"
8052        );
8053    }
8054
8055    /// `will_be_waited`'s two arms: the conservative `None` fallback (the
8056    /// `OrderSource::Streaming` case) is always `true`; a `Some(set)` checks
8057    /// membership.
8058    #[test]
8059    fn will_be_waited_none_is_conservative_true_for_any_node() {
8060        let ws: WaitSet = None;
8061        assert!(will_be_waited(&ws, NodeId(0)));
8062        assert!(will_be_waited(&ws, NodeId(12345)));
8063    }
8064
8065    #[test]
8066    fn will_be_waited_some_checks_membership() {
8067        let mut set = HashSet::new();
8068        set.insert(NodeId(3));
8069        let ws: WaitSet = Some(set);
8070        assert!(will_be_waited(&ws, NodeId(3)), "member must be waited");
8071        assert!(!will_be_waited(&ws, NodeId(4)), "non-member must be elided");
8072    }
8073
8074    /// A4b-1 test double: a `Completion` whose `wait` flips a shared flag, so a
8075    /// test can observe whether the drain actually waited it.
8076    struct FlagCompletion(std::sync::Arc<std::sync::atomic::AtomicUsize>);
8077    impl crate::compiled::Completion for FlagCompletion {
8078        fn wait(self: Box<Self>) -> Result<()> {
8079            self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
8080            Ok(())
8081        }
8082    }
8083
8084    /// A4b-1: `store_handle` keeps only `Pending` handles (so the post-drain
8085    /// empty-map assert is meaningful and the drain is O(pending)), and
8086    /// `drain_handles` waits each pending handle exactly once then empties the map.
8087    #[test]
8088    fn handle_map_stores_pending_and_drains_once() {
8089        use std::sync::Arc as StdArc;
8090        use std::sync::atomic::{AtomicUsize, Ordering};
8091
8092        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
8093
8094        // Ready handles are not stored.
8095        store_handle(&mut handles, NodeId(1), CompletionHandle::Ready);
8096        assert!(handles.is_empty(), "Ready handles must not be stored");
8097
8098        // Two pending handles are stored and each waited once on drain.
8099        let waited = StdArc::new(AtomicUsize::new(0));
8100        store_handle(
8101            &mut handles,
8102            NodeId(2),
8103            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8104        );
8105        store_handle(
8106            &mut handles,
8107            NodeId(3),
8108            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8109        );
8110        assert_eq!(handles.len(), 2);
8111
8112        drain_handles(&mut handles).expect("drain");
8113        assert_eq!(
8114            waited.load(Ordering::SeqCst),
8115            2,
8116            "each pending handle waited once"
8117        );
8118        assert!(handles.is_empty(), "map empty after drain");
8119    }
8120
8121    /// A4b-1: re-keying a NodeId with a new Pending handle waits the prior one
8122    /// (no leaked async work), and storing `Ready` over a prior Pending also
8123    /// waits it. Defensive — NodeIds are unique per realize in practice.
8124    #[test]
8125    fn handle_map_rekey_waits_previous() {
8126        use std::sync::Arc as StdArc;
8127        use std::sync::atomic::{AtomicUsize, Ordering};
8128
8129        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
8130        let waited = StdArc::new(AtomicUsize::new(0));
8131
8132        store_handle(
8133            &mut handles,
8134            NodeId(7),
8135            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8136        );
8137        // Re-key with another Pending → prior is waited.
8138        store_handle(
8139            &mut handles,
8140            NodeId(7),
8141            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8142        );
8143        assert_eq!(
8144            waited.load(Ordering::SeqCst),
8145            1,
8146            "rekey waited the prior pending"
8147        );
8148
8149        // Store Ready over the live Pending → it is waited too.
8150        store_handle(&mut handles, NodeId(7), CompletionHandle::Ready);
8151        assert_eq!(
8152            waited.load(Ordering::SeqCst),
8153            2,
8154            "Ready-over-Pending waited it"
8155        );
8156        assert!(handles.is_empty());
8157
8158        drain_handles(&mut handles).expect("drain empty");
8159    }
8160
8161    /// A4b-3: `wait_producer_handle` waits the named producer's handle EXACTLY
8162    /// once and removes it from the map (the finer cross-device source-drain
8163    /// consumes the producer's completion before the Copy reads its buffer), and
8164    /// is a no-op for an absent producer (CPU / Vulkan-`Ready` source, or an
8165    /// already-consumed handle). The realize-end drain then waits only what
8166    /// remains — no double-wait.
8167    #[test]
8168    fn wait_producer_handle_consumes_named_handle_once() {
8169        use std::sync::Arc as StdArc;
8170        use std::sync::atomic::{AtomicUsize, Ordering};
8171
8172        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
8173        let waited = StdArc::new(AtomicUsize::new(0));
8174
8175        // Two producers in flight; the Copy's source is NodeId(2).
8176        store_handle(
8177            &mut handles,
8178            NodeId(2),
8179            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8180        );
8181        store_handle(
8182            &mut handles,
8183            NodeId(5),
8184            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8185        );
8186
8187        // Absent producer → no-op (a CPU/Vulkan-Ready source has no handle).
8188        wait_producer_handle(&mut handles, NodeId(99)).expect("absent is no-op");
8189        assert_eq!(
8190            waited.load(Ordering::SeqCst),
8191            0,
8192            "absent producer waited nothing"
8193        );
8194        assert_eq!(handles.len(), 2);
8195
8196        // The cross-device copy's source: waited once, removed from the map.
8197        wait_producer_handle(&mut handles, NodeId(2)).expect("wait source");
8198        assert_eq!(
8199            waited.load(Ordering::SeqCst),
8200            1,
8201            "source producer waited once"
8202        );
8203        assert!(!handles.contains_key(&NodeId(2)), "source handle consumed");
8204        assert!(
8205            handles.contains_key(&NodeId(5)),
8206            "unrelated handle untouched"
8207        );
8208
8209        // Re-waiting the (now absent) source is a no-op — no double-wait.
8210        wait_producer_handle(&mut handles, NodeId(2)).expect("re-wait is no-op");
8211        assert_eq!(waited.load(Ordering::SeqCst), 1, "no double-wait");
8212
8213        // Realize-end drain waits only the remaining unrelated producer.
8214        drain_handles(&mut handles).expect("drain");
8215        assert_eq!(
8216            waited.load(Ordering::SeqCst),
8217            2,
8218            "drain waited the remaining one"
8219        );
8220        assert!(handles.is_empty());
8221    }
8222
8223    /// Op::Contiguize on a contiguous-already input is zero-copy:
8224    /// the executor adopts the input Storage Arc unchanged.
8225    #[test]
8226    fn op_contiguize_zero_copy_on_contiguous_input() {
8227        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
8228
8229        let graph = Arc::new(RwLock::new(Graph::new()));
8230        let (const_id, contig_id) = {
8231            let mut g = graph.write().unwrap();
8232            let const_id = g.push(Node {
8233                op: Op::Const,
8234                inputs: vec![],
8235                shape: Shape::from_dims(&[2, 2]),
8236                dtype: DType::F32,
8237            });
8238            let contig_id = g.push(Node {
8239                op: Op::Contiguize,
8240                inputs: vec![const_id],
8241                shape: Shape::from_dims(&[2, 2]),
8242                dtype: DType::F32,
8243            });
8244            // No need to set target_backend on Contiguize — the
8245            // executor inherits or defaults to CPU.
8246            (const_id, contig_id)
8247        };
8248
8249        let mut inputs = StorageCache::new();
8250        let input_arc = Arc::new(RwLock::new(storage));
8251        let input_arc_for_compare = Arc::clone(&input_arc);
8252        inputs.insert(const_id, input_arc);
8253
8254        let (result_arc, _) =
8255            PipelinedExecutor::realize(graph, contig_id, inputs).expect("realize");
8256
8257        // Same Arc → zero-copy adoption. Compare by raw pointer.
8258        assert!(
8259            Arc::ptr_eq(&result_arc, &input_arc_for_compare),
8260            "Op::Contiguize on contiguous input must adopt the input Arc (zero copy)",
8261        );
8262    }
8263
8264    /// Op::Contiguize on a strided input (here: a transposed view)
8265    /// materializes a fresh contiguous Storage. The output bytes
8266    /// reflect the strided view's logical content, not the input
8267    /// storage's underlying memory order.
8268    #[test]
8269    fn op_contiguize_materializes_on_strided_input() {
8270        // 2x3 row-major: [[1,2,3],[4,5,6]] → transpose → 3x2:
8271        // [[1,4],[2,5],[3,6]]. The transposed view shares the
8272        // original buffer; Op::Contiguize on the transpose
8273        // materializes contiguous bytes matching the transposed
8274        // logical order.
8275        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
8276
8277        let graph = Arc::new(RwLock::new(Graph::new()));
8278        let (const_id, _transpose_id, contig_id) = {
8279            let mut g = graph.write().unwrap();
8280            let const_id = g.push(Node {
8281                op: Op::Const,
8282                inputs: vec![],
8283                shape: Shape::from_dims(&[2, 3]),
8284                dtype: DType::F32,
8285            });
8286            let transpose_id = g.push(Node {
8287                op: Op::Transpose,
8288                inputs: vec![const_id],
8289                shape: Shape::from_dims(&[3, 2]),
8290                dtype: DType::F32,
8291            });
8292            let contig_id = g.push(Node {
8293                op: Op::Contiguize,
8294                inputs: vec![transpose_id],
8295                shape: Shape::from_dims(&[3, 2]),
8296                dtype: DType::F32,
8297            });
8298            (const_id, transpose_id, contig_id)
8299        };
8300
8301        let mut inputs = StorageCache::new();
8302        inputs.insert(const_id, Arc::new(RwLock::new(storage)));
8303
8304        let (result_arc, _) =
8305            PipelinedExecutor::realize(graph, contig_id, inputs).expect("realize");
8306
8307        let guard = result_arc.read().unwrap();
8308        let cpu = if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
8309            c
8310        } else {
8311            panic!("expected Cpu storage");
8312        };
8313        let typed: &[f32] = cpu.as_slice().expect("f32 cast");
8314        // Transposed logical order: [1,4,2,5,3,6].
8315        assert_eq!(
8316            typed,
8317            &[1.0, 4.0, 2.0, 5.0, 3.0, 6.0],
8318            "contiguized transpose must reflect logical (transposed) byte order",
8319        );
8320    }
8321
8322    /// E2E: 3-node graph (Const + Const + Add), pre-seeded inputs,
8323    /// realized through the compiler+executor thread pair, returns
8324    /// expected sum bytes.
8325    #[test]
8326    fn pipelined_realize_const_const_add() {
8327        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
8328        let rhs_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
8329
8330        let graph = Arc::new(RwLock::new(Graph::new()));
8331        let (lhs_id, rhs_id, add_id) = {
8332            let mut g = graph.write().unwrap();
8333            let lhs_id = g.push(Node {
8334                op: Op::Const,
8335                inputs: vec![],
8336                shape: Shape::from_dims(&[3]),
8337                dtype: DType::F32,
8338            });
8339            let rhs_id = g.push(Node {
8340                op: Op::Const,
8341                inputs: vec![],
8342                shape: Shape::from_dims(&[3]),
8343                dtype: DType::F32,
8344            });
8345            let add_id = g.push(Node {
8346                op: Op::Add,
8347                inputs: vec![lhs_id, rhs_id],
8348                shape: Shape::from_dims(&[3]),
8349                dtype: DType::F32,
8350            });
8351            g.set_target_backend(add_id, BackendId::Cpu);
8352            (lhs_id, rhs_id, add_id)
8353        };
8354
8355        let mut inputs = StorageCache::new();
8356        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
8357        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
8358
8359        let (result_arc, _result_layout) =
8360            PipelinedExecutor::realize(graph, add_id, inputs).expect("realize");
8361
8362        let guard = result_arc.read().unwrap();
8363        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
8364            let typed: &[f32] = c.as_slice().expect("f32 cast");
8365            assert_eq!(typed, &[11.0, 22.0, 33.0]);
8366        } else {
8367            panic!("expected CPU output");
8368        }
8369    }
8370
8371    /// CapturedRun executor build-out (Increment 1): capture a 2-op binary
8372    /// chain `z = (a + b) * c` THROUGH the pipelined executor's
8373    /// persistent-output mode, then prove the three capture guarantees on a
8374    /// live GPU:
8375    ///   1. after capture, the fixed output buffer holds the warm-run result
8376    ///      (capture RECORDS launches, it does not execute them);
8377    ///   2. `replay()` recomputes bit-exactly into the SAME fixed buffer;
8378    ///   3. replay reads the FIXED input addresses — overwriting an input
8379    ///      buffer in place and replaying yields the new result, matching an
8380    ///      independent uncaptured `realize`. This is the whole mechanism:
8381    ///      the write-into binary wrapper + the executor's reuse mode +
8382    ///      `capture_run` compose into a replayable decode-step graph.
8383    #[test]
8384    #[ignore = "requires a live CUDA device"]
8385    #[cfg(feature = "cuda")]
8386    fn capture_decode_binary_chain_replays_bit_exact_cuda() {
8387        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8388        use fuel_ir::Shape;
8389        use fuel_memory::BackendStorage;
8390
8391        let Ok(dev) = CudaDevice::new(0) else {
8392            return fuel_test_support::hardware::skip(
8393                fuel_test_support::hardware::Hardware::Cuda,
8394                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
8395            );
8396        };
8397
8398        // z = (a + b) * c, shape [4]. `y = a + b` is a persistent
8399        // INTERMEDIATE; `z` is the persistent target — both fixed-address.
8400        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId, NodeId, NodeId) {
8401            let graph = Arc::new(RwLock::new(Graph::new()));
8402            let (a, b, c, z) = {
8403                let mut g = graph.write().unwrap();
8404                let a = g.push(Node {
8405                    op: Op::Const,
8406                    inputs: vec![],
8407                    shape: Shape::from_dims(&[4]),
8408                    dtype: DType::F32,
8409                });
8410                let b = g.push(Node {
8411                    op: Op::Const,
8412                    inputs: vec![],
8413                    shape: Shape::from_dims(&[4]),
8414                    dtype: DType::F32,
8415                });
8416                let c = g.push(Node {
8417                    op: Op::Const,
8418                    inputs: vec![],
8419                    shape: Shape::from_dims(&[4]),
8420                    dtype: DType::F32,
8421                });
8422                let y = g.push(Node {
8423                    op: Op::Add,
8424                    inputs: vec![a, b],
8425                    shape: Shape::from_dims(&[4]),
8426                    dtype: DType::F32,
8427                });
8428                let z = g.push(Node {
8429                    op: Op::Mul,
8430                    inputs: vec![y, c],
8431                    shape: Shape::from_dims(&[4]),
8432                    dtype: DType::F32,
8433                });
8434                g.set_target_backend(y, BackendId::Cuda);
8435                g.set_target_backend(z, BackendId::Cuda);
8436                (a, b, c, z)
8437            };
8438            (graph, a, b, c, z)
8439        };
8440
8441        let up = |v: &[f32]| -> Arc<RwLock<Storage>> {
8442            let bytes: &[u8] = bytemuck::cast_slice(v);
8443            let cb = CudaStorageBytes::from_cpu_bytes(&dev, bytes).expect("h2d");
8444            Arc::new(RwLock::new(Storage::new(
8445                BackendStorage::Cuda(cb),
8446                DType::F32,
8447            )))
8448        };
8449        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8450            let g = arc.read().unwrap();
8451            let BackendStorage::Cuda(c) = &g.inner else {
8452                panic!("not cuda")
8453            };
8454            let host = c.to_cpu_bytes().expect("d2h");
8455            bytemuck::cast_slice(&host).to_vec()
8456        };
8457
8458        let a_data = [1.0_f32, 2.0, 3.0, 4.0];
8459        let b_data = [10.0_f32, 20.0, 30.0, 40.0];
8460        let c_data = [2.0_f32, 2.0, 2.0, 2.0];
8461        let expect0 = [22.0_f32, 44.0, 66.0, 88.0]; // (a+b)*c
8462
8463        // Fixed input Arcs (shared into capture; overwritten in place later).
8464        let a_arc = up(&a_data);
8465        let b_arc = up(&b_data);
8466        let c_arc = up(&c_data);
8467
8468        let (graph, a, b, c, z) = build();
8469        let mut inputs = StorageCache::new();
8470        inputs.insert(a, a_arc.clone());
8471        inputs.insert(b, b_arc.clone());
8472        inputs.insert(c, c_arc.clone());
8473
8474        let captured =
8475            PipelinedExecutor::capture_decode(Arc::clone(&graph), z, inputs, SymEnv::default())
8476                .expect("capture_decode");
8477
8478        // (1) warm-run result sits in the captured output buffer.
8479        assert_eq!(
8480            read(&captured.output),
8481            &expect0,
8482            "warm-run result after capture"
8483        );
8484
8485        // (2) replay with the same inputs recomputes bit-exactly.
8486        captured.run.replay(&dev).expect("replay");
8487        dev.synchronize().expect("sync");
8488        assert_eq!(read(&captured.output), &expect0, "replay reproduces result");
8489
8490        // (3) overwrite input `a` IN PLACE (same device address), replay ->
8491        //     the new result flows from the FIXED input address. Compare to
8492        //     an independent uncaptured realize with the same new input.
8493        let a2 = [100.0_f32, 200.0, 300.0, 400.0];
8494        {
8495            let g = a_arc.read().unwrap();
8496            let BackendStorage::Cuda(c) = &g.inner else {
8497                panic!("a not cuda")
8498            };
8499            c.write_from_host(bytemuck::cast_slice(&a2))
8500                .expect("in-place H2D");
8501        }
8502        captured.run.replay(&dev).expect("replay 2");
8503        dev.synchronize().expect("sync 2");
8504        let got = read(&captured.output);
8505
8506        let (graph_ref, ar, br, cr, zr) = build();
8507        let mut inputs_ref = StorageCache::new();
8508        inputs_ref.insert(ar, up(&a2));
8509        inputs_ref.insert(br, up(&b_data));
8510        inputs_ref.insert(cr, up(&c_data));
8511        let (ref_arc, _) =
8512            PipelinedExecutor::realize(graph_ref, zr, inputs_ref).expect("ref realize");
8513        let expect1 = read(&ref_arc); // (a2+b)*c = [220,440,660,880]
8514        assert_eq!(
8515            got, expect1,
8516            "replay after in-place input update matches uncaptured realize"
8517        );
8518        assert_eq!(expect1, vec![220.0, 440.0, 660.0, 880.0]);
8519    }
8520
8521    /// CapturedRun executor build-out (Increment 3): capture a DECODE-SHAPED
8522    /// graph — the full dense op-set composing in one capture — and prove it
8523    /// replays bit-exactly against an independent uncaptured realize.
8524    ///
8525    /// Graph (an FFN block + norms, batch=seq=1 like real decode):
8526    ///   n1 = rms_norm(x);  u = n1 · w_up;  s = silu(u);
8527    /// cuBLAS `gemm_dense` matmul IS graph-capturable (regression for the
8528    /// dangling-input bug that once masqueraded as "cuBLAS not replay-safe").
8529    /// Captures `y = a·w` where the caller does NOT retain `w`, FORCES the
8530    /// freed-`w` slot to be reused by garbage buffers, then replays 50× — all
8531    /// must equal the uncaptured realize. Passes iff `capture_decode` retains
8532    /// its input buffers (`CapturedDecode::retained_inputs`).
8533    #[test]
8534    #[ignore = "requires a live CUDA device"]
8535    #[cfg(feature = "cuda")]
8536    fn capture_decode_matmul_replays_bit_exact_cuda() {
8537        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8538        use fuel_ir::Shape;
8539        use fuel_memory::BackendStorage;
8540        let Ok(dev) = CudaDevice::new(0) else { return };
8541        const H: usize = 4;
8542        const F: usize = 8;
8543        let a_data: Vec<f32> = (0..H).map(|i| 0.5 + i as f32).collect();
8544        let w_data: Vec<f32> = (0..H * F).map(|i| 0.01 * (i as f32 + 1.0)).collect();
8545        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId, NodeId) {
8546            let graph = Arc::new(RwLock::new(Graph::new()));
8547            let (a, w, y) = {
8548                let mut g = graph.write().unwrap();
8549                let a = g.push(Node {
8550                    op: Op::Const,
8551                    inputs: vec![],
8552                    shape: Shape::from_dims(&[1, H]),
8553                    dtype: DType::F32,
8554                });
8555                let w = g.push(Node {
8556                    op: Op::Const,
8557                    inputs: vec![],
8558                    shape: Shape::from_dims(&[H, F]),
8559                    dtype: DType::F32,
8560                });
8561                let y = g.push(Node {
8562                    op: Op::MatMul,
8563                    inputs: vec![a, w],
8564                    shape: Shape::from_dims(&[1, F]),
8565                    dtype: DType::F32,
8566                });
8567                g.set_target_backend(y, BackendId::Cuda);
8568                (a, w, y)
8569            };
8570            (graph, a, w, y)
8571        };
8572        let up = |v: &[f32]| {
8573            let b: Vec<u8> = v.iter().flat_map(|f| f.to_le_bytes()).collect();
8574            Arc::new(RwLock::new(Storage::new(
8575                BackendStorage::Cuda(CudaStorageBytes::from_cpu_bytes(&dev, &b).unwrap()),
8576                DType::F32,
8577            )))
8578        };
8579        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8580            let g = arc.read().unwrap();
8581            let BackendStorage::Cuda(c) = &g.inner else {
8582                panic!("not cuda")
8583            };
8584            c.to_cpu_bytes()
8585                .unwrap()
8586                .chunks_exact(4)
8587                .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
8588                .collect()
8589        };
8590        // Reference (uncaptured).
8591        let (gr, ar, wr, yr) = build();
8592        let mut insr = StorageCache::new();
8593        insr.insert(ar, up(&a_data));
8594        insr.insert(wr, up(&w_data));
8595        let (refarc, _) = PipelinedExecutor::realize(gr, yr, insr).unwrap();
8596        let expect = read(&refarc);
8597        // Capture (a + w NOT retained by caller).
8598        let (graph, a, w, y) = build();
8599        let mut inputs = StorageCache::new();
8600        inputs.insert(a, up(&a_data));
8601        inputs.insert(w, up(&w_data));
8602        let captured =
8603            PipelinedExecutor::capture_decode(Arc::clone(&graph), y, inputs, SymEnv::default())
8604                .expect("capture");
8605        assert_eq!(read(&captured.output), expect, "warm result after capture");
8606        // FORCE freed-memory reuse: same-size (H*F) garbage buffers. If `w`
8607        // were dangling, replay would read 999.0s.
8608        let mut squatters = Vec::new();
8609        for _ in 0..8 {
8610            let g: Vec<u8> = (0..H * F).flat_map(|_| 999.0f32.to_le_bytes()).collect();
8611            squatters.push(CudaStorageBytes::from_cpu_bytes(&dev, &g).unwrap());
8612        }
8613        dev.synchronize().unwrap();
8614        let mut bad = 0usize;
8615        for _ in 0..50 {
8616            captured.run.replay(&dev).unwrap();
8617            dev.synchronize().unwrap();
8618            if read(&captured.output) != expect {
8619                bad += 1;
8620            }
8621        }
8622        assert_eq!(
8623            bad, 0,
8624            "cuBLAS matmul capture replays bit-exact ({bad}/50 wrong)"
8625        );
8626    }
8627
8628    /// `Op::MulScalar` / `OpKind::Affine` (the `1/√d` attention scale) is
8629    /// capture-safe (write-into variant + forced-reuse regression).
8630    #[test]
8631    #[ignore = "requires a live CUDA device"]
8632    #[cfg(feature = "cuda")]
8633    fn capture_decode_affine_replays_bit_exact_cuda() {
8634        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8635        use fuel_ir::Shape;
8636        use fuel_memory::BackendStorage;
8637        let Ok(dev) = CudaDevice::new(0) else { return };
8638        const N: usize = 6;
8639        let x_data: Vec<f32> = (0..N).map(|i| 1.0 + i as f32).collect();
8640        let expect: Vec<f32> = x_data.iter().map(|v| v * 0.5).collect();
8641        let graph = Arc::new(RwLock::new(Graph::new()));
8642        let (x, y) = {
8643            let mut g = graph.write().unwrap();
8644            let x = g.push(Node {
8645                op: Op::Const,
8646                inputs: vec![],
8647                shape: Shape::from_dims(&[1, N]),
8648                dtype: DType::F32,
8649            });
8650            let y = g.push(Node {
8651                op: Op::MulScalar(0.5),
8652                inputs: vec![x],
8653                shape: Shape::from_dims(&[1, N]),
8654                dtype: DType::F32,
8655            });
8656            g.set_target_backend(y, BackendId::Cuda);
8657            (x, y)
8658        };
8659        let up = |v: &[f32]| {
8660            let b: Vec<u8> = v.iter().flat_map(|f| f.to_le_bytes()).collect();
8661            Arc::new(RwLock::new(Storage::new(
8662                BackendStorage::Cuda(CudaStorageBytes::from_cpu_bytes(&dev, &b).unwrap()),
8663                DType::F32,
8664            )))
8665        };
8666        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8667            let g = arc.read().unwrap();
8668            let BackendStorage::Cuda(c) = &g.inner else {
8669                panic!("not cuda")
8670            };
8671            c.to_cpu_bytes()
8672                .unwrap()
8673                .chunks_exact(4)
8674                .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
8675                .collect()
8676        };
8677        let mut inputs = StorageCache::new();
8678        inputs.insert(x, up(&x_data));
8679        let captured =
8680            PipelinedExecutor::capture_decode(Arc::clone(&graph), y, inputs, SymEnv::default())
8681                .expect("capture");
8682        assert_eq!(read(&captured.output), expect, "warm result after capture");
8683        let mut sq = Vec::new();
8684        for _ in 0..8 {
8685            let g: Vec<u8> = (0..N).flat_map(|_| 999.0f32.to_le_bytes()).collect();
8686            sq.push(CudaStorageBytes::from_cpu_bytes(&dev, &g).unwrap());
8687        }
8688        dev.synchronize().unwrap();
8689        let mut bad = 0usize;
8690        for _ in 0..50 {
8691            captured.run.replay(&dev).unwrap();
8692            dev.synchronize().unwrap();
8693            if read(&captured.output) != expect {
8694                bad += 1;
8695            }
8696        }
8697        assert_eq!(bad, 0, "affine capture replays bit-exact ({bad}/50 wrong)");
8698    }
8699
8700    /// `index_select` (embedding lookup) IS graph-capturable (regression for
8701    /// the dangling-input bug that once looked like "element 0 dropped on
8702    /// replay"). Captures `emb = index_select(wte, tok)` with `wte` NOT
8703    /// retained by the caller, FORCES the freed-`wte` slot to be reused by
8704    /// garbage buffers, then replays 50× — all must be `[1,2,3,4]`. Passes iff
8705    /// `capture_decode` retains its input buffers.
8706    #[test]
8707    #[ignore = "requires a live CUDA device"]
8708    #[cfg(feature = "cuda")]
8709    fn capture_decode_index_select_replays_bit_exact_cuda() {
8710        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8711        use fuel_ir::Shape;
8712        use fuel_memory::BackendStorage;
8713        let Ok(dev) = CudaDevice::new(0) else { return };
8714        const V: usize = 3;
8715        const H: usize = 4;
8716        let wte_data: Vec<f32> = (0..V)
8717            .flat_map(|v| (0..H).map(move |c| 1.0 + 10.0 * v as f32 + c as f32))
8718            .collect();
8719        let graph = Arc::new(RwLock::new(Graph::new()));
8720        let (tok, wte, emb) = {
8721            let mut g = graph.write().unwrap();
8722            let tok = g.push(Node {
8723                op: Op::Const,
8724                inputs: vec![],
8725                shape: Shape::from_dims(&[1]),
8726                dtype: DType::U32,
8727            });
8728            let wte = g.push(Node {
8729                op: Op::Const,
8730                inputs: vec![],
8731                shape: Shape::from_dims(&[V, H]),
8732                dtype: DType::F32,
8733            });
8734            let emb = g.push(Node {
8735                op: Op::IndexSelect { dim: 0 },
8736                inputs: vec![wte, tok],
8737                shape: Shape::from_dims(&[1, H]),
8738                dtype: DType::F32,
8739            });
8740            g.set_target_backend(emb, BackendId::Cuda);
8741            (tok, wte, emb)
8742        };
8743        let up_f32 = |v: &[f32]| {
8744            let b: Vec<u8> = v.iter().flat_map(|f| f.to_le_bytes()).collect();
8745            Arc::new(RwLock::new(Storage::new(
8746                BackendStorage::Cuda(CudaStorageBytes::from_cpu_bytes(&dev, &b).unwrap()),
8747                DType::F32,
8748            )))
8749        };
8750        let up_u32 = |v: &[u32]| {
8751            let b: Vec<u8> = v.iter().flat_map(|x| x.to_le_bytes()).collect();
8752            Arc::new(RwLock::new(Storage::new(
8753                BackendStorage::Cuda(CudaStorageBytes::from_cpu_bytes(&dev, &b).unwrap()),
8754                DType::U32,
8755            )))
8756        };
8757        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8758            let g = arc.read().unwrap();
8759            let BackendStorage::Cuda(c) = &g.inner else {
8760                panic!("not cuda")
8761            };
8762            c.to_cpu_bytes()
8763                .unwrap()
8764                .chunks_exact(4)
8765                .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
8766                .collect()
8767        };
8768        let tok_arc = up_u32(&[0]);
8769        let mut inputs = StorageCache::new();
8770        inputs.insert(tok, tok_arc.clone());
8771        inputs.insert(wte, up_f32(&wte_data));
8772        let captured =
8773            PipelinedExecutor::capture_decode(Arc::clone(&graph), emb, inputs, SymEnv::default())
8774                .expect("capture");
8775        assert_eq!(
8776            read(&captured.output),
8777            vec![1.0, 2.0, 3.0, 4.0],
8778            "warm result after capture"
8779        );
8780        // FORCE freed-memory reuse: same-size (V*H) garbage buffers reclaim
8781        // `wte`'s slot if it were dangling — replay would then read 999.0s.
8782        let mut squatters = Vec::new();
8783        for _ in 0..8 {
8784            let g: Vec<u8> = (0..V * H).flat_map(|_| 999.0f32.to_le_bytes()).collect();
8785            squatters.push(CudaStorageBytes::from_cpu_bytes(&dev, &g).unwrap());
8786        }
8787        dev.synchronize().unwrap();
8788        let mut bad = 0usize;
8789        for _ in 0..50 {
8790            captured.run.replay(&dev).unwrap();
8791            dev.synchronize().unwrap();
8792            if read(&captured.output) != vec![1.0, 2.0, 3.0, 4.0] {
8793                bad += 1;
8794            }
8795        }
8796        assert_eq!(
8797            bad, 0,
8798            "index_select capture replays bit-exact ({bad}/50 wrong)"
8799        );
8800    }
8801
8802    ///   n1 = rms_norm(x);  s = silu(n1);  p = softmax(s);
8803    ///   r  = p + x;  n2 = rms_norm(r);  y = n2 + x
8804    /// Exercises rms_norm (×2 — proves the per-device RMS workspace is reused
8805    /// across sequential norms inside ONE captured graph), silu + softmax
8806    /// (write-into), and residual adds through the persistent-output capture
8807    /// path. Verified across two input value-sets (robust, not luck).
8808    ///
8809    /// Deliberately EXCLUDES matmul (cuBLAS not graph-replay-safe) and
8810    /// index_select (its host-side shape/stride arrays dangle under capture —
8811    /// proven to mis-replay). Both are surfaced `capture_decode` gaps, not
8812    /// silent mis-replays. See `op_kind_is_capture_writeinto`.
8813    #[test]
8814    #[ignore = "requires a live CUDA device"]
8815    #[cfg(feature = "cuda")]
8816    fn capture_decode_norm_silu_softmax_replays_bit_exact_cuda() {
8817        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8818        use fuel_graph::registry::{FusedOpParams, FusedOps};
8819        use fuel_ir::Shape;
8820        use fuel_memory::BackendStorage;
8821
8822        let Ok(dev) = CudaDevice::new(0) else {
8823            return fuel_test_support::hardware::skip(
8824                fuel_test_support::hardware::Hardware::Cuda,
8825                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
8826            );
8827        };
8828        const H: usize = 6;
8829        let eps = 1e-5f64;
8830
8831        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId) {
8832            let graph = Arc::new(RwLock::new(Graph::new()));
8833            let (x, y) = {
8834                let mut g = graph.write().unwrap();
8835                let mk = |g: &mut Graph, op: Op, ins: Vec<NodeId>, dims: &[usize]| {
8836                    g.push(Node {
8837                        op,
8838                        inputs: ins,
8839                        shape: Shape::from_dims(dims),
8840                        dtype: DType::F32,
8841                    })
8842                };
8843                let rms = || {
8844                    Op::Fused(
8845                        FusedOps::RMS_NORM_LAST_DIM,
8846                        FusedOpParams::RmsNormLastDim { eps },
8847                    )
8848                };
8849                let sm = || Op::Fused(FusedOps::SOFTMAX_LAST_DIM, FusedOpParams::SoftmaxLastDim);
8850                let x = mk(&mut g, Op::Const, vec![], &[1, H]);
8851                let n1 = mk(&mut g, rms(), vec![x], &[1, H]);
8852                let s = mk(&mut g, Op::Silu, vec![n1], &[1, H]);
8853                let p = mk(&mut g, sm(), vec![s], &[1, H]);
8854                let r = mk(&mut g, Op::Add, vec![p, x], &[1, H]);
8855                let n2 = mk(&mut g, rms(), vec![r], &[1, H]);
8856                let y = mk(&mut g, Op::Add, vec![n2, x], &[1, H]);
8857                for id in [n1, s, p, r, n2, y] {
8858                    g.set_target_backend(id, BackendId::Cuda);
8859                }
8860                (x, y)
8861            };
8862            (graph, x, y)
8863        };
8864
8865        let up = |v: &[f32]| -> Arc<RwLock<Storage>> {
8866            let cb = CudaStorageBytes::from_cpu_bytes(&dev, bytemuck::cast_slice(v)).expect("h2d");
8867            Arc::new(RwLock::new(Storage::new(
8868                BackendStorage::Cuda(cb),
8869                DType::F32,
8870            )))
8871        };
8872        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8873            let g = arc.read().unwrap();
8874            let BackendStorage::Cuda(c) = &g.inner else {
8875                panic!("not cuda")
8876            };
8877            bytemuck::cast_slice(&c.to_cpu_bytes().expect("d2h")).to_vec()
8878        };
8879
8880        let x_data: Vec<f32> = (0..H).map(|c| 0.1 * (c as f32 + 1.0)).collect();
8881        let x_arc = up(&x_data);
8882        let (graph, x, y) = build();
8883        let mut inputs = StorageCache::new();
8884        inputs.insert(x, x_arc.clone());
8885
8886        let captured =
8887            PipelinedExecutor::capture_decode(Arc::clone(&graph), y, inputs, SymEnv::default())
8888                .expect("capture_decode norm/silu/softmax");
8889
8890        let realize_ref = |xv: &[f32]| -> Vec<f32> {
8891            let (g, xr, yr) = build();
8892            let mut ins = StorageCache::new();
8893            ins.insert(xr, up(xv));
8894            let (arc, _) = PipelinedExecutor::realize(g, yr, ins).expect("ref realize");
8895            read(&arc)
8896        };
8897        let expect0 = realize_ref(&x_data);
8898
8899        // (1) after capture the output holds the warm result.
8900        assert_eq!(read(&captured.output), expect0, "warm result after capture");
8901        // (2) replay reproduces bit-exactly (incl. RMS workspace reuse on replay).
8902        captured.run.replay(&dev).expect("replay");
8903        dev.synchronize().expect("sync");
8904        assert_eq!(read(&captured.output), expect0, "replay reproduces result");
8905
8906        // (3) overwrite x in place, replay -> matches uncaptured realize (a
8907        //     DIFFERENT value-set — so the chain is robust, not input-lucky).
8908        let x2: Vec<f32> = (0..H).map(|c| 0.3 * (c as f32 + 1.0)).collect();
8909        {
8910            let g = x_arc.read().unwrap();
8911            let BackendStorage::Cuda(c) = &g.inner else {
8912                panic!("x not cuda")
8913            };
8914            c.write_from_host(bytemuck::cast_slice(&x2))
8915                .expect("in-place H2D");
8916        }
8917        captured.run.replay(&dev).expect("replay 2");
8918        dev.synchronize().expect("sync 2");
8919        assert_eq!(
8920            read(&captured.output),
8921            realize_ref(&x2),
8922            "replay after x update matches realize"
8923        );
8924    }
8925
8926    /// CapturedRun executor build-out (Increment 4b-γ): make `ContiguizeOf`
8927    /// (a non-contiguous reshape after `Permute` — the real decode graph's
8928    /// attention-merge reshape shape) AND a 2-input `Op::Concat` (the shape
8929    /// RoPE's CUDA decomposition emits for its rotate-half) BOTH
8930    /// capture-safe in ONE graph, so the crux 4b-γ exists for — allocation
8931    /// of an INTERMEDIATE, non-final buffer inside a capture scope — is
8932    /// actually exercised, not just each gap in isolation.
8933    ///
8934    /// Graph: `x [2,3,4] --Permute[1,0,2]--> [3,2,4]` (non-contiguous)
8935    /// `--Reshape[3,8]--> r` (`ContiguizeOf`, MUST allocate: its input is
8936    /// non-contiguous) `--Concat(dim=1, with b [3,8])--> y [3,16]` (target).
8937    #[test]
8938    #[ignore = "requires a live CUDA device"]
8939    #[cfg(feature = "cuda")]
8940    fn capture_decode_contiguize_then_concat_replays_bit_exact_cuda() {
8941        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
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
8952        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId, NodeId) {
8953            let graph = Arc::new(RwLock::new(Graph::new()));
8954            let (x, b, y) = {
8955                let mut g = graph.write().unwrap();
8956                let x = g.push(Node {
8957                    op: Op::Const,
8958                    inputs: vec![],
8959                    shape: Shape::from_dims(&[2, 3, 4]),
8960                    dtype: DType::F32,
8961                });
8962                let p = g.push(Node {
8963                    op: Op::Permute(vec![1, 0, 2]),
8964                    inputs: vec![x],
8965                    shape: Shape::from_dims(&[3, 2, 4]),
8966                    dtype: DType::F32,
8967                });
8968                let r = g.push(Node {
8969                    op: Op::Reshape(Shape::from_dims(&[3, 8])),
8970                    inputs: vec![p],
8971                    shape: Shape::from_dims(&[3, 8]),
8972                    dtype: DType::F32,
8973                });
8974                let b = g.push(Node {
8975                    op: Op::Const,
8976                    inputs: vec![],
8977                    shape: Shape::from_dims(&[3, 8]),
8978                    dtype: DType::F32,
8979                });
8980                let y = g.push(Node {
8981                    op: Op::Concat { dim: 1 },
8982                    inputs: vec![r, b],
8983                    shape: Shape::from_dims(&[3, 16]),
8984                    dtype: DType::F32,
8985                });
8986                g.set_target_backend(p, BackendId::Cuda);
8987                g.set_target_backend(r, BackendId::Cuda);
8988                g.set_target_backend(y, BackendId::Cuda);
8989                (x, b, y)
8990            };
8991            (graph, x, b, y)
8992        };
8993
8994        let up = |v: &[f32]| -> Arc<RwLock<Storage>> {
8995            let cb = CudaStorageBytes::from_cpu_bytes(&dev, bytemuck::cast_slice(v)).expect("h2d");
8996            Arc::new(RwLock::new(Storage::new(
8997                BackendStorage::Cuda(cb),
8998                DType::F32,
8999            )))
9000        };
9001        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9002            let g = arc.read().unwrap();
9003            let BackendStorage::Cuda(c) = &g.inner else {
9004                panic!("not cuda")
9005            };
9006            bytemuck::cast_slice(&c.to_cpu_bytes().expect("d2h")).to_vec()
9007        };
9008
9009        let x_data: Vec<f32> = (0..24).map(|i| i as f32).collect();
9010        let b_data: Vec<f32> = (0..24).map(|i| 100.0 + i as f32).collect();
9011        let x_arc = up(&x_data);
9012        let (graph, x, b, y) = build();
9013        let mut inputs = StorageCache::new();
9014        inputs.insert(x, x_arc.clone());
9015        // `b` deliberately NOT retained by a local variable — forces
9016        // reliance on `capture_decode`'s own `retained_inputs`, mirroring
9017        // the matmul/index_select regression precedent.
9018        inputs.insert(b, up(&b_data));
9019
9020        let captured =
9021            PipelinedExecutor::capture_decode(Arc::clone(&graph), y, inputs, SymEnv::default())
9022                .expect("capture_decode contiguize+concat");
9023
9024        let realize_ref = |xv: &[f32], bv: &[f32]| -> Vec<f32> {
9025            let (g, xr, br, yr) = build();
9026            let mut ins = StorageCache::new();
9027            ins.insert(xr, up(xv));
9028            ins.insert(br, up(bv));
9029            let (arc, _) = PipelinedExecutor::realize(g, yr, ins).expect("ref realize");
9030            read(&arc)
9031        };
9032        let expect0 = realize_ref(&x_data, &b_data);
9033
9034        // (1) warm-run result sits in the captured output buffer (capture
9035        //     RECORDS launches, it does not execute them at capture time).
9036        assert_eq!(read(&captured.output), expect0, "warm result after capture");
9037
9038        // (2) replay TWICE with unchanged inputs — proves the fixed-address
9039        //     reuse (both the ContiguizeOf intermediate and the Concat
9040        //     output) holds across multiple replay() calls, not just one.
9041        for i in 0..2 {
9042            captured
9043                .run
9044                .replay(&dev)
9045                .unwrap_or_else(|e| panic!("replay {i}: {e:?}"));
9046            dev.synchronize().expect("sync");
9047            assert_eq!(
9048                read(&captured.output),
9049                expect0,
9050                "replay {i} reproduces result"
9051            );
9052        }
9053
9054        // (3) overwrite x in place (a DIFFERENT value-set), replay again ->
9055        //     the new result flows from the FIXED input address, through
9056        //     the fixed ContiguizeOf intermediate, into the fixed Concat
9057        //     output — matches an independent uncaptured realize.
9058        let x2: Vec<f32> = (0..24).map(|i| 1000.0 + i as f32).collect();
9059        {
9060            let g = x_arc.read().unwrap();
9061            let BackendStorage::Cuda(c) = &g.inner else {
9062                panic!("x not cuda")
9063            };
9064            c.write_from_host(bytemuck::cast_slice(&x2))
9065                .expect("in-place H2D");
9066        }
9067        captured.run.replay(&dev).expect("replay 3");
9068        dev.synchronize().expect("sync 3");
9069        assert_eq!(
9070            read(&captured.output),
9071            realize_ref(&x2, &b_data),
9072            "replay after x update matches independent uncaptured realize"
9073        );
9074    }
9075
9076    /// CapturedRun executor build-out (Increment 4b-ζ): a same-device
9077    /// CUDA→CUDA `Op::Copy` — the shape `insert_safety_copies` emits for its
9078    /// aliasing-hazard snapshots in the real Llama decode graph — is
9079    /// capture-safe via `copy_from_cuda_wrapper`'s write-into
9080    /// `BackendStorage::Cuda` branch (`CudaStorageBytes::copy_from_device`).
9081    ///
9082    /// Graph: `x [2,4]`, `b [2,4]` --Copy{target: Cuda{0}}--> `c` (same-device
9083    /// snapshot of `x`) --Add(c, b)--> `y`. Capture, replay twice unchanged,
9084    /// then update `x` in place and replay again — every step must match an
9085    /// independent uncaptured `realize`.
9086    #[test]
9087    #[ignore = "requires a live CUDA device"]
9088    #[cfg(feature = "cuda")]
9089    fn capture_decode_same_device_copy_replays_bit_exact_cuda() {
9090        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
9091        use fuel_ir::Shape;
9092        use fuel_memory::BackendStorage;
9093
9094        let Ok(dev) = CudaDevice::new(0) else {
9095            return fuel_test_support::hardware::skip(
9096                fuel_test_support::hardware::Hardware::Cuda,
9097                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
9098            );
9099        };
9100
9101        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId, NodeId) {
9102            let graph = Arc::new(RwLock::new(Graph::new()));
9103            let (x, b, y) = {
9104                let mut g = graph.write().unwrap();
9105                let x = g.push(Node {
9106                    op: Op::Const,
9107                    inputs: vec![],
9108                    shape: Shape::from_dims(&[2, 4]),
9109                    dtype: DType::F32,
9110                });
9111                let b = g.push(Node {
9112                    op: Op::Const,
9113                    inputs: vec![],
9114                    shape: Shape::from_dims(&[2, 4]),
9115                    dtype: DType::F32,
9116                });
9117                // Same-device CUDA->CUDA copy — the write-into-safe case.
9118                let c = g.push(Node {
9119                    op: Op::Copy {
9120                        target: DeviceLocation::Cuda { gpu_id: 0 },
9121                    },
9122                    inputs: vec![x],
9123                    shape: Shape::from_dims(&[2, 4]),
9124                    dtype: DType::F32,
9125                });
9126                let y = g.push(Node {
9127                    op: Op::Add,
9128                    inputs: vec![c, b],
9129                    shape: Shape::from_dims(&[2, 4]),
9130                    dtype: DType::F32,
9131                });
9132                // Copy's target_backend = SOURCE backend (x is Cuda-resident).
9133                g.set_target_backend(c, BackendId::Cuda);
9134                g.set_target_backend(y, BackendId::Cuda);
9135                (x, b, y)
9136            };
9137            (graph, x, b, y)
9138        };
9139
9140        let up = |v: &[f32]| -> Arc<RwLock<Storage>> {
9141            let cb = CudaStorageBytes::from_cpu_bytes(&dev, bytemuck::cast_slice(v)).expect("h2d");
9142            Arc::new(RwLock::new(Storage::new(
9143                BackendStorage::Cuda(cb),
9144                DType::F32,
9145            )))
9146        };
9147        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9148            let g = arc.read().unwrap();
9149            let BackendStorage::Cuda(c) = &g.inner else {
9150                panic!("not cuda")
9151            };
9152            bytemuck::cast_slice(&c.to_cpu_bytes().expect("d2h")).to_vec()
9153        };
9154
9155        let x_data: Vec<f32> = (0..8).map(|i| i as f32).collect();
9156        let b_data: Vec<f32> = (0..8).map(|i| 100.0 + i as f32).collect();
9157        let x_arc = up(&x_data);
9158        let (graph, x, b, y) = build();
9159        let mut inputs = StorageCache::new();
9160        inputs.insert(x, x_arc.clone());
9161        // `b` deliberately NOT retained by a local variable — forces
9162        // reliance on `capture_decode`'s own `retained_inputs`.
9163        inputs.insert(b, up(&b_data));
9164
9165        let captured =
9166            PipelinedExecutor::capture_decode(Arc::clone(&graph), y, inputs, SymEnv::default())
9167                .expect("capture_decode same-device copy");
9168
9169        let realize_ref = |xv: &[f32], bv: &[f32]| -> Vec<f32> {
9170            let (g, xr, br, yr) = build();
9171            let mut ins = StorageCache::new();
9172            ins.insert(xr, up(xv));
9173            ins.insert(br, up(bv));
9174            let (arc, _) = PipelinedExecutor::realize(g, yr, ins).expect("ref realize");
9175            read(&arc)
9176        };
9177        let expect0 = realize_ref(&x_data, &b_data);
9178
9179        // (1) warm-run result sits in the captured output buffer.
9180        assert_eq!(read(&captured.output), expect0, "warm result after capture");
9181
9182        // (2) replay TWICE with unchanged inputs — the Copy's write-into
9183        //     destination buffer must stay bit-exact across replays.
9184        for i in 0..2 {
9185            captured
9186                .run
9187                .replay(&dev)
9188                .unwrap_or_else(|e| panic!("replay {i}: {e:?}"));
9189            dev.synchronize().expect("sync");
9190            assert_eq!(
9191                read(&captured.output),
9192                expect0,
9193                "replay {i} reproduces result"
9194            );
9195        }
9196
9197        // (3) overwrite x in place (a DIFFERENT value-set), replay again ->
9198        //     the Copy re-runs on the fixed input address into its fixed
9199        //     destination buffer -> matches an independent uncaptured realize.
9200        let x2: Vec<f32> = (0..8).map(|i| 1000.0 + i as f32).collect();
9201        {
9202            let g = x_arc.read().unwrap();
9203            let BackendStorage::Cuda(c) = &g.inner else {
9204                panic!("x not cuda")
9205            };
9206            c.write_from_host(bytemuck::cast_slice(&x2))
9207                .expect("in-place H2D");
9208        }
9209        captured.run.replay(&dev).expect("replay 3");
9210        dev.synchronize().expect("sync 3");
9211        assert_eq!(
9212            read(&captured.output),
9213            realize_ref(&x2, &b_data),
9214            "replay after x update matches independent uncaptured realize"
9215        );
9216    }
9217
9218    /// CapturedRun executor build-out (Increment 4b-ζ): a genuinely
9219    /// cross-device `Op::Copy` (D2H — `target: DeviceLocation::Cpu` from a
9220    /// CUDA-resident source) must still be REJECTED by `capture_decode`'s
9221    /// validation loop — a host round-trip can never be part of a CUDA
9222    /// graph capture. Fast check: no replay, just confirm the typed `Err`.
9223    #[test]
9224    #[ignore = "requires a live CUDA device"]
9225    #[cfg(feature = "cuda")]
9226    fn capture_decode_rejects_cross_device_copy_cuda() {
9227        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
9228        use fuel_ir::Shape;
9229        use fuel_memory::BackendStorage;
9230
9231        let Ok(dev) = CudaDevice::new(0) else {
9232            return fuel_test_support::hardware::skip(
9233                fuel_test_support::hardware::Hardware::Cuda,
9234                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
9235            );
9236        };
9237
9238        let graph = Arc::new(RwLock::new(Graph::new()));
9239        let (x, y) = {
9240            let mut g = graph.write().unwrap();
9241            let x = g.push(Node {
9242                op: Op::Const,
9243                inputs: vec![],
9244                shape: Shape::from_dims(&[2, 4]),
9245                dtype: DType::F32,
9246            });
9247            // Genuinely cross-device: D2H.
9248            let y = g.push(Node {
9249                op: Op::Copy {
9250                    target: DeviceLocation::Cpu,
9251                },
9252                inputs: vec![x],
9253                shape: Shape::from_dims(&[2, 4]),
9254                dtype: DType::F32,
9255            });
9256            g.set_target_backend(y, BackendId::Cuda); // source backend = Cuda
9257            (x, y)
9258        };
9259
9260        let x_data: Vec<f32> = (0..8).map(|i| i as f32).collect();
9261        let cb =
9262            CudaStorageBytes::from_cpu_bytes(&dev, bytemuck::cast_slice(&x_data)).expect("h2d");
9263        let x_arc = Arc::new(RwLock::new(Storage::new(
9264            BackendStorage::Cuda(cb),
9265            DType::F32,
9266        )));
9267        let mut inputs = StorageCache::new();
9268        inputs.insert(x, x_arc);
9269
9270        let result = PipelinedExecutor::capture_decode(graph, y, inputs, SymEnv::default());
9271        let msg = match result {
9272            Ok(_) => panic!("D2H Op::Copy must be rejected by capture_decode"),
9273            Err(e) => e.to_string(),
9274        };
9275        assert!(
9276            msg.contains("cross-device"),
9277            "error should describe the cross-device rejection: {msg}"
9278        );
9279    }
9280
9281    /// CapturedDecodeSession (Increment 4a): drive the warm→capture→replay
9282    /// orchestration over MANY tokens on a synthetic decode-shaped session —
9283    /// the real per-token decode pattern. Capture once, then per token
9284    /// H2D-update the fixed input buffer IN PLACE + replay, asserting each
9285    /// token's output is bit-exact against an independent uncaptured realize.
9286    /// A kernel-agnostic proof of the state machine + fixed-buffer mechanics
9287    /// (matmul + index_select excluded pending baracuda capture-safe kernels).
9288    #[test]
9289    #[ignore = "requires a live CUDA device"]
9290    #[cfg(feature = "cuda")]
9291    fn captured_decode_session_replays_many_tokens_cuda() {
9292        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
9293        use fuel_graph::registry::{FusedOpParams, FusedOps};
9294        use fuel_ir::Shape;
9295        use fuel_memory::BackendStorage;
9296
9297        let Ok(dev) = CudaDevice::new(0) else {
9298            return fuel_test_support::hardware::skip(
9299                fuel_test_support::hardware::Hardware::Cuda,
9300                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
9301            );
9302        };
9303        const H: usize = 6;
9304        let eps = 1e-5f64;
9305
9306        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId) {
9307            let graph = Arc::new(RwLock::new(Graph::new()));
9308            let (x, y) = {
9309                let mut g = graph.write().unwrap();
9310                let mk = |g: &mut Graph, op: Op, ins: Vec<NodeId>, dims: &[usize]| {
9311                    g.push(Node {
9312                        op,
9313                        inputs: ins,
9314                        shape: Shape::from_dims(dims),
9315                        dtype: DType::F32,
9316                    })
9317                };
9318                let rms = || {
9319                    Op::Fused(
9320                        FusedOps::RMS_NORM_LAST_DIM,
9321                        FusedOpParams::RmsNormLastDim { eps },
9322                    )
9323                };
9324                let sm = || Op::Fused(FusedOps::SOFTMAX_LAST_DIM, FusedOpParams::SoftmaxLastDim);
9325                let x = mk(&mut g, Op::Const, vec![], &[1, H]);
9326                let n1 = mk(&mut g, rms(), vec![x], &[1, H]);
9327                let s = mk(&mut g, Op::Silu, vec![n1], &[1, H]);
9328                let p = mk(&mut g, sm(), vec![s], &[1, H]);
9329                let r = mk(&mut g, Op::Add, vec![p, x], &[1, H]);
9330                let n2 = mk(&mut g, rms(), vec![r], &[1, H]);
9331                let y = mk(&mut g, Op::Add, vec![n2, x], &[1, H]);
9332                for id in [n1, s, p, r, n2, y] {
9333                    g.set_target_backend(id, BackendId::Cuda);
9334                }
9335                (x, y)
9336            };
9337            (graph, x, y)
9338        };
9339        let up = |v: &[f32]| -> Arc<RwLock<Storage>> {
9340            let cb = CudaStorageBytes::from_cpu_bytes(&dev, bytemuck::cast_slice(v)).expect("h2d");
9341            Arc::new(RwLock::new(Storage::new(
9342                BackendStorage::Cuda(cb),
9343                DType::F32,
9344            )))
9345        };
9346        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9347            let g = arc.read().unwrap();
9348            let BackendStorage::Cuda(c) = &g.inner else {
9349                panic!("not cuda")
9350            };
9351            bytemuck::cast_slice(&c.to_cpu_bytes().expect("d2h")).to_vec()
9352        };
9353        let realize_ref = |xv: &[f32]| -> Vec<f32> {
9354            let (g, xr, yr) = build();
9355            let mut ins = StorageCache::new();
9356            ins.insert(xr, up(xv));
9357            let (arc, _) = PipelinedExecutor::realize(g, yr, ins).expect("ref realize");
9358            read(&arc)
9359        };
9360
9361        // 5 distinct "tokens" (distinct per-token input value-sets).
9362        let tokens: Vec<Vec<f32>> = (0..5)
9363            .map(|t| {
9364                (0..H)
9365                    .map(|c| 0.1 * (t as f32 + 1.0) * (c as f32 + 1.0))
9366                    .collect()
9367            })
9368            .collect();
9369
9370        // Capture ONCE against token 0's fixed input buffer.
9371        let x_arc = up(&tokens[0]);
9372        let (graph, x, y) = build();
9373        let mut inputs = StorageCache::new();
9374        inputs.insert(x, x_arc.clone());
9375        let session =
9376            CapturedDecodeSession::capture(Arc::clone(&graph), y, inputs, &[x], SymEnv::default())
9377                .expect("capture session");
9378
9379        // Warm result (token 0) already sits in the output buffer.
9380        assert_eq!(
9381            read(session.output()),
9382            realize_ref(&tokens[0]),
9383            "warm token 0"
9384        );
9385
9386        // The decode loop: replay every token (incl. re-replaying token 0) via
9387        // in-place H2D update of the fixed input + one graph launch.
9388        for (t, tok) in tokens.iter().enumerate() {
9389            let out = session
9390                .replay_token(&[(x, bytemuck::cast_slice(tok))])
9391                .expect("replay_token");
9392            assert_eq!(
9393                read(&out),
9394                realize_ref(tok),
9395                "replayed token {t} matches uncaptured realize"
9396            );
9397        }
9398        // Distinct tokens must give distinct outputs (live recompute, not stale).
9399        assert_ne!(
9400            realize_ref(&tokens[0]),
9401            realize_ref(&tokens[1]),
9402            "tokens must differ"
9403        );
9404    }
9405
9406    /// PR-C1 behavior contract: `realize_with_optimized_route` with an
9407    /// **empty** route (the no-pressure / no-telemetry case) is
9408    /// byte-identical to `realize_with_optimized` (arm-0). On a branchless
9409    /// graph the route has no branches to resolve, so both must produce
9410    /// the same bytes — realize is unchanged from Phase B.
9411    #[test]
9412    fn realize_with_optimized_route_empty_equals_arm0() {
9413        use crate::optimize::OptimizedGraph;
9414
9415        let build = || {
9416            let graph = Arc::new(RwLock::new(Graph::new()));
9417            let (lhs_id, rhs_id, add_id) = {
9418                let mut g = graph.write().unwrap();
9419                let lhs_id = g.push(Node {
9420                    op: Op::Const,
9421                    inputs: vec![],
9422                    shape: Shape::from_dims(&[3]),
9423                    dtype: DType::F32,
9424                });
9425                let rhs_id = g.push(Node {
9426                    op: Op::Const,
9427                    inputs: vec![],
9428                    shape: Shape::from_dims(&[3]),
9429                    dtype: DType::F32,
9430                });
9431                let add_id = g.push(Node {
9432                    op: Op::Add,
9433                    inputs: vec![lhs_id, rhs_id],
9434                    shape: Shape::from_dims(&[3]),
9435                    dtype: DType::F32,
9436                });
9437                g.set_target_backend(add_id, BackendId::Cpu);
9438                (lhs_id, rhs_id, add_id)
9439            };
9440            let mut inputs = StorageCache::new();
9441            inputs.insert(
9442                lhs_id,
9443                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9444                    1.0_f32, 2.0, 3.0,
9445                ]))),
9446            );
9447            inputs.insert(
9448                rhs_id,
9449                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9450                    10.0_f32, 20.0, 30.0,
9451                ]))),
9452            );
9453            (graph, add_id, inputs)
9454        };
9455
9456        let read_bytes = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9457            let guard = arc.read().unwrap();
9458            match &guard.inner {
9459                fuel_memory::BackendStorage::Cpu(c) => {
9460                    c.as_slice::<f32>().expect("f32 cast").to_vec()
9461                }
9462                _ => panic!("expected CPU output"),
9463            }
9464        };
9465
9466        // Stamp the fixture with the LIVE topology generation rather than a
9467        // hard-coded 0. The executor's chunk-boundary check compares the plan's
9468        // stamped generation against `topology_generation()`; a real
9469        // `OptimizedGraph` carries the generation snapshotted at optimize time
9470        // (`plan.rs` `compile_plan`, which reads it *after* the bindings table
9471        // is warm), so it already reflects every registered backend. Force
9472        // `global_bindings()` init here so any feature-gated auto-registration
9473        // has run and settled the counter before we read it — otherwise a stale
9474        // read would be bumped out from under us the first time realize warms
9475        // the bindings. Under default features this is 0; under
9476        // `--features vulkan`, `register_derived_gpu_caps` bumps it to 1.
9477        drop(global_bindings());
9478        let live_gen = crate::dispatch::topology_generation();
9479
9480        // Arm-0 path.
9481        let (g_a, add_a, in_a) = build();
9482        let opt_a = OptimizedGraph {
9483            roots: vec![add_a],
9484            generation: live_gen,
9485            placements: None,
9486            eviction: None,
9487        };
9488        let (arm0_arc, _) = PipelinedExecutor::realize_with_optimized(g_a, add_a, in_a, &opt_a)
9489            .expect("arm-0 realize");
9490        let arm0 = read_bytes(&arm0_arc);
9491
9492        // Empty-route path — must match arm-0 exactly.
9493        let (g_r, add_r, in_r) = build();
9494        let opt_r = OptimizedGraph {
9495            roots: vec![add_r],
9496            generation: live_gen,
9497            placements: None,
9498            eviction: None,
9499        };
9500        let empty_route = PickedRoute::new();
9501        let (route_arc, _) =
9502            PipelinedExecutor::realize_with_optimized_route(g_r, add_r, in_r, &opt_r, &empty_route)
9503                .expect("empty-route realize");
9504        let routed = read_bytes(&route_arc);
9505
9506        assert_eq!(arm0, vec![11.0, 22.0, 33.0]);
9507        assert_eq!(
9508            routed, arm0,
9509            "an empty route realizes byte-identically to arm-0 (Phase B contract)",
9510        );
9511    }
9512
9513    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
9514    /// §5): [`PipelinedExecutor::realize_with_optimized_picking_cached_env`]
9515    /// over a shared `order_cache` must (a) realize byte-identically to the
9516    /// uncached arm-0 path, on both the cold (empty cache) and warm
9517    /// (populated cache) call, and (b) actually populate the cache on the
9518    /// first call rather than silently never using it.
9519    #[test]
9520    fn realize_with_optimized_picking_cached_env_matches_arm0_cold_and_warm() {
9521        use crate::optimize::OptimizedGraph;
9522        use std::sync::OnceLock;
9523
9524        let build = || {
9525            let graph = Arc::new(RwLock::new(Graph::new()));
9526            let (lhs_id, rhs_id, add_id) = {
9527                let mut g = graph.write().unwrap();
9528                let lhs_id = g.push(Node {
9529                    op: Op::Const,
9530                    inputs: vec![],
9531                    shape: Shape::from_dims(&[3]),
9532                    dtype: DType::F32,
9533                });
9534                let rhs_id = g.push(Node {
9535                    op: Op::Const,
9536                    inputs: vec![],
9537                    shape: Shape::from_dims(&[3]),
9538                    dtype: DType::F32,
9539                });
9540                let add_id = g.push(Node {
9541                    op: Op::Add,
9542                    inputs: vec![lhs_id, rhs_id],
9543                    shape: Shape::from_dims(&[3]),
9544                    dtype: DType::F32,
9545                });
9546                g.set_target_backend(add_id, BackendId::Cpu);
9547                (lhs_id, rhs_id, add_id)
9548            };
9549            let mut inputs = StorageCache::new();
9550            inputs.insert(
9551                lhs_id,
9552                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9553                    1.0_f32, 2.0, 3.0,
9554                ]))),
9555            );
9556            inputs.insert(
9557                rhs_id,
9558                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9559                    10.0_f32, 20.0, 30.0,
9560                ]))),
9561            );
9562            (graph, add_id, inputs)
9563        };
9564        let read_bytes = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9565            let guard = arc.read().unwrap();
9566            match &guard.inner {
9567                fuel_memory::BackendStorage::Cpu(c) => {
9568                    c.as_slice::<f32>().expect("f32 cast").to_vec()
9569                }
9570                _ => panic!("expected CPU output"),
9571            }
9572        };
9573
9574        drop(global_bindings());
9575        let live_gen = crate::dispatch::topology_generation();
9576
9577        let (g, add, inputs) = build();
9578        let optimized = OptimizedGraph {
9579            roots: vec![add],
9580            generation: live_gen,
9581            placements: None,
9582            eviction: None,
9583        };
9584        let order_cache: OnceLock<Vec<NodeId>> = OnceLock::new();
9585        assert!(order_cache.get().is_none(), "sanity: cache starts empty");
9586
9587        // Cold call: cache miss, must compute AND populate.
9588        let (cold_arc, _) = PipelinedExecutor::realize_with_optimized_picking_cached_env(
9589            g.clone(),
9590            add,
9591            inputs,
9592            &optimized,
9593            &order_cache,
9594            None,
9595            None,
9596            SymEnv::default(),
9597        )
9598        .expect("cold cached realize");
9599        assert_eq!(read_bytes(&cold_arc), vec![11.0, 22.0, 33.0]);
9600        assert!(
9601            order_cache.get().is_some(),
9602            "the cold call must populate order_cache, not leave it empty"
9603        );
9604        let cached_order_after_cold = order_cache.get().unwrap().clone();
9605
9606        // Warm call: cache hit. Fresh inputs (same graph, new values) so the
9607        // realized OUTPUT differs from the cold call while the dispatch
9608        // ORDER (what's cached) must not change.
9609        let mut warm_inputs = StorageCache::new();
9610        warm_inputs.insert(
9611            g.read().unwrap().node(add).inputs[0],
9612            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9613                100.0_f32, 200.0, 300.0,
9614            ]))),
9615        );
9616        warm_inputs.insert(
9617            g.read().unwrap().node(add).inputs[1],
9618            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9619                1.0_f32, 2.0, 3.0,
9620            ]))),
9621        );
9622        let (warm_arc, _) = PipelinedExecutor::realize_with_optimized_picking_cached_env(
9623            g,
9624            add,
9625            warm_inputs,
9626            &optimized,
9627            &order_cache,
9628            None,
9629            None,
9630            SymEnv::default(),
9631        )
9632        .expect("warm cached realize");
9633        assert_eq!(
9634            read_bytes(&warm_arc),
9635            vec![101.0, 202.0, 303.0],
9636            "warm call must realize its OWN rebound inputs, not replay stale output",
9637        );
9638        assert_eq!(
9639            order_cache.get().unwrap(),
9640            &cached_order_after_cold,
9641            "the warm call must reuse the SAME cached order, not recompute a different one",
9642        );
9643    }
9644
9645    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
9646    /// §5), PM review question: does `OrderSource::Cached` weaken the
9647    /// existing `TopologyChanged` chunk-boundary check? No — proven at the
9648    /// unit level (not a live topology-bump integration test, deliberately:
9649    /// `bump_topology_generation()` mutates a process-wide atomic shared by
9650    /// every concurrently-running test in this binary, including the cold/
9651    /// warm cache test above, which reads it into a local at the start of
9652    /// ITS OWN body and would flake if another test's bump landed mid-call;
9653    /// introducing that cross-test hazard isn't worth it when the two arms'
9654    /// `generation_for` expressions are provably identical). `generation_for`
9655    /// is private to this module, so it's tested directly here: given the
9656    /// SAME `&OptimizedGraph`, `Cached` and `Optimized` must report the
9657    /// IDENTICAL generation — the chunk-boundary check that compares this
9658    /// value against the LIVE `topology_generation()` fires exactly the
9659    /// same way for both, so caching cannot silently skip or weaken it.
9660    #[test]
9661    fn cached_generation_for_matches_optimized_generation_for() {
9662        let optimized = OptimizedGraph {
9663            roots: vec![NodeId(0)],
9664            generation: 42,
9665            placements: None,
9666            eviction: None,
9667        };
9668        let order_cache: std::sync::OnceLock<Vec<NodeId>> = std::sync::OnceLock::new();
9669
9670        let optimized_gen = generation_for(&OrderSource::Optimized {
9671            optimized: &optimized,
9672            route: None,
9673        });
9674        let cached_gen = generation_for(&OrderSource::Cached {
9675            optimized: &optimized,
9676            order_cache: &order_cache,
9677        });
9678        assert_eq!(
9679            optimized_gen,
9680            Some(42),
9681            "sanity: Optimized reports the OptimizedGraph's own generation",
9682        );
9683        assert_eq!(
9684            cached_gen, optimized_gen,
9685            "Cached must report the SAME generation as Optimized for the same \
9686             OptimizedGraph -- the TopologyChanged check cannot tell the two apart, \
9687             by construction, so caching cannot silently weaken it",
9688        );
9689    }
9690
9691    /// **PR-C3 reorder-invariance gate (CPU, runnable — ORDERING level).**
9692    /// The auto-overlap reorder is a HINT: it changes only *which order*
9693    /// independent device runs dispatch in, never *which* nodes run nor the
9694    /// result. The byte-identical-OUTPUT proof is necessarily LIVE (the
9695    /// reorder fires only on a ≥2-device graph, which needs ≥2 real backends
9696    /// to realize — see `cuda_vulkan_multidevice_realize_live`'s
9697    /// `[22,86,192,340]` oracle, which now flows through this reorder, plus
9698    /// the dual-GPU `cuda_vulkan_overlap_bench_live` arbitrary-graph
9699    /// auto-overlap gate). THIS test proves the ordering-level invariant on a
9700    /// CPU-only path: the C3 reorder of a two-device graph is a valid
9701    /// topological **permutation** of the un-reordered topo order — same node
9702    /// multiset, every node still after its inputs — that genuinely DIFFERS
9703    /// from the un-reordered order (so the reorder fired). Because the
9704    /// executor caches each node's result and every op is deterministic,
9705    /// realizing any valid topological order yields identical bytes; this
9706    /// test guards the precondition (a valid permutation) that makes that so.
9707    #[test]
9708    fn c3_reorder_is_a_valid_topo_permutation() {
9709        // Two INDEPENDENT device sub-chains over distinct consts reconverging
9710        // at a final CUDA add, the Vulkan root bridged to CUDA by an explicit
9711        // Op::Copy (a residency seam = its own run). Reconverge inputs in the
9712        // "wrong" (cuda-first) order, the order the un-reordered topo DFS pops
9713        // CUDA-last — exactly the arbitrary-graph shape the auto-overlap pass
9714        // must fix. The chains are UNARY (Relu) so each stays a single
9715        // contiguous run (no const-re-read fan-in fragmenting them), exactly
9716        // like the live benchmark's `relu(mul·add)` chains; the CUDA chain is
9717        // HEAVIER (4 vs 2) so the critical-path reorder emits it first.
9718        // (Stamps only; not realized here — the ordering proof, CPU-runnable.)
9719        let n = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9720            g.push(Node {
9721                op,
9722                inputs,
9723                shape: Shape::from_dims(&[3]),
9724                dtype: DType::F32,
9725            })
9726        };
9727        let mut g = Graph::new();
9728        let ca = n(&mut g, Op::Const, vec![]);
9729        let cb = n(&mut g, Op::Const, vec![]);
9730        // CUDA chain — HEAVIER (4 unary stages, one contiguous run).
9731        let mut cprev = ca;
9732        for _ in 0..4 {
9733            cprev = n(&mut g, Op::Relu, vec![cprev]);
9734            g.set_target_backend(cprev, BackendId::Cuda);
9735        }
9736        let c2 = cprev; // CUDA chunk root
9737        // Vulkan chain — lighter (2 unary stages).
9738        let mut vprev = cb;
9739        for _ in 0..2 {
9740            vprev = n(&mut g, Op::Relu, vec![vprev]);
9741            g.set_target_backend(vprev, BackendId::Vulkan);
9742        }
9743        let v2 = vprev; // Vulkan chunk root
9744        // Vulkan -> CUDA copy (residency seam), then reconverge on CUDA with
9745        // inputs [cuda_root, copy] (cuda-first).
9746        let copy = g.push(Node {
9747            op: Op::Copy {
9748                target: DeviceLocation::Cuda { gpu_id: 0 },
9749            },
9750            inputs: vec![v2],
9751            shape: Shape::from_dims(&[3]),
9752            dtype: DType::F32,
9753        });
9754        g.set_target_backend(copy, BackendId::Cuda);
9755        let out = n(&mut g, Op::Add, vec![c2, copy]);
9756        g.set_target_backend(out, BackendId::Cuda);
9757
9758        let unreordered = execution_plan(&g, &[out]);
9759        let reordered = fuel_graph::lower_runs_arm0(&g, &[out]);
9760
9761        // (1) The reorder FIRED — the order changed (else the test is
9762        //     vacuous + auto-overlap did nothing on an arbitrary graph).
9763        assert_ne!(
9764            reordered, unreordered,
9765            "the C3 reorder must change the order on a two-device graph; \
9766             reordered={reordered:?} unreordered={unreordered:?}",
9767        );
9768
9769        // (2) Same node multiset — a permutation, no add/drop.
9770        let mut a = unreordered.clone();
9771        let mut b = reordered.clone();
9772        a.sort();
9773        b.sort();
9774        assert_eq!(a, b, "the reorder is a permutation of the same node set");
9775
9776        // (3) The reordered order is a VALID topological order: every node
9777        //     appears after all of its inputs that are in the order.
9778        let pos: std::collections::HashMap<NodeId, usize> = reordered
9779            .iter()
9780            .enumerate()
9781            .map(|(i, &node)| (node, i))
9782            .collect();
9783        for (i, &node) in reordered.iter().enumerate() {
9784            for &inp in &g.node(node).inputs {
9785                if let Some(&j) = pos.get(&inp) {
9786                    assert!(
9787                        j < i,
9788                        "input {inp:?} of {node:?} must precede it in the reordered \
9789                         order; reordered={reordered:?}",
9790                    );
9791                }
9792            }
9793        }
9794
9795        // (4) The overlap-relevant property: BOTH device producer chunks
9796        //     (the CUDA root c2, the Vulkan root v2) are emitted BEFORE the
9797        //     host-blocking cross-device copy — the A4b overlap topology the
9798        //     un-reordered cuda-last DFS violates — AND the HEAVIER CUDA chunk
9799        //     is emitted first (critical-path: the auto-submit device runs
9800        //     earliest, the live-overlap regression guard).
9801        let p = |node: NodeId| pos[&node];
9802        assert!(p(c2) < p(copy), "CUDA chunk before the cross-device copy");
9803        assert!(p(v2) < p(copy), "Vulkan chunk before the cross-device copy");
9804        assert!(
9805            p(c2) < p(v2),
9806            "the heavier CUDA chunk is emitted before the lighter Vulkan chunk \
9807             (critical-path heavy-first); reordered={reordered:?}",
9808        );
9809    }
9810
9811    /// **C3 follow-on — the OPERAND-ORDER-INVARIANCE gate (CPU, runnable —
9812    /// the reliable operand-independence proof).** The residual the live
9813    /// `cuda_vulkan_overlap_bench_live` benchmark targets is whether the
9814    /// reconverge OPERAND order (`xc.add(&xv)` vs `xv.add(&xc)`) changes the
9815    /// wall-clock overlap. Wall-clock is thermally noisy on a heterogeneous
9816    /// dev box; the DETERMINISTIC root guarantee is this: the C3-reordered
9817    /// dispatch order the executor consumes is **byte-identical for both
9818    /// operand orders**. If the lowered order is the same, the executor
9819    /// processes the SAME WorkItem stream with the SAME cross-device
9820    /// submit/wait timing, so overlap cannot depend on the operand order.
9821    ///
9822    /// This builds the SAME two-device reconverge as
9823    /// `c3_reorder_is_a_valid_topo_permutation` but TWICE — once cuda-first
9824    /// (`add(cuda_root, copy)`), once vulkan-first (`add(copy, cuda_root)`)
9825    /// — over structurally identical graphs (same node ids, only the
9826    /// reconverge's two inputs swapped) and asserts `lower_runs_arm0` emits
9827    /// the identical op/device run sequence. The live executor trace confirms
9828    /// the same: both operand orders produce the identical WorkItem stream
9829    /// (the eager-submit/drain/wait sequence at every cross-device copy is the
9830    /// same, and the CUDA chunk is enqueued first in both).
9831    #[test]
9832    fn c3_reorder_is_operand_order_invariant() {
9833        // Build the two-device reconverge with the reconverge inputs in the
9834        // given order; return (graph, out) over a FRESH graph so node ids line
9835        // up 1:1 between the two builds (only the add's input order differs).
9836        let build = |cuda_first: bool| -> (Graph, NodeId) {
9837            let n = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9838                g.push(Node {
9839                    op,
9840                    inputs,
9841                    shape: Shape::from_dims(&[3]),
9842                    dtype: DType::F32,
9843                })
9844            };
9845            let mut g = Graph::new();
9846            let ca = n(&mut g, Op::Const, vec![]);
9847            let cb = n(&mut g, Op::Const, vec![]);
9848            let mut cprev = ca;
9849            for _ in 0..4 {
9850                cprev = n(&mut g, Op::Relu, vec![cprev]);
9851                g.set_target_backend(cprev, BackendId::Cuda);
9852            }
9853            let c2 = cprev;
9854            let mut vprev = cb;
9855            for _ in 0..2 {
9856                vprev = n(&mut g, Op::Relu, vec![vprev]);
9857                g.set_target_backend(vprev, BackendId::Vulkan);
9858            }
9859            let v2 = vprev;
9860            let copy = g.push(Node {
9861                op: Op::Copy {
9862                    target: DeviceLocation::Cuda { gpu_id: 0 },
9863                },
9864                inputs: vec![v2],
9865                shape: Shape::from_dims(&[3]),
9866                dtype: DType::F32,
9867            });
9868            g.set_target_backend(copy, BackendId::Cuda);
9869            // The ONE knob: the reconverge's two inputs, swapped.
9870            let inputs = if cuda_first {
9871                vec![c2, copy]
9872            } else {
9873                vec![copy, c2]
9874            };
9875            let out = n(&mut g, Op::Add, inputs);
9876            g.set_target_backend(out, BackendId::Cuda);
9877            (g, out)
9878        };
9879
9880        let (g_cf, out_cf) = build(true);
9881        let (g_vf, out_vf) = build(false);
9882
9883        // Lower both via the production path (dispatch_order → lower_runs_arm0
9884        // → device_alternating_order, the C3 reorder).
9885        let order_cf = fuel_graph::lower_runs_arm0(&g_cf, &[out_cf]);
9886        let order_vf = fuel_graph::lower_runs_arm0(&g_vf, &[out_vf]);
9887
9888        // The decisive guarantee: the lowered dispatch order — as an
9889        // (op, device) sequence — is IDENTICAL for both operand orders. (Node
9890        // ids can differ if the build assigned them differently, but here the
9891        // builds are structurally identical so even the ids match; compare the
9892        // op/device sequence to be robust + descriptive on failure.)
9893        let tag = |g: &Graph, ids: &[NodeId]| -> Vec<(String, Option<BackendId>)> {
9894            ids.iter()
9895                .map(|&id| (format!("{:?}", g.node(id).op), g.target_backend(id)))
9896                .collect()
9897        };
9898        let seq_cf = tag(&g_cf, &order_cf);
9899        let seq_vf = tag(&g_vf, &order_vf);
9900        assert_eq!(
9901            seq_cf, seq_vf,
9902            "the C3-reordered dispatch order MUST be identical for both \
9903             reconverge operand orders (operand-order-invariance — the \
9904             executor then sees the same WorkItem stream regardless of \
9905             operand order, so overlap is operand-insensitive).\n\
9906             cuda-first = {seq_cf:?}\nvulkan-first = {seq_vf:?}",
9907        );
9908    }
9909
9910    /// A selector that always takes the LAST arm (arm 1) so a non-arm-0
9911    /// pick is observable (a `WinnerSelector` picks arm-0 ⇒ empty route).
9912    #[cfg(test)]
9913    #[derive(Debug)]
9914    struct PickLast;
9915    #[cfg(test)]
9916    impl RuntimeSelector for PickLast {
9917        fn select<'a>(
9918            &self,
9919            set: &'a crate::ranker::AlternativeSet,
9920        ) -> Option<&'a crate::ranker::Candidate> {
9921            set.alternatives().last()
9922        }
9923    }
9924
9925    /// Build the 2-arm diamond (mirrors `route_picker::tests::diamond`):
9926    /// arm-0 on CUDA, arm-1 on CPU; the arm exits carry their
9927    /// `target_backend` so the picker reads each arm's placement. Returns
9928    /// `(graph_arc, branch, post)`.
9929    #[cfg(test)]
9930    fn picking_diamond() -> (Arc<RwLock<Graph>>, NodeId, NodeId) {
9931        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9932            g.push(Node {
9933                op,
9934                inputs,
9935                shape: Shape::from_dims(&[2]),
9936                dtype: DType::F32,
9937            })
9938        };
9939        let mut g = Graph::new();
9940        let pre = node(&mut g, Op::Const, vec![]);
9941        let diverge = node(&mut g, Op::Relu, vec![pre]);
9942        let arm0 = node(&mut g, Op::Silu, vec![diverge]);
9943        let arm1 = node(&mut g, Op::GeluTanh, vec![diverge]);
9944        g.set_target_backend(arm0, BackendId::Cuda);
9945        g.set_target_backend(arm1, BackendId::Cpu);
9946        let reconverge = node(&mut g, Op::Relu, vec![arm0]);
9947        let mut b = g.open_branch(diverge);
9948        b.add_arm(arm0);
9949        b.add_arm(arm1);
9950        let branch = b
9951            .finalize_branches(&mut g, reconverge)
9952            .expect("well-formed 2-arm branch")
9953            .expect("2 arms survive");
9954        let post = node(&mut g, Op::Tanh, vec![reconverge]);
9955        (Arc::new(RwLock::new(g)), branch, post)
9956    }
9957
9958    /// Step E Phase C, PR C1: the streaming picking entry's gate.
9959    /// `streaming_pick_for` (the streaming successor of the old one-shot
9960    /// `pick_route_for`) must (1) return `Some(pick)` when a selector + a
9961    /// branch are present (⇒ the `OrderSource::Streaming` walk), (2) return
9962    /// `None` with no selector (the `runtime_selector_disabled` opt-out ⇒
9963    /// arm-0), and (3) short-circuit to `None` on a branchless graph (the
9964    /// fast-path ⇒ the untouched `dispatch_order` lowering).
9965    #[test]
9966    fn streaming_pick_for_gates() {
9967        let (graph, _branch, post) = picking_diamond();
9968        let _ = post;
9969
9970        // (1) selector + branch ⇒ Some(pick).
9971        let sel: Arc<dyn RuntimeSelector> = Arc::new(PickLast);
9972        assert!(
9973            PipelinedExecutor::streaming_pick_for(&graph, Some(sel.clone()), None)
9974                .expect("ok")
9975                .is_some(),
9976            "selector + branch ⇒ a streaming pick",
9977        );
9978
9979        // (2) no selector ⇒ None (arm-0 lowering).
9980        assert!(
9981            PipelinedExecutor::streaming_pick_for(&graph, None, None)
9982                .expect("ok")
9983                .is_none(),
9984            "no selector ⇒ no streaming pick (arm-0 lowering)",
9985        );
9986
9987        // (3) branchless graph + selector ⇒ None (the fast-path).
9988        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9989            g.push(Node {
9990                op,
9991                inputs,
9992                shape: Shape::from_dims(&[2]),
9993                dtype: DType::F32,
9994            })
9995        };
9996        let bl_graph = {
9997            let mut g = Graph::new();
9998            let c1 = node(&mut g, Op::Const, vec![]);
9999            let c2 = node(&mut g, Op::Const, vec![]);
10000            let add = node(&mut g, Op::Add, vec![c1, c2]);
10001            g.set_target_backend(add, BackendId::Cpu);
10002            Arc::new(RwLock::new(g))
10003        };
10004        assert!(
10005            PipelinedExecutor::streaming_pick_for(&bl_graph, Some(sel), None)
10006                .expect("ok")
10007                .is_none(),
10008            "branchless graph ⇒ no branches ⇒ no streaming pick (fast-path)",
10009        );
10010    }
10011
10012    /// **C1 byte-identity gate (executor layer).** The STREAMED dispatch
10013    /// order — produced by the compiler thread's lazy per-branch resolution
10014    /// (`walk_picked_route_streaming` over `resolve_branch`, the same path
10015    /// `order_for(OrderSource::Streaming)` collects) — equals the ONE-SHOT
10016    /// order (`lower_picked_route` over the route the eager `pick_route`
10017    /// resolves) on the branched diamond, for both arm-0 (WinnerSelector)
10018    /// and arm-1 (PickLast). This is the proof that C1 changes *when* a
10019    /// branch resolves, not *which* arm — the same selector, the same
10020    /// `resolve_branch`, the same emitted order.
10021    #[test]
10022    fn streamed_order_equals_one_shot() {
10023        let (graph, _branch, post) = picking_diamond();
10024        let g = graph.read().unwrap();
10025        let bindings = global_bindings();
10026
10027        for sel in [
10028            Arc::new(crate::ranker::WinnerSelector) as Arc<dyn RuntimeSelector>,
10029            Arc::new(PickLast) as Arc<dyn RuntimeSelector>,
10030        ] {
10031            // One-shot: resolve the whole route, then lower.
10032            let one_shot_route = pick_route(&g, &[post], &bindings, sel.as_ref(), None);
10033            let one_shot = fuel_graph::lower_picked_route(&g, &[post], &one_shot_route);
10034
10035            // Streamed: resolve each branch lazily at the frontier via the
10036            // SAME `resolve_branch` the compiler thread uses.
10037            let streamed = fuel_graph::lower_picked_route_streaming(&g, &[post], |branch| {
10038                resolve_branch(&g, branch, &bindings, sel.as_ref())
10039            });
10040
10041            assert_eq!(
10042                streamed, one_shot,
10043                "streamed order must equal one-shot for selector {sel:?}",
10044            );
10045        }
10046    }
10047
10048    /// Realizing a node whose target_backend isn't set surfaces a
10049    /// typed error (no panic).
10050    #[test]
10051    fn pipelined_errors_on_unset_target_backend() {
10052        let graph = Arc::new(RwLock::new(Graph::new()));
10053        let (lhs_id, rhs_id, add_id) = {
10054            let mut g = graph.write().unwrap();
10055            let lhs = g.push(Node {
10056                op: Op::Const,
10057                inputs: vec![],
10058                shape: Shape::from_dims(&[2]),
10059                dtype: DType::F32,
10060            });
10061            let rhs = g.push(Node {
10062                op: Op::Const,
10063                inputs: vec![],
10064                shape: Shape::from_dims(&[2]),
10065                dtype: DType::F32,
10066            });
10067            // Deliberately do NOT call set_target_backend on the Add.
10068            let add = g.push(Node {
10069                op: Op::Add,
10070                inputs: vec![lhs, rhs],
10071                shape: Shape::from_dims(&[2]),
10072                dtype: DType::F32,
10073            });
10074            (lhs, rhs, add)
10075        };
10076
10077        let mut inputs = StorageCache::new();
10078        inputs.insert(
10079            lhs_id,
10080            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]))),
10081        );
10082        inputs.insert(
10083            rhs_id,
10084            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[3.0_f32, 4.0]))),
10085        );
10086
10087        let result = PipelinedExecutor::realize(graph, add_id, inputs);
10088        assert!(result.is_err(), "missing target_backend must error");
10089        let msg = result.unwrap_err().to_string();
10090        assert!(
10091            msg.contains("target_backend"),
10092            "error names the unmet precondition: {msg}"
10093        );
10094    }
10095
10096    /// Realizing a Const-only graph adopts the pre-seeded input
10097    /// without calling any kernel.
10098    #[test]
10099    fn pipelined_realize_const_only() {
10100        let storage = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0, 7.0]);
10101
10102        let graph = Arc::new(RwLock::new(Graph::new()));
10103        let const_id = {
10104            let mut g = graph.write().unwrap();
10105            g.push(Node {
10106                op: Op::Const,
10107                inputs: vec![],
10108                shape: Shape::from_dims(&[3]),
10109                dtype: DType::F32,
10110            })
10111        };
10112
10113        let mut inputs = StorageCache::new();
10114        inputs.insert(const_id, Arc::new(RwLock::new(storage)));
10115
10116        let (result_arc, _) =
10117            PipelinedExecutor::realize(graph, const_id, inputs).expect("realize const");
10118        let guard = result_arc.read().unwrap();
10119        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
10120            let typed: &[f32] = c.as_slice().unwrap();
10121            assert_eq!(typed, &[5.0, 6.0, 7.0]);
10122        }
10123    }
10124
10125    /// Missing input-cache entry for a Const surfaces a typed error.
10126    #[test]
10127    fn pipelined_errors_on_missing_const_input() {
10128        let graph = Arc::new(RwLock::new(Graph::new()));
10129        let const_id = {
10130            let mut g = graph.write().unwrap();
10131            g.push(Node {
10132                op: Op::Const,
10133                inputs: vec![],
10134                shape: Shape::from_dims(&[2]),
10135                dtype: DType::F32,
10136            })
10137        };
10138        // Deliberately empty input cache.
10139        let inputs = StorageCache::new();
10140        let result = PipelinedExecutor::realize(graph, const_id, inputs);
10141        assert!(result.is_err());
10142    }
10143
10144    /// E2E: 2-node graph (Const + Relu) — exercises the unary
10145    /// dispatch wrapper + kernel through the pipelined executor.
10146    #[test]
10147    fn pipelined_realize_const_relu() {
10148        let storage = fuel_memory::from_slice_cpu(&[-1.0_f32, 0.0, 0.5, -3.5, 7.25]);
10149        let graph = Arc::new(RwLock::new(Graph::new()));
10150        let (in_id, relu_id) = {
10151            let mut g = graph.write().unwrap();
10152            let in_id = g.push(Node {
10153                op: Op::Const,
10154                inputs: vec![],
10155                shape: Shape::from_dims(&[5]),
10156                dtype: DType::F32,
10157            });
10158            let relu_id = g.push(Node {
10159                op: Op::Relu,
10160                inputs: vec![in_id],
10161                shape: Shape::from_dims(&[5]),
10162                dtype: DType::F32,
10163            });
10164            g.set_target_backend(relu_id, BackendId::Cpu);
10165            (in_id, relu_id)
10166        };
10167        let mut inputs = StorageCache::new();
10168        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10169
10170        let (result_arc, _) = PipelinedExecutor::realize(graph, relu_id, inputs).expect("realize");
10171        let guard = result_arc.read().unwrap();
10172        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
10173            let typed: &[f32] = c.as_slice().expect("f32 cast");
10174            assert_eq!(typed, &[0.0, 0.0, 0.5, 0.0, 7.25]);
10175        }
10176    }
10177
10178    /// E2E: Const + Const + Sub + Mul + Div — exercises three more
10179    /// of the freshly-migrated binary kernels in one graph. Verifies
10180    /// that intermediates flow through the cache as expected.
10181    #[test]
10182    fn pipelined_realize_chained_binary_ops() {
10183        let a_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
10184        let b_storage = fuel_memory::from_slice_cpu(&[3.0_f32, 5.0]);
10185        let c_storage = fuel_memory::from_slice_cpu(&[2.0_f32, 4.0]);
10186
10187        let graph = Arc::new(RwLock::new(Graph::new()));
10188        let (a_id, b_id, c_id, sub_id, mul_id, div_id) = {
10189            let mut g = graph.write().unwrap();
10190            let a = g.push(Node {
10191                op: Op::Const,
10192                inputs: vec![],
10193                shape: Shape::from_dims(&[2]),
10194                dtype: DType::F32,
10195            });
10196            let b = g.push(Node {
10197                op: Op::Const,
10198                inputs: vec![],
10199                shape: Shape::from_dims(&[2]),
10200                dtype: DType::F32,
10201            });
10202            let c = g.push(Node {
10203                op: Op::Const,
10204                inputs: vec![],
10205                shape: Shape::from_dims(&[2]),
10206                dtype: DType::F32,
10207            });
10208            // (a - b)         = [7, 15]
10209            let sub = g.push(Node {
10210                op: Op::Sub,
10211                inputs: vec![a, b],
10212                shape: Shape::from_dims(&[2]),
10213                dtype: DType::F32,
10214            });
10215            // (a - b) * c     = [14, 60]
10216            let mul = g.push(Node {
10217                op: Op::Mul,
10218                inputs: vec![sub, c],
10219                shape: Shape::from_dims(&[2]),
10220                dtype: DType::F32,
10221            });
10222            // ((a-b)*c) / b   = [14/3, 12]
10223            let div = g.push(Node {
10224                op: Op::Div,
10225                inputs: vec![mul, b],
10226                shape: Shape::from_dims(&[2]),
10227                dtype: DType::F32,
10228            });
10229            g.set_target_backend(sub, BackendId::Cpu);
10230            g.set_target_backend(mul, BackendId::Cpu);
10231            g.set_target_backend(div, BackendId::Cpu);
10232            (a, b, c, sub, mul, div)
10233        };
10234
10235        let _ = (sub_id, mul_id);
10236        let mut inputs = StorageCache::new();
10237        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
10238        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
10239        inputs.insert(c_id, Arc::new(RwLock::new(c_storage)));
10240
10241        let (result_arc, _) = PipelinedExecutor::realize(graph, div_id, inputs).expect("realize");
10242        let guard = result_arc.read().unwrap();
10243        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
10244            let typed: &[f32] = c.as_slice().unwrap();
10245            assert!((typed[0] - (14.0_f32 / 3.0)).abs() < 1e-6);
10246            assert!((typed[1] - 12.0).abs() < 1e-6);
10247        }
10248    }
10249
10250    /// E2E: Const + Transpose — verifies metadata-only view ops
10251    /// share the input's Storage Arc and produce a strided Layout.
10252    /// Stage 3 of Layout-on-Node.
10253    #[test]
10254    fn pipelined_realize_transpose_is_metadata_only() {
10255        // shape [2, 3]; transpose → shape [3, 2], strided
10256        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
10257        let graph = Arc::new(RwLock::new(Graph::new()));
10258        let (in_id, t_id) = {
10259            let mut g = graph.write().unwrap();
10260            let in_id = g.push(Node {
10261                op: Op::Const,
10262                inputs: vec![],
10263                shape: Shape::from_dims(&[2, 3]),
10264                dtype: DType::F32,
10265            });
10266            let t_id = g.push(Node {
10267                op: Op::Transpose,
10268                inputs: vec![in_id],
10269                shape: Shape::from_dims(&[3, 2]),
10270                dtype: DType::F32,
10271            });
10272            // Note: NO set_target_backend — transpose is metadata-only
10273            // and doesn't run on a backend.
10274            (in_id, t_id)
10275        };
10276        let mut inputs = StorageCache::new();
10277        let in_arc = Arc::new(RwLock::new(storage));
10278        inputs.insert(in_id, Arc::clone(&in_arc));
10279
10280        let (result_arc, result_layout) =
10281            PipelinedExecutor::realize(graph, t_id, inputs).expect("realize");
10282
10283        // The output Storage Arc is the SAME Arc as the input —
10284        // metadata-only adoption shares bytes.
10285        assert!(
10286            Arc::ptr_eq(&result_arc, &in_arc),
10287            "transpose must share input bytes"
10288        );
10289
10290        // The output Layout is the transposed view.
10291        assert_eq!(result_layout.shape().dims(), &[3, 2]);
10292        assert_eq!(result_layout.stride(), &[1, 3]);
10293        assert!(!result_layout.is_contiguous());
10294    }
10295
10296    /// E2E: Const + Flip(dim=0) — verifies Op::Flip is metadata-only.
10297    /// The output Storage Arc must be the SAME Arc (no copy);
10298    /// the output Layout has a negated stride at dim 0 and a
10299    /// shifted start_offset.
10300    #[test]
10301    fn pipelined_realize_flip_is_metadata_only() {
10302        // shape [3, 4]; flip dim 0 → shape [3, 4], stride [-4, 1], offset 8.
10303        let data: Vec<f32> = (1..=12).map(|x| x as f32).collect();
10304        let storage = fuel_memory::from_slice_cpu(&data);
10305        let graph = Arc::new(RwLock::new(Graph::new()));
10306        let (in_id, f_id) = {
10307            let mut g = graph.write().unwrap();
10308            let in_id = g.push(Node {
10309                op: Op::Const,
10310                inputs: vec![],
10311                shape: Shape::from_dims(&[3, 4]),
10312                dtype: DType::F32,
10313            });
10314            let f_id = g.push(Node {
10315                op: Op::Flip { dim: 0 },
10316                inputs: vec![in_id],
10317                shape: Shape::from_dims(&[3, 4]),
10318                dtype: DType::F32,
10319            });
10320            (in_id, f_id)
10321        };
10322        let mut inputs = StorageCache::new();
10323        let in_arc = Arc::new(RwLock::new(storage));
10324        inputs.insert(in_id, Arc::clone(&in_arc));
10325
10326        let (result_arc, result_layout) =
10327            PipelinedExecutor::realize(graph, f_id, inputs).expect("realize");
10328
10329        assert!(
10330            Arc::ptr_eq(&result_arc, &in_arc),
10331            "flip must share input bytes"
10332        );
10333        assert_eq!(result_layout.shape().dims(), &[3, 4]);
10334        assert_eq!(result_layout.stride(), &[-4_isize, 1]);
10335        assert_eq!(result_layout.start_offset(), 8);
10336        assert!(!result_layout.is_contiguous());
10337    }
10338
10339    /// E2E: Const + Permute(rank-3 axes [2, 0, 1]) — verifies the
10340    /// general permute path through metadata-only adoption.
10341    #[test]
10342    fn pipelined_realize_permute_is_metadata_only() {
10343        // shape [2, 3, 4]; permute axes [2, 0, 1] → shape [4, 2, 3]
10344        let data: Vec<f32> = (1..=24).map(|x| x as f32).collect();
10345        let storage = fuel_memory::from_slice_cpu(&data);
10346        let graph = Arc::new(RwLock::new(Graph::new()));
10347        let (in_id, p_id) = {
10348            let mut g = graph.write().unwrap();
10349            let in_id = g.push(Node {
10350                op: Op::Const,
10351                inputs: vec![],
10352                shape: Shape::from_dims(&[2, 3, 4]),
10353                dtype: DType::F32,
10354            });
10355            let p_id = g.push(Node {
10356                op: Op::Permute(vec![2, 0, 1]),
10357                inputs: vec![in_id],
10358                shape: Shape::from_dims(&[4, 2, 3]),
10359                dtype: DType::F32,
10360            });
10361            (in_id, p_id)
10362        };
10363        let mut inputs = StorageCache::new();
10364        let in_arc = Arc::new(RwLock::new(storage));
10365        inputs.insert(in_id, Arc::clone(&in_arc));
10366
10367        let (result_arc, result_layout) =
10368            PipelinedExecutor::realize(graph, p_id, inputs).expect("realize");
10369
10370        assert!(Arc::ptr_eq(&result_arc, &in_arc));
10371        assert_eq!(result_layout.shape().dims(), &[4, 2, 3]);
10372        // Original strides for shape [2, 3, 4] are [12, 4, 1].
10373        // After permute axes [2, 0, 1]: [strides[2], strides[0], strides[1]] = [1, 12, 4].
10374        assert_eq!(result_layout.stride(), &[1, 12, 4]);
10375    }
10376
10377    /// E2E: Const + Cast(f32→f64) — verifies cast through the
10378    /// pipelined executor. Output Storage has the target dtype;
10379    /// bytes encode the widened values.
10380    #[test]
10381    fn pipelined_realize_cast_f32_to_f64() {
10382        let storage = fuel_memory::from_slice_cpu(&[1.5_f32, -2.25, 100.0]);
10383        let graph = Arc::new(RwLock::new(Graph::new()));
10384        let (in_id, c_id) = {
10385            let mut g = graph.write().unwrap();
10386            let in_id = g.push(Node {
10387                op: Op::Const,
10388                inputs: vec![],
10389                shape: Shape::from_dims(&[3]),
10390                dtype: DType::F32,
10391            });
10392            let c_id = g.push(Node {
10393                op: Op::Cast(DType::F64),
10394                inputs: vec![in_id],
10395                shape: Shape::from_dims(&[3]),
10396                dtype: DType::F64,
10397            });
10398            g.set_target_backend(c_id, BackendId::Cpu);
10399            (in_id, c_id)
10400        };
10401        let mut inputs = StorageCache::new();
10402        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10403
10404        let (result_arc, result_layout) =
10405            PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
10406        assert_eq!(result_layout.shape().dims(), &[3]);
10407
10408        let guard = result_arc.read().unwrap();
10409        assert_eq!(guard.dtype, DType::F64);
10410        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10411            panic!("expected Cpu storage");
10412        };
10413        assert_eq!(c.as_slice::<f64>().unwrap(), &[1.5_f64, -2.25, 100.0]);
10414    }
10415
10416    /// E2E: Const + Cast(f32→bf16) + Cast(bf16→f32) — round trip
10417    /// through bf16; verifies the Cast wrapper's source-dtype
10418    /// dispatch (different sources hit different match arms).
10419    /// Inputs chosen to round-trip exactly through bf16.
10420    #[test]
10421    fn pipelined_realize_cast_round_trip_via_bf16() {
10422        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, -3.0, 0.5]);
10423        let graph = Arc::new(RwLock::new(Graph::new()));
10424        let (in_id, c1_id, c2_id) = {
10425            let mut g = graph.write().unwrap();
10426            let in_id = g.push(Node {
10427                op: Op::Const,
10428                inputs: vec![],
10429                shape: Shape::from_dims(&[4]),
10430                dtype: DType::F32,
10431            });
10432            let c1_id = g.push(Node {
10433                op: Op::Cast(DType::BF16),
10434                inputs: vec![in_id],
10435                shape: Shape::from_dims(&[4]),
10436                dtype: DType::BF16,
10437            });
10438            let c2_id = g.push(Node {
10439                op: Op::Cast(DType::F32),
10440                inputs: vec![c1_id],
10441                shape: Shape::from_dims(&[4]),
10442                dtype: DType::F32,
10443            });
10444            g.set_target_backend(c1_id, BackendId::Cpu);
10445            g.set_target_backend(c2_id, BackendId::Cpu);
10446            (in_id, c1_id, c2_id)
10447        };
10448        let _ = c1_id;
10449        let mut inputs = StorageCache::new();
10450        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10451
10452        let (result_arc, _) = PipelinedExecutor::realize(graph, c2_id, inputs).expect("realize");
10453        let guard = result_arc.read().unwrap();
10454        assert_eq!(guard.dtype, DType::F32);
10455        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10456            panic!("expected Cpu storage");
10457        };
10458        assert_eq!(c.as_slice::<f32>().unwrap(), &[1.0_f32, 2.0, -3.0, 0.5]);
10459    }
10460
10461    /// E2E: Const + Slice — slice is metadata-only; the output Arc
10462    /// shares bytes with the input, and the Layout's start_offset
10463    /// + narrowed shape reflect the slice. Stage 3 of Layout-on-Node
10464    ///
10465    /// extended to cover Op::Slice via Layout::narrow.
10466    #[test]
10467    fn pipelined_realize_slice_is_metadata_only() {
10468        // shape [5]; slice dim 0 from index 1 with len 3 → shape [3]
10469        // Source: [10, 20, 30, 40, 50]; slice → [20, 30, 40]
10470        let storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0]);
10471        let graph = Arc::new(RwLock::new(Graph::new()));
10472        let (in_id, s_id) = {
10473            let mut g = graph.write().unwrap();
10474            let in_id = g.push(Node {
10475                op: Op::Const,
10476                inputs: vec![],
10477                shape: Shape::from_dims(&[5]),
10478                dtype: DType::F32,
10479            });
10480            let s_id = g.push(Node {
10481                op: Op::Slice {
10482                    dim: 0,
10483                    start: 1,
10484                    len: 3,
10485                },
10486                inputs: vec![in_id],
10487                shape: Shape::from_dims(&[3]),
10488                dtype: DType::F32,
10489            });
10490            (in_id, s_id)
10491        };
10492        let mut inputs = StorageCache::new();
10493        let in_arc = Arc::new(RwLock::new(storage));
10494        inputs.insert(in_id, Arc::clone(&in_arc));
10495
10496        let (result_arc, result_layout) =
10497            PipelinedExecutor::realize(graph, s_id, inputs).expect("realize");
10498
10499        // Bytes shared with the input.
10500        assert!(Arc::ptr_eq(&result_arc, &in_arc));
10501        assert_eq!(result_layout.shape().dims(), &[3]);
10502        // Slice into a contiguous source: the resulting layout has
10503        // start_offset = original_stride[0] * start = 1 * 1 = 1,
10504        // and stride [1] (still contiguous within the narrowed dim).
10505        assert_eq!(result_layout.start_offset(), 1);
10506        assert_eq!(result_layout.stride(), &[1]);
10507    }
10508
10509    /// E2E: Const + Slice + SumAll — slice is metadata-only, but
10510    /// sum needs contiguous bytes, so auto-Contiguize materializes
10511    /// the slice before reduce. Tests the stage 3+4 integration
10512    /// through Op::Slice. Sum of `[20, 30, 40]` is 90.
10513    #[test]
10514    fn pipelined_realize_slice_then_sum_all() {
10515        let storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0]);
10516        let graph = Arc::new(RwLock::new(Graph::new()));
10517        let (in_id, s_id, sum_id) = {
10518            let mut g = graph.write().unwrap();
10519            let in_id = g.push(Node {
10520                op: Op::Const,
10521                inputs: vec![],
10522                shape: Shape::from_dims(&[5]),
10523                dtype: DType::F32,
10524            });
10525            let s_id = g.push(Node {
10526                op: Op::Slice {
10527                    dim: 0,
10528                    start: 1,
10529                    len: 3,
10530                },
10531                inputs: vec![in_id],
10532                shape: Shape::from_dims(&[3]),
10533                dtype: DType::F32,
10534            });
10535            let sum_id = g.push(Node {
10536                op: Op::SumAll,
10537                inputs: vec![s_id],
10538                shape: Shape::from_dims(&[]),
10539                dtype: DType::F32,
10540            });
10541            g.set_target_backend(sum_id, BackendId::Cpu);
10542            (in_id, s_id, sum_id)
10543        };
10544        let _ = s_id;
10545        let mut inputs = StorageCache::new();
10546        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10547
10548        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
10549        let guard = result_arc.read().unwrap();
10550        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10551            panic!("expected Cpu storage");
10552        };
10553        assert_eq!(c.as_slice::<f32>().unwrap(), &[90.0]);
10554    }
10555
10556    /// E2E: Const + Flip + ReluElementwise — Flip is metadata-only,
10557    /// then a kernel that doesn't yet handle negative strides forces
10558    /// auto-Contiguize to materialize through StridedIndex (which
10559    /// handles signed strides natively). Verifies the post-flip
10560    /// data ordering ([4, 3, 2, 1]) is correctly seen by the kernel.
10561    #[test]
10562    fn pipelined_realize_flip_then_relu_materializes_in_reverse() {
10563        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
10564        let graph = Arc::new(RwLock::new(Graph::new()));
10565        let (in_id, _f_id, r_id) = {
10566            let mut g = graph.write().unwrap();
10567            let in_id = g.push(Node {
10568                op: Op::Const,
10569                inputs: vec![],
10570                shape: Shape::from_dims(&[4]),
10571                dtype: DType::F32,
10572            });
10573            let f_id = g.push(Node {
10574                op: Op::Flip { dim: 0 },
10575                inputs: vec![in_id],
10576                shape: Shape::from_dims(&[4]),
10577                dtype: DType::F32,
10578            });
10579            let r_id = g.push(Node {
10580                op: Op::Relu,
10581                inputs: vec![f_id],
10582                shape: Shape::from_dims(&[4]),
10583                dtype: DType::F32,
10584            });
10585            g.set_target_backend(r_id, BackendId::Cpu);
10586            (in_id, f_id, r_id)
10587        };
10588        let mut inputs = StorageCache::new();
10589        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10590
10591        let (result_arc, result_layout) =
10592            PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
10593        let guard = result_arc.read().unwrap();
10594        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10595            panic!("expected Cpu storage");
10596        };
10597        assert_eq!(c.as_slice::<f32>().unwrap(), &[4.0, 3.0, 2.0, 1.0]);
10598        assert_eq!(result_layout.shape().dims(), &[4]);
10599        assert!(result_layout.is_contiguous(), "relu output is contiguous");
10600    }
10601
10602    /// E2E: Const + BroadcastTo — verifies that broadcast layouts
10603    /// have stride 0 on the broadcast dim while sharing the input's
10604    /// bytes. Stage 3 of Layout-on-Node.
10605    #[test]
10606    fn pipelined_realize_broadcast_is_metadata_only() {
10607        // shape [3]; broadcast to [4, 3] — leading dim is 0-stride
10608        let storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
10609        let graph = Arc::new(RwLock::new(Graph::new()));
10610        let (in_id, b_id) = {
10611            let mut g = graph.write().unwrap();
10612            let in_id = g.push(Node {
10613                op: Op::Const,
10614                inputs: vec![],
10615                shape: Shape::from_dims(&[3]),
10616                dtype: DType::F32,
10617            });
10618            let b_id = g.push(Node {
10619                op: Op::BroadcastTo(Shape::from_dims(&[4, 3])),
10620                inputs: vec![in_id],
10621                shape: Shape::from_dims(&[4, 3]),
10622                dtype: DType::F32,
10623            });
10624            (in_id, b_id)
10625        };
10626        let mut inputs = StorageCache::new();
10627        let in_arc = Arc::new(RwLock::new(storage));
10628        inputs.insert(in_id, Arc::clone(&in_arc));
10629
10630        let (result_arc, result_layout) =
10631            PipelinedExecutor::realize(graph, b_id, inputs).expect("realize");
10632
10633        assert!(Arc::ptr_eq(&result_arc, &in_arc));
10634        assert_eq!(result_layout.shape().dims(), &[4, 3]);
10635        // Broadcasted leading dim has stride 0.
10636        assert_eq!(result_layout.stride(), &[0, 1]);
10637    }
10638
10639    /// E2E: Const + Const + MatMul — exercises rank-2 matmul
10640    /// through the pipelined executor. Inputs are contiguous (no
10641    /// auto-Contiguize needed); the kernel walks them via the
10642    /// (m, n, k) carried in OpParams::Matmul.
10643    #[test]
10644    fn pipelined_realize_matmul_2x3_times_3x2() {
10645        // [[1, 2, 3], [4, 5, 6]] @ [[7, 8], [9, 10], [11, 12]]
10646        //   = [[58, 64], [139, 154]]
10647        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
10648        let rhs_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0, 9.0, 10.0, 11.0, 12.0]);
10649
10650        let graph = Arc::new(RwLock::new(Graph::new()));
10651        let (lhs_id, rhs_id, mm_id) = {
10652            let mut g = graph.write().unwrap();
10653            let lhs = g.push(Node {
10654                op: Op::Const,
10655                inputs: vec![],
10656                shape: Shape::from_dims(&[2, 3]),
10657                dtype: DType::F32,
10658            });
10659            let rhs = g.push(Node {
10660                op: Op::Const,
10661                inputs: vec![],
10662                shape: Shape::from_dims(&[3, 2]),
10663                dtype: DType::F32,
10664            });
10665            let mm = g.push(Node {
10666                op: Op::MatMul,
10667                inputs: vec![lhs, rhs],
10668                shape: Shape::from_dims(&[2, 2]),
10669                dtype: DType::F32,
10670            });
10671            g.set_target_backend(mm, BackendId::Cpu);
10672            (lhs, rhs, mm)
10673        };
10674        let mut inputs = StorageCache::new();
10675        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
10676        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
10677
10678        let (result_arc, result_layout) =
10679            PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
10680        assert_eq!(result_layout.shape().dims(), &[2, 2]);
10681        assert!(result_layout.is_contiguous());
10682
10683        let guard = result_arc.read().unwrap();
10684        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10685            panic!("expected Cpu storage");
10686        };
10687        assert_eq!(c.as_slice::<f32>().unwrap(), &[58.0, 64.0, 139.0, 154.0]);
10688    }
10689
10690    /// E2E: batched matmul through the pipelined executor. Two
10691    /// batches of [2, 2] @ [2, 2]; the kernel iterates over
10692    /// `batch_count` and produces concatenated outputs.
10693    #[test]
10694    fn pipelined_realize_matmul_batched_2x_2x2_times_2x2() {
10695        let lhs_storage = fuel_memory::from_slice_cpu(&[
10696            1.0_f32, 2.0, 3.0, 4.0, // batch 0
10697            1.0, 0.0, 0.0, 1.0, // batch 1 (identity)
10698        ]);
10699        let rhs_storage = fuel_memory::from_slice_cpu(&[
10700            5.0_f32, 6.0, 7.0, 8.0, // batch 0
10701            10.0, 20.0, 30.0, 40.0, // batch 1
10702        ]);
10703
10704        let graph = Arc::new(RwLock::new(Graph::new()));
10705        let (lhs_id, rhs_id, mm_id) = {
10706            let mut g = graph.write().unwrap();
10707            let lhs = g.push(Node {
10708                op: Op::Const,
10709                inputs: vec![],
10710                shape: Shape::from_dims(&[2, 2, 2]),
10711                dtype: DType::F32,
10712            });
10713            let rhs = g.push(Node {
10714                op: Op::Const,
10715                inputs: vec![],
10716                shape: Shape::from_dims(&[2, 2, 2]),
10717                dtype: DType::F32,
10718            });
10719            let mm = g.push(Node {
10720                op: Op::MatMul,
10721                inputs: vec![lhs, rhs],
10722                shape: Shape::from_dims(&[2, 2, 2]),
10723                dtype: DType::F32,
10724            });
10725            g.set_target_backend(mm, BackendId::Cpu);
10726            (lhs, rhs, mm)
10727        };
10728        let mut inputs = StorageCache::new();
10729        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
10730        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
10731
10732        let (result_arc, result_layout) =
10733            PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
10734        assert_eq!(result_layout.shape().dims(), &[2, 2, 2]);
10735        assert!(result_layout.is_contiguous());
10736
10737        let guard = result_arc.read().unwrap();
10738        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10739            panic!("expected Cpu storage");
10740        };
10741        // batch 0: [[1,2],[3,4]] @ [[5,6],[7,8]] = [[19,22],[43,50]]
10742        // batch 1: identity @ [[10,20],[30,40]]   = [[10,20],[30,40]]
10743        assert_eq!(
10744            c.as_slice::<f32>().unwrap(),
10745            &[19.0, 22.0, 43.0, 50.0, 10.0, 20.0, 30.0, 40.0]
10746        );
10747    }
10748
10749    /// E2E: F64 elementwise add through the pipelined executor.
10750    /// Verifies that capability-driven dispatch correctly routes
10751    /// (AddElementwise, F64) to the f64 wrapper/kernel.
10752    #[test]
10753    fn pipelined_realize_add_f64() {
10754        let lhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0]);
10755        let rhs = fuel_memory::from_slice_cpu(&[10.0_f64, 20.0, 30.0]);
10756        let graph = Arc::new(RwLock::new(Graph::new()));
10757        let (l_id, r_id, op_id) = {
10758            let mut g = graph.write().unwrap();
10759            let l = g.push(Node {
10760                op: Op::Const,
10761                inputs: vec![],
10762                shape: Shape::from_dims(&[3]),
10763                dtype: DType::F64,
10764            });
10765            let r = g.push(Node {
10766                op: Op::Const,
10767                inputs: vec![],
10768                shape: Shape::from_dims(&[3]),
10769                dtype: DType::F64,
10770            });
10771            let op = g.push(Node {
10772                op: Op::Add,
10773                inputs: vec![l, r],
10774                shape: Shape::from_dims(&[3]),
10775                dtype: DType::F64,
10776            });
10777            g.set_target_backend(op, BackendId::Cpu);
10778            (l, r, op)
10779        };
10780        let mut inputs = StorageCache::new();
10781        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10782        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10783        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
10784        let guard = result_arc.read().unwrap();
10785        assert_eq!(guard.dtype, DType::F64);
10786        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10787            panic!("expected Cpu storage");
10788        };
10789        assert_eq!(c.as_slice::<f64>().unwrap(), &[11.0_f64, 22.0, 33.0]);
10790    }
10791
10792    /// E2E: Op::Equal F32 → Bool mask through the pipelined executor (GAP-168c).
10793    /// Verifies (a) the binding-table key `(EqualElementwise, [F32, F32, U8],
10794    /// Cpu)` resolves, (b) the executor allocates a U8-sized output
10795    /// buffer (1 byte per element, not 4), (c) the kernel writes the
10796    /// expected mask bits including IEEE-754 NaN handling
10797    /// (`NaN == NaN` is false).
10798    #[test]
10799    fn pipelined_realize_eq_f32_to_bool_mask() {
10800        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, f32::NAN, 0.0]);
10801        let rhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -0.0]);
10802        let graph = Arc::new(RwLock::new(Graph::new()));
10803        let (l_id, r_id, eq_id) = {
10804            let mut g = graph.write().unwrap();
10805            let l = g.push(Node {
10806                op: Op::Const,
10807                inputs: vec![],
10808                shape: Shape::from_dims(&[5]),
10809                dtype: DType::F32,
10810            });
10811            let r = g.push(Node {
10812                op: Op::Const,
10813                inputs: vec![],
10814                shape: Shape::from_dims(&[5]),
10815                dtype: DType::F32,
10816            });
10817            let eq = g.push(Node {
10818                op: Op::Equal,
10819                inputs: vec![l, r],
10820                shape: Shape::from_dims(&[5]),
10821                dtype: DType::Bool,
10822            });
10823            g.set_target_backend(eq, BackendId::Cpu);
10824            (l, r, eq)
10825        };
10826        let mut inputs = StorageCache::new();
10827        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10828        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10829        let (result_arc, _) = PipelinedExecutor::realize(graph, eq_id, inputs).expect("realize");
10830        let guard = result_arc.read().unwrap();
10831        assert_eq!(guard.dtype, DType::Bool);
10832        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10833            panic!("expected Cpu storage");
10834        };
10835        let mask: &[u8] = c.as_slice().expect("u8 view");
10836        // Index 0: 1.0 == 1.0 → 1.
10837        // Index 1: 2.0 != 5.0 → 0.
10838        // Index 2: 3.0 == 3.0 → 1.
10839        // Index 3: NaN == NaN → 0 (IEEE-754).
10840        // Index 4: 0.0 == -0.0 → 1 (IEEE-754 zero equality).
10841        assert_eq!(mask, &[1, 0, 1, 0, 1]);
10842    }
10843
10844    /// E2E: Op::Ne F32 → Bool mask. Mirrors the Eq F32 test with
10845    /// inverted predicate; NaN-vs-NaN slot now yields `1` (since
10846    /// `NaN != NaN` per IEEE-754).
10847    #[test]
10848    fn pipelined_realize_ne_f32_to_bool_mask() {
10849        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, f32::NAN, 0.0]);
10850        let rhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -0.0]);
10851        let graph = Arc::new(RwLock::new(Graph::new()));
10852        let (l_id, r_id, ne_id) = {
10853            let mut g = graph.write().unwrap();
10854            let l = g.push(Node {
10855                op: Op::Const,
10856                inputs: vec![],
10857                shape: Shape::from_dims(&[5]),
10858                dtype: DType::F32,
10859            });
10860            let r = g.push(Node {
10861                op: Op::Const,
10862                inputs: vec![],
10863                shape: Shape::from_dims(&[5]),
10864                dtype: DType::F32,
10865            });
10866            let ne = g.push(Node {
10867                op: Op::Ne,
10868                inputs: vec![l, r],
10869                shape: Shape::from_dims(&[5]),
10870                dtype: DType::Bool,
10871            });
10872            g.set_target_backend(ne, BackendId::Cpu);
10873            (l, r, ne)
10874        };
10875        let mut inputs = StorageCache::new();
10876        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10877        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10878        let (result_arc, _) = PipelinedExecutor::realize(graph, ne_id, inputs).expect("realize");
10879        let guard = result_arc.read().unwrap();
10880        assert_eq!(guard.dtype, DType::Bool);
10881        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10882            panic!("expected Cpu storage");
10883        };
10884        let mask: &[u8] = c.as_slice().expect("u8 view");
10885        // Inverse of the Eq test:
10886        // 1.0 != 1.0 → 0;  2.0 != 5.0 → 1;  3.0 != 3.0 → 0;
10887        // NaN != NaN → 1 (IEEE-754);  0.0 != -0.0 → 0 (IEEE-754).
10888        assert_eq!(mask, &[0, 1, 0, 1, 0]);
10889    }
10890
10891    /// E2E: Op::Lt F32 → Bool mask. Confirms strict-less-than semantics
10892    /// + IEEE-754 NaN handling (any comparison with NaN is unordered →
10893    ///
10894    /// `0`).
10895    #[test]
10896    fn pipelined_realize_lt_f32_to_bool_mask() {
10897        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -1.0]);
10898        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 3.0, 0.0, 0.0]);
10899        let graph = Arc::new(RwLock::new(Graph::new()));
10900        let (l_id, r_id, lt_id) = {
10901            let mut g = graph.write().unwrap();
10902            let l = g.push(Node {
10903                op: Op::Const,
10904                inputs: vec![],
10905                shape: Shape::from_dims(&[5]),
10906                dtype: DType::F32,
10907            });
10908            let r = g.push(Node {
10909                op: Op::Const,
10910                inputs: vec![],
10911                shape: Shape::from_dims(&[5]),
10912                dtype: DType::F32,
10913            });
10914            let lt = g.push(Node {
10915                op: Op::Lt,
10916                inputs: vec![l, r],
10917                shape: Shape::from_dims(&[5]),
10918                dtype: DType::Bool,
10919            });
10920            g.set_target_backend(lt, BackendId::Cpu);
10921            (l, r, lt)
10922        };
10923        let mut inputs = StorageCache::new();
10924        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10925        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10926        let (result_arc, _) = PipelinedExecutor::realize(graph, lt_id, inputs).expect("realize");
10927        let guard = result_arc.read().unwrap();
10928        assert_eq!(guard.dtype, DType::Bool);
10929        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10930            panic!("expected Cpu storage");
10931        };
10932        let mask: &[u8] = c.as_slice().expect("u8 view");
10933        // 1.0 < 2.0 → 1;  5.0 < 5.0 → 0 (strict);  3.0 < 3.0 → 0;
10934        // NaN < 0.0 → 0 (unordered);  -1.0 < 0.0 → 1.
10935        assert_eq!(mask, &[1, 0, 0, 0, 1]);
10936    }
10937
10938    /// E2E: Op::Le F32 → Bool mask. Distinct from Lt at the equal slot
10939    /// (`5.0 <= 5.0` = 1, vs Lt's `5.0 < 5.0` = 0). NaN unordered → 0.
10940    #[test]
10941    fn pipelined_realize_le_f32_to_bool_mask() {
10942        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -1.0]);
10943        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 2.0, 0.0, 0.0]);
10944        let graph = Arc::new(RwLock::new(Graph::new()));
10945        let (l_id, r_id, le_id) = {
10946            let mut g = graph.write().unwrap();
10947            let l = g.push(Node {
10948                op: Op::Const,
10949                inputs: vec![],
10950                shape: Shape::from_dims(&[5]),
10951                dtype: DType::F32,
10952            });
10953            let r = g.push(Node {
10954                op: Op::Const,
10955                inputs: vec![],
10956                shape: Shape::from_dims(&[5]),
10957                dtype: DType::F32,
10958            });
10959            let le = g.push(Node {
10960                op: Op::Le,
10961                inputs: vec![l, r],
10962                shape: Shape::from_dims(&[5]),
10963                dtype: DType::Bool,
10964            });
10965            g.set_target_backend(le, BackendId::Cpu);
10966            (l, r, le)
10967        };
10968        let mut inputs = StorageCache::new();
10969        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10970        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10971        let (result_arc, _) = PipelinedExecutor::realize(graph, le_id, inputs).expect("realize");
10972        let guard = result_arc.read().unwrap();
10973        assert_eq!(guard.dtype, DType::Bool);
10974        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10975            panic!("expected Cpu storage");
10976        };
10977        let mask: &[u8] = c.as_slice().expect("u8 view");
10978        // 1.0 <= 2.0 → 1;  5.0 <= 5.0 → 1 (key Lt difference);
10979        // 3.0 <= 2.0 → 0;  NaN <= 0.0 → 0 (unordered);  -1.0 <= 0.0 → 1.
10980        assert_eq!(mask, &[1, 1, 0, 0, 1]);
10981    }
10982
10983    /// E2E: Op::Gt F32 → Bool mask. Strict-greater: equality slot is
10984    /// `0`. NaN unordered → `0`.
10985    #[test]
10986    fn pipelined_realize_gt_f32_to_bool_mask() {
10987        let lhs = fuel_memory::from_slice_cpu(&[3.0_f32, 5.0, 2.0, f32::NAN, 1.0]);
10988        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 3.0, 0.0, 0.0]);
10989        let graph = Arc::new(RwLock::new(Graph::new()));
10990        let (l_id, r_id, gt_id) = {
10991            let mut g = graph.write().unwrap();
10992            let l = g.push(Node {
10993                op: Op::Const,
10994                inputs: vec![],
10995                shape: Shape::from_dims(&[5]),
10996                dtype: DType::F32,
10997            });
10998            let r = g.push(Node {
10999                op: Op::Const,
11000                inputs: vec![],
11001                shape: Shape::from_dims(&[5]),
11002                dtype: DType::F32,
11003            });
11004            let gt = g.push(Node {
11005                op: Op::Gt,
11006                inputs: vec![l, r],
11007                shape: Shape::from_dims(&[5]),
11008                dtype: DType::Bool,
11009            });
11010            g.set_target_backend(gt, BackendId::Cpu);
11011            (l, r, gt)
11012        };
11013        let mut inputs = StorageCache::new();
11014        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11015        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11016        let (result_arc, _) = PipelinedExecutor::realize(graph, gt_id, inputs).expect("realize");
11017        let guard = result_arc.read().unwrap();
11018        assert_eq!(guard.dtype, DType::Bool);
11019        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11020            panic!("expected Cpu storage");
11021        };
11022        let mask: &[u8] = c.as_slice().expect("u8 view");
11023        // 3.0 > 2.0 → 1;  5.0 > 5.0 → 0 (strict);  2.0 > 3.0 → 0;
11024        // NaN > 0.0 → 0 (unordered);  1.0 > 0.0 → 1.
11025        assert_eq!(mask, &[1, 0, 0, 0, 1]);
11026    }
11027
11028    /// E2E: Op::Ge F32 → Bool mask. Greater-or-equal: equality slot
11029    /// is `1` (distinguishes from Gt). NaN unordered → `0`. Closes
11030    /// the comparison family with full `[Eq, Ne, Lt, Le, Gt, Ge]`
11031    /// coverage.
11032    #[test]
11033    fn pipelined_realize_ge_f32_to_bool_mask() {
11034        let lhs = fuel_memory::from_slice_cpu(&[3.0_f32, 5.0, 2.0, f32::NAN, 0.0]);
11035        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 3.0, 0.0, 0.0]);
11036        let graph = Arc::new(RwLock::new(Graph::new()));
11037        let (l_id, r_id, ge_id) = {
11038            let mut g = graph.write().unwrap();
11039            let l = g.push(Node {
11040                op: Op::Const,
11041                inputs: vec![],
11042                shape: Shape::from_dims(&[5]),
11043                dtype: DType::F32,
11044            });
11045            let r = g.push(Node {
11046                op: Op::Const,
11047                inputs: vec![],
11048                shape: Shape::from_dims(&[5]),
11049                dtype: DType::F32,
11050            });
11051            let ge = g.push(Node {
11052                op: Op::Ge,
11053                inputs: vec![l, r],
11054                shape: Shape::from_dims(&[5]),
11055                dtype: DType::Bool,
11056            });
11057            g.set_target_backend(ge, BackendId::Cpu);
11058            (l, r, ge)
11059        };
11060        let mut inputs = StorageCache::new();
11061        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11062        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11063        let (result_arc, _) = PipelinedExecutor::realize(graph, ge_id, inputs).expect("realize");
11064        let guard = result_arc.read().unwrap();
11065        assert_eq!(guard.dtype, DType::Bool);
11066        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11067            panic!("expected Cpu storage");
11068        };
11069        let mask: &[u8] = c.as_slice().expect("u8 view");
11070        // 3.0 >= 2.0 → 1;  5.0 >= 5.0 → 1 (key Gt difference);
11071        // 2.0 >= 3.0 → 0;  NaN >= 0.0 → 0 (unordered);  0.0 >= 0.0 → 1.
11072        assert_eq!(mask, &[1, 1, 0, 0, 1]);
11073    }
11074
11075    /// E2E: Op::Equal F64 → Bool mask. Confirms the F64 wrapper is
11076    /// independently registered and routed (binding-table key
11077    /// `(EqualElementwise, [F64, F64, U8], Cpu)`).
11078    #[test]
11079    fn pipelined_realize_eq_f64_to_bool_mask() {
11080        let lhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0]);
11081        let rhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 4.0]);
11082        let graph = Arc::new(RwLock::new(Graph::new()));
11083        let (l_id, r_id, eq_id) = {
11084            let mut g = graph.write().unwrap();
11085            let l = g.push(Node {
11086                op: Op::Const,
11087                inputs: vec![],
11088                shape: Shape::from_dims(&[3]),
11089                dtype: DType::F64,
11090            });
11091            let r = g.push(Node {
11092                op: Op::Const,
11093                inputs: vec![],
11094                shape: Shape::from_dims(&[3]),
11095                dtype: DType::F64,
11096            });
11097            let eq = g.push(Node {
11098                op: Op::Equal,
11099                inputs: vec![l, r],
11100                shape: Shape::from_dims(&[3]),
11101                dtype: DType::Bool,
11102            });
11103            g.set_target_backend(eq, BackendId::Cpu);
11104            (l, r, eq)
11105        };
11106        let mut inputs = StorageCache::new();
11107        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11108        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11109        let (result_arc, _) = PipelinedExecutor::realize(graph, eq_id, inputs).expect("realize");
11110        let guard = result_arc.read().unwrap();
11111        assert_eq!(guard.dtype, DType::Bool);
11112        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11113            panic!("expected Cpu storage");
11114        };
11115        let mask: &[u8] = c.as_slice().expect("u8 view");
11116        assert_eq!(mask, &[1, 1, 0]);
11117    }
11118
11119    /// E2E: Op::Where ternary select — `out[i] = if cond[i] != 0 { a[i] } else { b[i] }`.
11120    /// Validates (a) the binding-table key `(Where, [Bool, F32, F32, F32], Cpu)`
11121    /// resolves to the where_f32 wrapper, (b) the Bool cond input drives
11122    /// the per-slot pick, (c) outputs preserve the input dtype.
11123    ///
11124    /// GAP-168(c): the cond STORAGE is tagged Bool, not merely the graph node.
11125    /// Bool and U8 are byte-identical, so leaving the storage U8 under a Bool
11126    /// node is exactly the mismatch this cut exists to make visible.
11127    #[test]
11128    fn pipelined_realize_where_f32_picks_per_slot_from_bool_mask() {
11129        // cond = [1, 0, 1, 0, 1]; a = [1, 2, 3, 4, 5]; b = [10, 20, 30, 40, 50]
11130        // expected = [1, 20, 3, 40, 5]
11131        let mut cond_storage = fuel_memory::from_slice_cpu(&[1u8, 0, 1, 0, 1]);
11132        cond_storage.dtype = DType::Bool; // GAP-168(c): a Bool mask, not U8 bytes
11133        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0]);
11134        let b_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0]);
11135        let graph = Arc::new(RwLock::new(Graph::new()));
11136        let (cond_id, a_id, b_id, where_id) = {
11137            let mut g = graph.write().unwrap();
11138            let cond = g.push(Node {
11139                op: Op::Const,
11140                inputs: vec![],
11141                shape: Shape::from_dims(&[5]),
11142                dtype: DType::Bool,
11143            });
11144            let a = g.push(Node {
11145                op: Op::Const,
11146                inputs: vec![],
11147                shape: Shape::from_dims(&[5]),
11148                dtype: DType::F32,
11149            });
11150            let b = g.push(Node {
11151                op: Op::Const,
11152                inputs: vec![],
11153                shape: Shape::from_dims(&[5]),
11154                dtype: DType::F32,
11155            });
11156            let w = g.push(Node {
11157                op: Op::Where,
11158                inputs: vec![cond, a, b],
11159                shape: Shape::from_dims(&[5]),
11160                dtype: DType::F32,
11161            });
11162            g.set_target_backend(w, BackendId::Cpu);
11163            (cond, a, b, w)
11164        };
11165        let mut inputs = StorageCache::new();
11166        inputs.insert(cond_id, Arc::new(RwLock::new(cond_storage)));
11167        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
11168        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
11169        let (result_arc, _) = PipelinedExecutor::realize(graph, where_id, inputs).expect("realize");
11170        let guard = result_arc.read().unwrap();
11171        assert_eq!(guard.dtype, DType::F32);
11172        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11173            panic!("expected Cpu storage");
11174        };
11175        let out: &[f32] = c.as_slice().expect("f32 view");
11176        assert_eq!(out, &[1.0, 20.0, 3.0, 40.0, 5.0]);
11177    }
11178
11179    /// E2E: full chain `eq → where`. Compares two f32 vectors, then
11180    /// uses the resulting Bool mask to pick from a third tensor (or a
11181    /// fallback). Validates the comparison-family + Where ops compose
11182    /// end-to-end.
11183    #[test]
11184    fn pipelined_realize_eq_then_where_full_chain() {
11185        // a = [1, 2, 3]; b = [1, 5, 3] → eq = [1, 0, 1]
11186        // pick = [10, 20, 30]; fallback = [99, 99, 99]
11187        // result = [10, 99, 30]
11188        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
11189        let b_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0]);
11190        let pick_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
11191        let fb_storage = fuel_memory::from_slice_cpu(&[99.0_f32, 99.0, 99.0]);
11192        let graph = Arc::new(RwLock::new(Graph::new()));
11193        let (a_id, b_id, pick_id, fb_id, where_id) = {
11194            let mut g = graph.write().unwrap();
11195            let a = g.push(Node {
11196                op: Op::Const,
11197                inputs: vec![],
11198                shape: Shape::from_dims(&[3]),
11199                dtype: DType::F32,
11200            });
11201            let b = g.push(Node {
11202                op: Op::Const,
11203                inputs: vec![],
11204                shape: Shape::from_dims(&[3]),
11205                dtype: DType::F32,
11206            });
11207            let pick = g.push(Node {
11208                op: Op::Const,
11209                inputs: vec![],
11210                shape: Shape::from_dims(&[3]),
11211                dtype: DType::F32,
11212            });
11213            let fb = g.push(Node {
11214                op: Op::Const,
11215                inputs: vec![],
11216                shape: Shape::from_dims(&[3]),
11217                dtype: DType::F32,
11218            });
11219            let eq = g.push(Node {
11220                op: Op::Equal,
11221                inputs: vec![a, b],
11222                shape: Shape::from_dims(&[3]),
11223                dtype: DType::Bool,
11224            });
11225            let w = g.push(Node {
11226                op: Op::Where,
11227                inputs: vec![eq, pick, fb],
11228                shape: Shape::from_dims(&[3]),
11229                dtype: DType::F32,
11230            });
11231            g.set_target_backend(eq, BackendId::Cpu);
11232            g.set_target_backend(w, BackendId::Cpu);
11233            (a, b, pick, fb, w)
11234        };
11235        let mut inputs = StorageCache::new();
11236        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
11237        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
11238        inputs.insert(pick_id, Arc::new(RwLock::new(pick_storage)));
11239        inputs.insert(fb_id, Arc::new(RwLock::new(fb_storage)));
11240        let (result_arc, _) = PipelinedExecutor::realize(graph, where_id, inputs).expect("realize");
11241        let guard = result_arc.read().unwrap();
11242        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11243            panic!("expected Cpu storage");
11244        };
11245        let out: &[f32] = c.as_slice().expect("f32 view");
11246        assert_eq!(out, &[10.0, 99.0, 30.0]);
11247    }
11248
11249    /// E2E: Q4_0 QMatMul through the pipelined executor — proves
11250    /// quantized weights can flow into the unified path. Activations
11251    /// are F32, weights are U32-typed (raw block bytes).
11252    /// Construct a Q4_0 weight tensor where every weight = 1.0
11253    /// (d=1.0, every nibble=9 → 1*(9-8)=1), so A @ W^T computes
11254    /// the per-row sum of activations.
11255    #[test]
11256    fn pipelined_realize_qmatmul_q4_0_unit_weight_sums_activations() {
11257        use fuel_graph::QuantType;
11258        use half::f16;
11259        let block_size = std::mem::size_of::<fuel_quantized::BlockQ4_0>();
11260        let mut w_bytes = vec![0u8; 2 * block_size];
11261        for block_idx in 0..2 {
11262            let off = block_idx * block_size;
11263            let d_bytes = f16::from_f32(1.0).to_le_bytes();
11264            w_bytes[off..off + 2].copy_from_slice(&d_bytes);
11265            for i in 0..16 {
11266                w_bytes[off + 2 + i] = 0x99;
11267            }
11268        }
11269        // Weight tensor is U32-typed (rank-1, length = bytes/4)
11270        let w_storage = fuel_memory::Storage::new(
11271            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
11272                &w_bytes,
11273            )),
11274            DType::U32,
11275        );
11276
11277        let act_vec: Vec<f32> = (1..=32).map(|x| x as f32).collect();
11278        let act_storage = fuel_memory::from_slice_cpu(&act_vec);
11279
11280        let graph = Arc::new(RwLock::new(Graph::new()));
11281        let (act_id, w_id, mm_id) = {
11282            let mut g = graph.write().unwrap();
11283            let act = g.push(Node {
11284                op: Op::Const,
11285                inputs: vec![],
11286                shape: Shape::from_dims(&[1, 32]),
11287                dtype: DType::F32,
11288            });
11289            let w = g.push(Node {
11290                op: Op::Const,
11291                inputs: vec![],
11292                shape: Shape::from_dims(&[w_bytes.len() / 4]),
11293                dtype: DType::U32,
11294            });
11295            let mm = g.push(Node {
11296                op: Op::Fused(
11297                    fuel_graph::registry::FusedOps::QMATMUL,
11298                    fuel_graph::registry::FusedOpParams::QMatMul {
11299                        quant_type: QuantType::Q4_0,
11300                        k: 32,
11301                        n: 2,
11302                    },
11303                ),
11304                inputs: vec![act, w],
11305                shape: Shape::from_dims(&[1, 2]),
11306                dtype: DType::F32,
11307            });
11308            g.set_target_backend(mm, BackendId::Cpu);
11309            (act, w, mm)
11310        };
11311        let mut inputs = StorageCache::new();
11312        inputs.insert(act_id, Arc::new(RwLock::new(act_storage)));
11313        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
11314        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11315        let guard = result_arc.read().unwrap();
11316        assert_eq!(guard.dtype, DType::F32);
11317        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11318            panic!("expected Cpu storage");
11319        };
11320        let r: &[f32] = c.as_slice().unwrap();
11321        // Both rows = sum(1..=32) = 528, within Q8_1 round-trip
11322        // tolerance.
11323        assert!((r[0] - 528.0).abs() < 0.5, "got {}, want 528", r[0]);
11324        assert!((r[1] - 528.0).abs() < 0.5, "got {}, want 528", r[1]);
11325    }
11326
11327    /// E2E: QMatMul with Q5_0 weights — verifies the new quant
11328    /// dispatch arm picks `qmatmul_q5_0_f32`. We build weights by
11329    /// quantizing all-ones via `BlockQ5_0::from_float`, then
11330    /// compare pipelined output against the direct fuel_quantized
11331    /// matmul on the same blocks.
11332    #[test]
11333    fn pipelined_realize_qmatmul_q5_0_against_reference() {
11334        use fuel_graph::QuantType;
11335        use fuel_quantized::{BlockQ5_0, GgmlType};
11336        let n = 2;
11337        let k = 64; // 2 blocks per row
11338        // Quantize an all-ones [n, k] weight matrix.
11339        let w_f32 = vec![1.0_f32; n * k];
11340        let blocks_per_row = k / BlockQ5_0::BLCK_SIZE;
11341        let mut w_blocks = vec![BlockQ5_0::zeros(); n * blocks_per_row];
11342        BlockQ5_0::from_float(&w_f32, &mut w_blocks);
11343        // Reinterpret block slice as bytes (BlockQ5_0 is #[repr(C)]).
11344        let bytes_per_block = std::mem::size_of::<BlockQ5_0>();
11345        let w_bytes: Vec<u8> = unsafe {
11346            std::slice::from_raw_parts(
11347                w_blocks.as_ptr() as *const u8,
11348                w_blocks.len() * bytes_per_block,
11349            )
11350        }
11351        .to_vec();
11352        let w_storage = fuel_memory::Storage::new(
11353            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
11354                &w_bytes,
11355            )),
11356            DType::U32,
11357        );
11358        let act_vec: Vec<f32> = (1..=k).map(|x| x as f32).collect();
11359        let act_storage = fuel_memory::from_slice_cpu(&act_vec);
11360        // Reference: direct matmul through fuel_quantized.
11361        let mut ref_out = vec![0.0_f32; n];
11362        fuel_quantized::matmul::<BlockQ5_0>((1, k, n), &act_vec, &w_blocks, &mut ref_out)
11363            .expect("ref matmul");
11364
11365        let graph = Arc::new(RwLock::new(Graph::new()));
11366        let (act_id, w_id, mm_id) = {
11367            let mut g = graph.write().unwrap();
11368            let act = g.push(Node {
11369                op: Op::Const,
11370                inputs: vec![],
11371                shape: Shape::from_dims(&[1, k]),
11372                dtype: DType::F32,
11373            });
11374            let w = g.push(Node {
11375                op: Op::Const,
11376                inputs: vec![],
11377                shape: Shape::from_dims(&[w_bytes.len() / 4]),
11378                dtype: DType::U32,
11379            });
11380            let mm = g.push(Node {
11381                op: Op::Fused(
11382                    fuel_graph::registry::FusedOps::QMATMUL,
11383                    fuel_graph::registry::FusedOpParams::QMatMul {
11384                        quant_type: QuantType::Q5_0,
11385                        k,
11386                        n,
11387                    },
11388                ),
11389                inputs: vec![act, w],
11390                shape: Shape::from_dims(&[1, n]),
11391                dtype: DType::F32,
11392            });
11393            g.set_target_backend(mm, BackendId::Cpu);
11394            (act, w, mm)
11395        };
11396        let mut inputs = StorageCache::new();
11397        inputs.insert(act_id, Arc::new(RwLock::new(act_storage)));
11398        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
11399        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11400        let guard = result_arc.read().unwrap();
11401        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11402            panic!("expected Cpu storage");
11403        };
11404        let r: &[f32] = c.as_slice().unwrap();
11405        // Bit-exact against same kernel via the trait, since both
11406        // paths run fuel_quantized::matmul<BlockQ5_0>.
11407        assert_eq!(
11408            r,
11409            ref_out.as_slice(),
11410            "pipelined Q5_0 differs from reference: got {r:?}, want {ref_out:?}"
11411        );
11412    }
11413
11414    /// E2E: QMatMul with Q6K (256-element super-block k-quant).
11415    /// Same idea as the Q5_0 test — bit-exact against the
11416    /// reference fuel_quantized::matmul<BlockQ6K>. Confirms the
11417    /// dispatch arm wires `qmatmul_q6k_f32` correctly.
11418    #[test]
11419    fn pipelined_realize_qmatmul_q6k_against_reference() {
11420        use fuel_graph::QuantType;
11421        use fuel_quantized::{BlockQ6K, GgmlType};
11422        let n = 2;
11423        let k = 256; // 1 super-block per row
11424        let w_f32 = vec![1.0_f32; n * k];
11425        let blocks_per_row = k / BlockQ6K::BLCK_SIZE;
11426        let mut w_blocks = vec![BlockQ6K::zeros(); n * blocks_per_row];
11427        BlockQ6K::from_float(&w_f32, &mut w_blocks);
11428        let bytes_per_block = std::mem::size_of::<BlockQ6K>();
11429        let w_bytes: Vec<u8> = unsafe {
11430            std::slice::from_raw_parts(
11431                w_blocks.as_ptr() as *const u8,
11432                w_blocks.len() * bytes_per_block,
11433            )
11434        }
11435        .to_vec();
11436        let w_storage = fuel_memory::Storage::new(
11437            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
11438                &w_bytes,
11439            )),
11440            DType::U32,
11441        );
11442        let act_vec: Vec<f32> = (1..=k).map(|x| x as f32 / 100.0).collect();
11443        let act_storage = fuel_memory::from_slice_cpu(&act_vec);
11444        let mut ref_out = vec![0.0_f32; n];
11445        fuel_quantized::matmul::<BlockQ6K>((1, k, n), &act_vec, &w_blocks, &mut ref_out)
11446            .expect("ref matmul");
11447
11448        let graph = Arc::new(RwLock::new(Graph::new()));
11449        let (act_id, w_id, mm_id) = {
11450            let mut g = graph.write().unwrap();
11451            let act = g.push(Node {
11452                op: Op::Const,
11453                inputs: vec![],
11454                shape: Shape::from_dims(&[1, k]),
11455                dtype: DType::F32,
11456            });
11457            let w = g.push(Node {
11458                op: Op::Const,
11459                inputs: vec![],
11460                shape: Shape::from_dims(&[w_bytes.len() / 4]),
11461                dtype: DType::U32,
11462            });
11463            let mm = g.push(Node {
11464                op: Op::Fused(
11465                    fuel_graph::registry::FusedOps::QMATMUL,
11466                    fuel_graph::registry::FusedOpParams::QMatMul {
11467                        quant_type: QuantType::Q6K,
11468                        k,
11469                        n,
11470                    },
11471                ),
11472                inputs: vec![act, w],
11473                shape: Shape::from_dims(&[1, n]),
11474                dtype: DType::F32,
11475            });
11476            g.set_target_backend(mm, BackendId::Cpu);
11477            (act, w, mm)
11478        };
11479        let mut inputs = StorageCache::new();
11480        inputs.insert(act_id, Arc::new(RwLock::new(act_storage)));
11481        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
11482        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11483        let guard = result_arc.read().unwrap();
11484        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11485            panic!("expected Cpu storage");
11486        };
11487        let r: &[f32] = c.as_slice().unwrap();
11488        assert_eq!(
11489            r,
11490            ref_out.as_slice(),
11491            "pipelined Q6K differs from reference: got {r:?}, want {ref_out:?}"
11492        );
11493    }
11494
11495    /// E2E: BF16 RmsNormLastDim through the pipelined executor.
11496    /// Verifies that capability-driven dispatch routes the
11497    /// half-float norm op to the bf16-specific kernel (which
11498    /// accumulates in f32 internally).
11499    #[test]
11500    fn pipelined_realize_rms_norm_bf16() {
11501        let v: Vec<half::bf16> = [3.0_f32, 4.0]
11502            .iter()
11503            .map(|&x| half::bf16::from_f32(x))
11504            .collect();
11505        let storage = fuel_memory::from_slice_cpu(&v);
11506        let graph = Arc::new(RwLock::new(Graph::new()));
11507        let (in_id, op_id) = {
11508            let mut g = graph.write().unwrap();
11509            let in_id = g.push(Node {
11510                op: Op::Const,
11511                inputs: vec![],
11512                shape: Shape::from_dims(&[1, 2]),
11513                dtype: DType::BF16,
11514            });
11515            let op_id = g.push(Node {
11516                op: Op::Fused(
11517                    fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM,
11518                    fuel_graph::registry::FusedOpParams::RmsNormLastDim { eps: 0.0 },
11519                ),
11520                inputs: vec![in_id],
11521                shape: Shape::from_dims(&[1, 2]),
11522                dtype: DType::BF16,
11523            });
11524            g.set_target_backend(op_id, BackendId::Cpu);
11525            (in_id, op_id)
11526        };
11527        let mut inputs = StorageCache::new();
11528        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11529        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
11530        let guard = result_arc.read().unwrap();
11531        assert_eq!(guard.dtype, DType::BF16);
11532        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11533            panic!("expected Cpu storage");
11534        };
11535        let r: &[half::bf16] = c.as_slice().unwrap();
11536        let rms = (12.5_f32).sqrt();
11537        // bf16's ~3-digit mantissa absorbs the divisor; allow ~5%.
11538        assert!((r[0].to_f32() - 3.0 / rms).abs() < 0.05);
11539        assert!((r[1].to_f32() - 4.0 / rms).abs() < 0.05);
11540    }
11541
11542    /// E2E: BF16 matmul through the pipelined executor — proves
11543    /// the LLM forward-pass blocker (every transformer layer
11544    /// is dominated by matmul). Identity matmul on bf16 round-
11545    /// trips small integers exactly.
11546    #[test]
11547    fn pipelined_realize_matmul_bf16_identity() {
11548        let lhs_v: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0]
11549            .iter()
11550            .map(|&x| half::bf16::from_f32(x))
11551            .collect();
11552        let rhs_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0]
11553            .iter()
11554            .map(|&x| half::bf16::from_f32(x))
11555            .collect();
11556        let lhs = fuel_memory::from_slice_cpu(&lhs_v);
11557        let rhs = fuel_memory::from_slice_cpu(&rhs_v);
11558        let graph = Arc::new(RwLock::new(Graph::new()));
11559        let (l_id, r_id, mm_id) = {
11560            let mut g = graph.write().unwrap();
11561            let l = g.push(Node {
11562                op: Op::Const,
11563                inputs: vec![],
11564                shape: Shape::from_dims(&[2, 2]),
11565                dtype: DType::BF16,
11566            });
11567            let r = g.push(Node {
11568                op: Op::Const,
11569                inputs: vec![],
11570                shape: Shape::from_dims(&[2, 2]),
11571                dtype: DType::BF16,
11572            });
11573            let mm = g.push(Node {
11574                op: Op::MatMul,
11575                inputs: vec![l, r],
11576                shape: Shape::from_dims(&[2, 2]),
11577                dtype: DType::BF16,
11578            });
11579            g.set_target_backend(mm, BackendId::Cpu);
11580            (l, r, mm)
11581        };
11582        let mut inputs = StorageCache::new();
11583        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11584        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11585        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11586        let guard = result_arc.read().unwrap();
11587        assert_eq!(guard.dtype, DType::BF16);
11588        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11589            panic!("expected Cpu storage");
11590        };
11591        let r: &[half::bf16] = c.as_slice().unwrap();
11592        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
11593        assert_eq!(result_f32, vec![1.0, 2.0, 3.0, 4.0]);
11594    }
11595
11596    /// E2E (ROADMAP row 34): a mixed `[F32, W, F32]` matmul (f32 activation, half weight) runs on
11597    /// the CPU through the NATIVE kernel, with the weight left half-width: the output is f32 and
11598    /// equals the f64 matmul over the widened weights to f32 accumulation error. The weight is
11599    /// rounded to its stored half type first.
11600    fn mixed_cpu_matmul_matches_f64(weight_dtype: DType) {
11601        let (m, n, k) = (3_usize, 5_usize, 7_usize);
11602        let a: Vec<f32> = (0..m * k)
11603            .map(|i| ((i * 37 % 19) as f32 - 9.0) / 8.0)
11604            .collect();
11605        let w_f32: Vec<f32> = (0..k * n)
11606            .map(|i| ((i * 53 % 23) as f32 - 11.0) / 10.0)
11607            .collect();
11608        let (w_storage, widened): (_, Vec<f32>) = if weight_dtype == DType::BF16 {
11609            let h: Vec<half::bf16> = w_f32.iter().map(|&x| half::bf16::from_f32(x)).collect();
11610            let wide = h.iter().map(|x| x.to_f32()).collect();
11611            (fuel_memory::from_slice_cpu(&h), wide)
11612        } else {
11613            let h: Vec<half::f16> = w_f32.iter().map(|&x| half::f16::from_f32(x)).collect();
11614            let wide = h.iter().map(|x| x.to_f32()).collect();
11615            (fuel_memory::from_slice_cpu(&h), wide)
11616        };
11617        let graph = Arc::new(RwLock::new(Graph::new()));
11618        let (l_id, r_id, mm_id) = {
11619            let mut g = graph.write().unwrap();
11620            let l = g.push(Node {
11621                op: Op::Const,
11622                inputs: vec![],
11623                shape: Shape::from_dims(&[m, k]),
11624                dtype: DType::F32,
11625            });
11626            let r = g.push(Node {
11627                op: Op::Const,
11628                inputs: vec![],
11629                shape: Shape::from_dims(&[k, n]),
11630                dtype: weight_dtype,
11631            });
11632            let mm = g.push(Node {
11633                op: Op::MatMul,
11634                inputs: vec![l, r],
11635                shape: Shape::from_dims(&[m, n]),
11636                dtype: DType::F32,
11637            });
11638            g.set_target_backend(mm, BackendId::Cpu);
11639            (l, r, mm)
11640        };
11641        let mut inputs = StorageCache::new();
11642        inputs.insert(l_id, Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&a))));
11643        inputs.insert(r_id, Arc::new(RwLock::new(w_storage)));
11644        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11645        let guard = result_arc.read().unwrap();
11646        assert_eq!(guard.dtype, DType::F32);
11647        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11648            panic!("expected Cpu storage");
11649        };
11650        let got: &[f32] = c.as_slice().unwrap();
11651        for i in 0..m {
11652            for j in 0..n {
11653                let want: f64 = (0..k)
11654                    .map(|kk| a[i * k + kk] as f64 * widened[kk * n + j] as f64)
11655                    .sum();
11656                let err = (got[i * n + j] as f64 - want).abs();
11657                assert!(
11658                    err < 1e-5,
11659                    "{weight_dtype:?} [{i},{j}]: got {}, want {want}",
11660                    got[i * n + j]
11661                );
11662            }
11663        }
11664    }
11665
11666    #[test]
11667    fn pipelined_realize_mixed_f32_bf16_matmul_is_native_on_cpu() {
11668        mixed_cpu_matmul_matches_f64(DType::BF16);
11669    }
11670
11671    #[test]
11672    fn pipelined_realize_mixed_f32_f16_matmul_is_native_on_cpu() {
11673        mixed_cpu_matmul_matches_f64(DType::F16);
11674    }
11675
11676    /// E2E: F16 sum-reduce — verifies bf16/f16 reduction dispatch
11677    /// works through the executor.
11678    #[test]
11679    fn pipelined_realize_sum_dim_f16() {
11680        let v: Vec<half::f16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]
11681            .iter()
11682            .map(|&x| half::f16::from_f32(x))
11683            .collect();
11684        let storage = fuel_memory::from_slice_cpu(&v);
11685        let graph = Arc::new(RwLock::new(Graph::new()));
11686        let (in_id, sum_id) = {
11687            let mut g = graph.write().unwrap();
11688            let in_id = g.push(Node {
11689                op: Op::Const,
11690                inputs: vec![],
11691                shape: Shape::from_dims(&[2, 3]),
11692                dtype: DType::F16,
11693            });
11694            let sum_id = g.push(Node {
11695                op: Op::SumDim(1),
11696                inputs: vec![in_id],
11697                shape: Shape::from_dims(&[2]),
11698                dtype: DType::F16,
11699            });
11700            g.set_target_backend(sum_id, BackendId::Cpu);
11701            (in_id, sum_id)
11702        };
11703        let mut inputs = StorageCache::new();
11704        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11705        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
11706        let guard = result_arc.read().unwrap();
11707        assert_eq!(guard.dtype, DType::F16);
11708        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11709            panic!("expected Cpu storage");
11710        };
11711        let r: &[half::f16] = c.as_slice().unwrap();
11712        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
11713        assert_eq!(result_f32, vec![6.0, 15.0]);
11714    }
11715
11716    /// E2E: BF16 elementwise add through the pipelined executor.
11717    #[test]
11718    fn pipelined_realize_add_bf16() {
11719        let lhs_vec: Vec<half::bf16> = [1.0_f32, 2.0, 3.0]
11720            .iter()
11721            .map(|&x| half::bf16::from_f32(x))
11722            .collect();
11723        let rhs_vec: Vec<half::bf16> = [10.0_f32, 20.0, 30.0]
11724            .iter()
11725            .map(|&x| half::bf16::from_f32(x))
11726            .collect();
11727        let lhs = fuel_memory::from_slice_cpu(&lhs_vec);
11728        let rhs = fuel_memory::from_slice_cpu(&rhs_vec);
11729        let graph = Arc::new(RwLock::new(Graph::new()));
11730        let (l_id, r_id, op_id) = {
11731            let mut g = graph.write().unwrap();
11732            let l = g.push(Node {
11733                op: Op::Const,
11734                inputs: vec![],
11735                shape: Shape::from_dims(&[3]),
11736                dtype: DType::BF16,
11737            });
11738            let r = g.push(Node {
11739                op: Op::Const,
11740                inputs: vec![],
11741                shape: Shape::from_dims(&[3]),
11742                dtype: DType::BF16,
11743            });
11744            let op = g.push(Node {
11745                op: Op::Add,
11746                inputs: vec![l, r],
11747                shape: Shape::from_dims(&[3]),
11748                dtype: DType::BF16,
11749            });
11750            g.set_target_backend(op, BackendId::Cpu);
11751            (l, r, op)
11752        };
11753        let mut inputs = StorageCache::new();
11754        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11755        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11756        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
11757        let guard = result_arc.read().unwrap();
11758        assert_eq!(guard.dtype, DType::BF16);
11759        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11760            panic!("expected Cpu storage");
11761        };
11762        let r: &[half::bf16] = c.as_slice().unwrap();
11763        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
11764        assert_eq!(result_f32, vec![11.0, 22.0, 33.0]);
11765    }
11766
11767    /// E2E: F16 unary chain — Const + Sqr + Sqrt — verifies F16
11768    /// dispatch works and the via-f32 round-trip kernels behave
11769    /// correctly through the executor.
11770    #[test]
11771    fn pipelined_realize_sqr_then_sqrt_f16() {
11772        let v: Vec<half::f16> = [1.0_f32, 4.0, 9.0]
11773            .iter()
11774            .map(|&x| half::f16::from_f32(x))
11775            .collect();
11776        let storage = fuel_memory::from_slice_cpu(&v);
11777        let graph = Arc::new(RwLock::new(Graph::new()));
11778        let (in_id, sqrt_id) = {
11779            let mut g = graph.write().unwrap();
11780            let in_id = g.push(Node {
11781                op: Op::Const,
11782                inputs: vec![],
11783                shape: Shape::from_dims(&[3]),
11784                dtype: DType::F16,
11785            });
11786            let sqr_id = g.push(Node {
11787                op: Op::Sqr,
11788                inputs: vec![in_id],
11789                shape: Shape::from_dims(&[3]),
11790                dtype: DType::F16,
11791            });
11792            let sqrt_id = g.push(Node {
11793                op: Op::Sqrt,
11794                inputs: vec![sqr_id],
11795                shape: Shape::from_dims(&[3]),
11796                dtype: DType::F16,
11797            });
11798            g.set_target_backend(sqr_id, BackendId::Cpu);
11799            g.set_target_backend(sqrt_id, BackendId::Cpu);
11800            (in_id, sqrt_id)
11801        };
11802        let mut inputs = StorageCache::new();
11803        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11804        let (result_arc, _) = PipelinedExecutor::realize(graph, sqrt_id, inputs).expect("realize");
11805        let guard = result_arc.read().unwrap();
11806        assert_eq!(guard.dtype, DType::F16);
11807        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11808            panic!("expected Cpu storage");
11809        };
11810        let r: &[half::f16] = c.as_slice().unwrap();
11811        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
11812        // f16 has ~3 decimal digits; sqrt(sqr(x)) = |x| within rounding.
11813        for (got, want) in result_f32.iter().zip(&[1.0_f32, 4.0, 9.0]) {
11814            assert!((got - want).abs() < 0.05, "got {got}, want {want}");
11815        }
11816    }
11817
11818    /// E2E: F64 sum-reduce along one dim through the pipelined
11819    /// executor.
11820    #[test]
11821    fn pipelined_realize_sum_dim_f64() {
11822        let storage = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
11823        let graph = Arc::new(RwLock::new(Graph::new()));
11824        let (in_id, sum_id) = {
11825            let mut g = graph.write().unwrap();
11826            let in_id = g.push(Node {
11827                op: Op::Const,
11828                inputs: vec![],
11829                shape: Shape::from_dims(&[2, 3]),
11830                dtype: DType::F64,
11831            });
11832            let sum_id = g.push(Node {
11833                op: Op::SumDim(1),
11834                inputs: vec![in_id],
11835                shape: Shape::from_dims(&[2]),
11836                dtype: DType::F64,
11837            });
11838            g.set_target_backend(sum_id, BackendId::Cpu);
11839            (in_id, sum_id)
11840        };
11841        let mut inputs = StorageCache::new();
11842        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11843        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
11844        let guard = result_arc.read().unwrap();
11845        assert_eq!(guard.dtype, DType::F64);
11846        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11847            panic!("expected Cpu storage");
11848        };
11849        assert_eq!(c.as_slice::<f64>().unwrap(), &[6.0_f64, 15.0]);
11850    }
11851
11852    /// E2E: F64 matmul through the pipelined executor.
11853    #[test]
11854    fn pipelined_realize_matmul_2x3_times_3x2_f64() {
11855        let lhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
11856        let rhs = fuel_memory::from_slice_cpu(&[7.0_f64, 8.0, 9.0, 10.0, 11.0, 12.0]);
11857        let graph = Arc::new(RwLock::new(Graph::new()));
11858        let (l_id, r_id, mm_id) = {
11859            let mut g = graph.write().unwrap();
11860            let l = g.push(Node {
11861                op: Op::Const,
11862                inputs: vec![],
11863                shape: Shape::from_dims(&[2, 3]),
11864                dtype: DType::F64,
11865            });
11866            let r = g.push(Node {
11867                op: Op::Const,
11868                inputs: vec![],
11869                shape: Shape::from_dims(&[3, 2]),
11870                dtype: DType::F64,
11871            });
11872            let mm = g.push(Node {
11873                op: Op::MatMul,
11874                inputs: vec![l, r],
11875                shape: Shape::from_dims(&[2, 2]),
11876                dtype: DType::F64,
11877            });
11878            g.set_target_backend(mm, BackendId::Cpu);
11879            (l, r, mm)
11880        };
11881        let mut inputs = StorageCache::new();
11882        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11883        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11884        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11885        let guard = result_arc.read().unwrap();
11886        assert_eq!(guard.dtype, DType::F64);
11887        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11888            panic!("expected Cpu storage");
11889        };
11890        assert_eq!(
11891            c.as_slice::<f64>().unwrap(),
11892            &[58.0_f64, 64.0, 139.0, 154.0]
11893        );
11894    }
11895
11896    /// E2E: F64 unary chain — Const + Sqr + Sqrt — verifies that
11897    /// the kernel-binding lookup picks the f64 entries when the
11898    /// graph nodes carry DType::F64.
11899    #[test]
11900    fn pipelined_realize_sqr_then_sqrt_f64() {
11901        let storage = fuel_memory::from_slice_cpu(&[1.0_f64, 4.0, 9.0]);
11902        let graph = Arc::new(RwLock::new(Graph::new()));
11903        let (in_id, sqrt_id) = {
11904            let mut g = graph.write().unwrap();
11905            let in_id = g.push(Node {
11906                op: Op::Const,
11907                inputs: vec![],
11908                shape: Shape::from_dims(&[3]),
11909                dtype: DType::F64,
11910            });
11911            let sqr_id = g.push(Node {
11912                op: Op::Sqr,
11913                inputs: vec![in_id],
11914                shape: Shape::from_dims(&[3]),
11915                dtype: DType::F64,
11916            });
11917            let sqrt_id = g.push(Node {
11918                op: Op::Sqrt,
11919                inputs: vec![sqr_id],
11920                shape: Shape::from_dims(&[3]),
11921                dtype: DType::F64,
11922            });
11923            g.set_target_backend(sqr_id, BackendId::Cpu);
11924            g.set_target_backend(sqrt_id, BackendId::Cpu);
11925            (in_id, sqrt_id)
11926        };
11927        let mut inputs = StorageCache::new();
11928        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11929        let (result_arc, _) = PipelinedExecutor::realize(graph, sqrt_id, inputs).expect("realize");
11930        let guard = result_arc.read().unwrap();
11931        assert_eq!(guard.dtype, DType::F64);
11932        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11933            panic!("expected Cpu storage");
11934        };
11935        assert_eq!(c.as_slice::<f64>().unwrap(), &[1.0_f64, 4.0, 9.0]);
11936    }
11937
11938    /// E2E: ArgMaxDim — produces U32 output indices.
11939    #[test]
11940    fn pipelined_realize_argmax_dim() {
11941        // input [2, 3] = [[1, 5, 2], [9, 0, 4]]
11942        // argmax dim=1 → [1, 0]
11943        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 2.0, 9.0, 0.0, 4.0]);
11944        let graph = Arc::new(RwLock::new(Graph::new()));
11945        let (in_id, op_id) = {
11946            let mut g = graph.write().unwrap();
11947            let in_id = g.push(Node {
11948                op: Op::Const,
11949                inputs: vec![],
11950                shape: Shape::from_dims(&[2, 3]),
11951                dtype: DType::F32,
11952            });
11953            let op_id = g.push(Node {
11954                op: Op::ArgMaxDim(1),
11955                inputs: vec![in_id],
11956                shape: Shape::from_dims(&[2]),
11957                dtype: DType::U32,
11958            });
11959            g.set_target_backend(op_id, BackendId::Cpu);
11960            (in_id, op_id)
11961        };
11962        let mut inputs = StorageCache::new();
11963        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11964        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
11965        let guard = result_arc.read().unwrap();
11966        assert_eq!(guard.dtype, DType::U32);
11967        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11968            panic!("expected Cpu storage");
11969        };
11970        assert_eq!(c.as_slice::<u32>().unwrap(), &[1u32, 0]);
11971    }
11972
11973    /// E2E: IndexAdd along outer dim — accumulate updates into a
11974    /// rank-1 base tensor at indexed positions.
11975    #[test]
11976    fn pipelined_realize_index_add_simple() {
11977        let base = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
11978        let indices = fuel_memory::from_slice_cpu(&[0u32, 0]);
11979        let src = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
11980        let graph = Arc::new(RwLock::new(Graph::new()));
11981        let (b_id, i_id, s_id, op_id) = {
11982            let mut g = graph.write().unwrap();
11983            let b = g.push(Node {
11984                op: Op::Const,
11985                inputs: vec![],
11986                shape: Shape::from_dims(&[3]),
11987                dtype: DType::F32,
11988            });
11989            let i = g.push(Node {
11990                op: Op::Const,
11991                inputs: vec![],
11992                shape: Shape::from_dims(&[2]),
11993                dtype: DType::U32,
11994            });
11995            let s = g.push(Node {
11996                op: Op::Const,
11997                inputs: vec![],
11998                shape: Shape::from_dims(&[2]),
11999                dtype: DType::F32,
12000            });
12001            let op = g.push(Node {
12002                op: Op::IndexAdd { dim: 0 },
12003                inputs: vec![b, i, s],
12004                shape: Shape::from_dims(&[3]),
12005                dtype: DType::F32,
12006            });
12007            g.set_target_backend(op, BackendId::Cpu);
12008            (b, i, s, op)
12009        };
12010        let mut inputs = StorageCache::new();
12011        inputs.insert(b_id, Arc::new(RwLock::new(base)));
12012        inputs.insert(i_id, Arc::new(RwLock::new(indices)));
12013        inputs.insert(s_id, Arc::new(RwLock::new(src)));
12014        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12015        let guard = result_arc.read().unwrap();
12016        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12017            panic!("expected Cpu storage");
12018        };
12019        // 10 + 1 + 2 = 13; 20 untouched; 30 untouched.
12020        assert_eq!(c.as_slice::<f32>().unwrap(), &[13.0, 20.0, 30.0]);
12021    }
12022
12023    /// E2E: ScatterAdd along outer dim — same-rank indices, base
12024    /// starts as zeros, src adds values at scatter positions.
12025    #[test]
12026    fn pipelined_realize_scatter_add_outer_dim() {
12027        // base [3, 2] = zeros; indices [2, 2] = [[0, 1], [2, 0]];
12028        // src [2, 2] = [[1, 2], [3, 4]]; dim=0
12029        // → out = [[1, 4], [0, 2], [3, 0]]
12030        let base = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
12031        let indices = fuel_memory::from_slice_cpu(&[0u32, 1, 2, 0]);
12032        let src = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
12033        let graph = Arc::new(RwLock::new(Graph::new()));
12034        let (b_id, i_id, s_id, op_id) = {
12035            let mut g = graph.write().unwrap();
12036            let b = g.push(Node {
12037                op: Op::Const,
12038                inputs: vec![],
12039                shape: Shape::from_dims(&[3, 2]),
12040                dtype: DType::F32,
12041            });
12042            let i = g.push(Node {
12043                op: Op::Const,
12044                inputs: vec![],
12045                shape: Shape::from_dims(&[2, 2]),
12046                dtype: DType::U32,
12047            });
12048            let s = g.push(Node {
12049                op: Op::Const,
12050                inputs: vec![],
12051                shape: Shape::from_dims(&[2, 2]),
12052                dtype: DType::F32,
12053            });
12054            let op = g.push(Node {
12055                op: Op::ScatterAdd { dim: 0 },
12056                inputs: vec![b, i, s],
12057                shape: Shape::from_dims(&[3, 2]),
12058                dtype: DType::F32,
12059            });
12060            g.set_target_backend(op, BackendId::Cpu);
12061            (b, i, s, op)
12062        };
12063        let mut inputs = StorageCache::new();
12064        inputs.insert(b_id, Arc::new(RwLock::new(base)));
12065        inputs.insert(i_id, Arc::new(RwLock::new(indices)));
12066        inputs.insert(s_id, Arc::new(RwLock::new(src)));
12067        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12068        let guard = result_arc.read().unwrap();
12069        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12070            panic!("expected Cpu storage");
12071        };
12072        assert_eq!(
12073            c.as_slice::<f32>().unwrap(),
12074            &[1.0, 4.0, 0.0, 2.0, 3.0, 0.0]
12075        );
12076    }
12077
12078    /// E2E: Rope through the pipelined executor. cos=0, sin=1
12079    /// rotates the head_dim halves with sign per the rotate_half
12080    /// convention.
12081    #[test]
12082    fn pipelined_realize_rope_pi_over_two() {
12083        // x [1, 1, 4] = [1, 2, 3, 4]. cos=[0,0,0,0], sin=[1,1,1,1].
12084        // Expected: [-3, -4, 1, 2].
12085        let x = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
12086        let cos = fuel_memory::from_slice_cpu(&[0.0_f32, 0.0, 0.0, 0.0]);
12087        let sin = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
12088        let graph = Arc::new(RwLock::new(Graph::new()));
12089        let (x_id, cos_id, sin_id, r_id) = {
12090            let mut g = graph.write().unwrap();
12091            let x = g.push(Node {
12092                op: Op::Const,
12093                inputs: vec![],
12094                shape: Shape::from_dims(&[1, 1, 4]),
12095                dtype: DType::F32,
12096            });
12097            let c = g.push(Node {
12098                op: Op::Const,
12099                inputs: vec![],
12100                shape: Shape::from_dims(&[1, 4]),
12101                dtype: DType::F32,
12102            });
12103            let s = g.push(Node {
12104                op: Op::Const,
12105                inputs: vec![],
12106                shape: Shape::from_dims(&[1, 4]),
12107                dtype: DType::F32,
12108            });
12109            let r = g.push(Node {
12110                op: Op::Fused(
12111                    fuel_graph::registry::FusedOps::ROPE,
12112                    fuel_graph::registry::FusedOpParams::Rope,
12113                ),
12114                inputs: vec![x, c, s],
12115                shape: Shape::from_dims(&[1, 1, 4]),
12116                dtype: DType::F32,
12117            });
12118            g.set_target_backend(r, BackendId::Cpu);
12119            (x, c, s, r)
12120        };
12121        let mut inputs = StorageCache::new();
12122        inputs.insert(x_id, Arc::new(RwLock::new(x)));
12123        inputs.insert(cos_id, Arc::new(RwLock::new(cos)));
12124        inputs.insert(sin_id, Arc::new(RwLock::new(sin)));
12125        let (result_arc, _) = PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
12126        let guard = result_arc.read().unwrap();
12127        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12128            panic!("expected Cpu storage");
12129        };
12130        assert_eq!(c.as_slice::<f32>().unwrap(), &[-3.0, -4.0, 1.0, 2.0]);
12131    }
12132
12133    /// E2E: Gather along inner dim. Source [2, 4]; indices [2, 3];
12134    /// output [2, 3] = picks from each row by per-row indices.
12135    #[test]
12136    fn pipelined_realize_gather_inner_dim() {
12137        let source =
12138            fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0]);
12139        let indices = fuel_memory::from_slice_cpu(&[0u32, 2, 1, 3, 0, 0]);
12140        let graph = Arc::new(RwLock::new(Graph::new()));
12141        let (src_id, idx_id, g_id) = {
12142            let mut g = graph.write().unwrap();
12143            let s = g.push(Node {
12144                op: Op::Const,
12145                inputs: vec![],
12146                shape: Shape::from_dims(&[2, 4]),
12147                dtype: DType::F32,
12148            });
12149            let i = g.push(Node {
12150                op: Op::Const,
12151                inputs: vec![],
12152                shape: Shape::from_dims(&[2, 3]),
12153                dtype: DType::U32,
12154            });
12155            let g_id = g.push(Node {
12156                op: Op::Gather { dim: 1 },
12157                inputs: vec![s, i],
12158                shape: Shape::from_dims(&[2, 3]),
12159                dtype: DType::F32,
12160            });
12161            g.set_target_backend(g_id, BackendId::Cpu);
12162            (s, i, g_id)
12163        };
12164        let mut inputs = StorageCache::new();
12165        inputs.insert(src_id, Arc::new(RwLock::new(source)));
12166        inputs.insert(idx_id, Arc::new(RwLock::new(indices)));
12167        let (result_arc, _) = PipelinedExecutor::realize(graph, g_id, inputs).expect("realize");
12168        let guard = result_arc.read().unwrap();
12169        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12170            panic!("expected Cpu storage");
12171        };
12172        assert_eq!(
12173            c.as_slice::<f32>().unwrap(),
12174            &[10.0, 30.0, 20.0, 80.0, 50.0, 50.0]
12175        );
12176    }
12177
12178    /// E2E: IndexSelect — embedding-table lookup. Source is a
12179    /// `[vocab=4, d_model=3]` table; indices are token IDs;
12180    /// output is `[seq=3, d_model=3]` with the picked rows.
12181    #[test]
12182    fn pipelined_realize_index_select_embedding_lookup() {
12183        let table = fuel_memory::from_slice_cpu(&[
12184            10.0_f32, 11.0, 12.0, // row 0
12185            20.0, 21.0, 22.0, // row 1
12186            30.0, 31.0, 32.0, // row 2
12187            40.0, 41.0, 42.0, // row 3
12188        ]);
12189        let indices = fuel_memory::from_slice_cpu(&[2u32, 0, 2]);
12190        let graph = Arc::new(RwLock::new(Graph::new()));
12191        let (table_id, idx_id, sel_id) = {
12192            let mut g = graph.write().unwrap();
12193            let t = g.push(Node {
12194                op: Op::Const,
12195                inputs: vec![],
12196                shape: Shape::from_dims(&[4, 3]),
12197                dtype: DType::F32,
12198            });
12199            let i = g.push(Node {
12200                op: Op::Const,
12201                inputs: vec![],
12202                shape: Shape::from_dims(&[3]),
12203                dtype: DType::U32,
12204            });
12205            let s = g.push(Node {
12206                op: Op::IndexSelect { dim: 0 },
12207                inputs: vec![t, i],
12208                shape: Shape::from_dims(&[3, 3]),
12209                dtype: DType::F32,
12210            });
12211            g.set_target_backend(s, BackendId::Cpu);
12212            (t, i, s)
12213        };
12214        let mut inputs = StorageCache::new();
12215        inputs.insert(table_id, Arc::new(RwLock::new(table)));
12216        inputs.insert(idx_id, Arc::new(RwLock::new(indices)));
12217        let (result_arc, result_layout) =
12218            PipelinedExecutor::realize(graph, sel_id, inputs).expect("realize");
12219        assert_eq!(result_layout.shape().dims(), &[3, 3]);
12220        let guard = result_arc.read().unwrap();
12221        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12222            panic!("expected Cpu storage");
12223        };
12224        assert_eq!(
12225            c.as_slice::<f32>().unwrap(),
12226            &[30.0, 31.0, 32.0, 10.0, 11.0, 12.0, 30.0, 31.0, 32.0]
12227        );
12228    }
12229
12230    /// E2E: RmsNormLastDim on a 2-row input. Each row's output
12231    /// has unit RMS up to the eps-induced bias.
12232    #[test]
12233    fn pipelined_realize_rms_norm_last_dim() {
12234        let storage = fuel_memory::from_slice_cpu(&[
12235            3.0_f32, 4.0, // row 0: rms = sqrt(12.5)
12236            6.0, 8.0, // row 1: rms = sqrt(50.0) = 5*sqrt(2)
12237        ]);
12238        let graph = Arc::new(RwLock::new(Graph::new()));
12239        let (in_id, op_id) = {
12240            let mut g = graph.write().unwrap();
12241            let in_id = g.push(Node {
12242                op: Op::Const,
12243                inputs: vec![],
12244                shape: Shape::from_dims(&[2, 2]),
12245                dtype: DType::F32,
12246            });
12247            let op_id = g.push(Node {
12248                op: Op::Fused(
12249                    fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM,
12250                    fuel_graph::registry::FusedOpParams::RmsNormLastDim { eps: 0.0 },
12251                ),
12252                inputs: vec![in_id],
12253                shape: Shape::from_dims(&[2, 2]),
12254                dtype: DType::F32,
12255            });
12256            g.set_target_backend(op_id, BackendId::Cpu);
12257            (in_id, op_id)
12258        };
12259        let mut inputs = StorageCache::new();
12260        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12261        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12262        let guard = result_arc.read().unwrap();
12263        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12264            panic!("expected Cpu storage");
12265        };
12266        let result: &[f32] = c.as_slice().unwrap();
12267        // Row 0: rms = sqrt(12.5). Output = [3, 4] / sqrt(12.5).
12268        let rms0 = (12.5_f32).sqrt();
12269        assert!((result[0] - 3.0 / rms0).abs() < 1e-6);
12270        assert!((result[1] - 4.0 / rms0).abs() < 1e-6);
12271        // Row 1: rms = sqrt(50). Output = [6, 8] / sqrt(50).
12272        let rms1 = (50.0_f32).sqrt();
12273        assert!((result[2] - 6.0 / rms1).abs() < 1e-6);
12274        assert!((result[3] - 8.0 / rms1).abs() < 1e-6);
12275    }
12276
12277    /// E2E: LayerNormLastDim — each row's output has zero mean and
12278    /// unit variance.
12279    #[test]
12280    fn pipelined_realize_layer_norm_last_dim() {
12281        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 10.0, 20.0, 30.0]);
12282        let graph = Arc::new(RwLock::new(Graph::new()));
12283        let (in_id, op_id) = {
12284            let mut g = graph.write().unwrap();
12285            let in_id = g.push(Node {
12286                op: Op::Const,
12287                inputs: vec![],
12288                shape: Shape::from_dims(&[2, 3]),
12289                dtype: DType::F32,
12290            });
12291            let op_id = g.push(Node {
12292                op: Op::Fused(
12293                    fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM,
12294                    fuel_graph::registry::FusedOpParams::LayerNormLastDim { eps: 0.0 },
12295                ),
12296                inputs: vec![in_id],
12297                shape: Shape::from_dims(&[2, 3]),
12298                dtype: DType::F32,
12299            });
12300            g.set_target_backend(op_id, BackendId::Cpu);
12301            (in_id, op_id)
12302        };
12303        let mut inputs = StorageCache::new();
12304        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12305        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12306        let guard = result_arc.read().unwrap();
12307        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12308            panic!("expected Cpu storage");
12309        };
12310        let result: &[f32] = c.as_slice().unwrap();
12311        // Each row should have mean ~0 and var ~1.
12312        for row in 0..2 {
12313            let off = row * 3;
12314            let sum: f32 = result[off..off + 3].iter().sum();
12315            let mean = sum / 3.0;
12316            assert!(mean.abs() < 1e-6, "row {row} mean should be 0, got {mean}");
12317            let var: f32 = result[off..off + 3]
12318                .iter()
12319                .map(|v| (v - mean).powi(2))
12320                .sum::<f32>()
12321                / 3.0;
12322            assert!(
12323                (var - 1.0).abs() < 1e-6,
12324                "row {row} var should be 1, got {var}"
12325            );
12326        }
12327    }
12328
12329    /// E2E: SoftmaxLastDim on a 2-row input. Each row should sum
12330    /// to 1; uniform row gives uniform output.
12331    #[test]
12332    fn pipelined_realize_softmax_last_dim() {
12333        // Row 0: [1, 1, 1, 1] → uniform 0.25 each
12334        // Row 1: [0, 0, 0, 100] → effectively a one-hot at position 3
12335        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 100.0]);
12336        let graph = Arc::new(RwLock::new(Graph::new()));
12337        let (in_id, op_id) = {
12338            let mut g = graph.write().unwrap();
12339            let in_id = g.push(Node {
12340                op: Op::Const,
12341                inputs: vec![],
12342                shape: Shape::from_dims(&[2, 4]),
12343                dtype: DType::F32,
12344            });
12345            let op_id = g.push(Node {
12346                op: Op::Fused(
12347                    fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM,
12348                    fuel_graph::registry::FusedOpParams::SoftmaxLastDim,
12349                ),
12350                inputs: vec![in_id],
12351                shape: Shape::from_dims(&[2, 4]),
12352                dtype: DType::F32,
12353            });
12354            g.set_target_backend(op_id, BackendId::Cpu);
12355            (in_id, op_id)
12356        };
12357        let mut inputs = StorageCache::new();
12358        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12359        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12360        let guard = result_arc.read().unwrap();
12361        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12362            panic!("expected Cpu storage");
12363        };
12364        let result: &[f32] = c.as_slice().unwrap();
12365
12366        // Row 0: uniform 0.25
12367        for v in &result[..4] {
12368            assert!((v - 0.25).abs() < 1e-7);
12369        }
12370        // Row 1: positions 0..3 ≈ 0, position 4 (= last column) ≈ 1
12371        // (e^100 dominates).
12372        for v in &result[4..7] {
12373            assert!(
12374                *v < 1e-30,
12375                "row-1 leading positions should be near 0, got {v}"
12376            );
12377        }
12378        assert!(
12379            result[7] > 0.999,
12380            "row-1 last position should dominate, got {}",
12381            result[7]
12382        );
12383        // Each row sums to 1.
12384        let row0_sum: f32 = result[..4].iter().sum();
12385        let row1_sum: f32 = result[4..].iter().sum();
12386        assert!((row0_sum - 1.0).abs() < 1e-6);
12387        assert!((row1_sum - 1.0).abs() < 1e-6);
12388    }
12389
12390    /// E2E: Concat along inner dim — two [2, 3] tensors → [2, 6].
12391    #[test]
12392    fn pipelined_realize_concat_inner_dim() {
12393        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
12394        let b = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0, 9.0, 10.0, 11.0, 12.0]);
12395        let graph = Arc::new(RwLock::new(Graph::new()));
12396        let (a_id, b_id, c_id) = {
12397            let mut g = graph.write().unwrap();
12398            let a = g.push(Node {
12399                op: Op::Const,
12400                inputs: vec![],
12401                shape: Shape::from_dims(&[2, 3]),
12402                dtype: DType::F32,
12403            });
12404            let b = g.push(Node {
12405                op: Op::Const,
12406                inputs: vec![],
12407                shape: Shape::from_dims(&[2, 3]),
12408                dtype: DType::F32,
12409            });
12410            let c = g.push(Node {
12411                op: Op::Concat { dim: 1 },
12412                inputs: vec![a, b],
12413                shape: Shape::from_dims(&[2, 6]),
12414                dtype: DType::F32,
12415            });
12416            g.set_target_backend(c, BackendId::Cpu);
12417            (a, b, c)
12418        };
12419        let mut inputs = StorageCache::new();
12420        inputs.insert(a_id, Arc::new(RwLock::new(a)));
12421        inputs.insert(b_id, Arc::new(RwLock::new(b)));
12422        let (result_arc, result_layout) =
12423            PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12424        assert_eq!(result_layout.shape().dims(), &[2, 6]);
12425        let guard = result_arc.read().unwrap();
12426        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12427            panic!("expected Cpu storage");
12428        };
12429        assert_eq!(
12430            c.as_slice::<f32>().unwrap(),
12431            &[
12432                1.0, 2.0, 3.0, 7.0, 8.0, 9.0, 4.0, 5.0, 6.0, 10.0, 11.0, 12.0
12433            ]
12434        );
12435    }
12436
12437    /// E2E: Concat with three inputs along outer dim — verifies
12438    /// variable-arity input handling through the executor.
12439    #[test]
12440    fn pipelined_realize_concat_three_inputs_outer() {
12441        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
12442        let b = fuel_memory::from_slice_cpu(&[3.0_f32, 4.0]);
12443        let c = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0]);
12444        let graph = Arc::new(RwLock::new(Graph::new()));
12445        let (a_id, b_id, c_id, cat_id) = {
12446            let mut g = graph.write().unwrap();
12447            let a = g.push(Node {
12448                op: Op::Const,
12449                inputs: vec![],
12450                shape: Shape::from_dims(&[2]),
12451                dtype: DType::F32,
12452            });
12453            let b = g.push(Node {
12454                op: Op::Const,
12455                inputs: vec![],
12456                shape: Shape::from_dims(&[2]),
12457                dtype: DType::F32,
12458            });
12459            let c = g.push(Node {
12460                op: Op::Const,
12461                inputs: vec![],
12462                shape: Shape::from_dims(&[2]),
12463                dtype: DType::F32,
12464            });
12465            let cat = g.push(Node {
12466                op: Op::Concat { dim: 0 },
12467                inputs: vec![a, b, c],
12468                shape: Shape::from_dims(&[6]),
12469                dtype: DType::F32,
12470            });
12471            g.set_target_backend(cat, BackendId::Cpu);
12472            (a, b, c, cat)
12473        };
12474        let mut inputs = StorageCache::new();
12475        inputs.insert(a_id, Arc::new(RwLock::new(a)));
12476        inputs.insert(b_id, Arc::new(RwLock::new(b)));
12477        inputs.insert(c_id, Arc::new(RwLock::new(c)));
12478        let (result_arc, _) = PipelinedExecutor::realize(graph, cat_id, inputs).expect("realize");
12479        let guard = result_arc.read().unwrap();
12480        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12481            panic!("expected Cpu storage");
12482        };
12483        assert_eq!(
12484            c.as_slice::<f32>().unwrap(),
12485            &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
12486        );
12487    }
12488
12489    /// E2E: AddScalar — graph emits Op::AddScalar; the executor
12490    /// maps it to OpKind::Affine with mul=1, add=c.
12491    #[test]
12492    fn pipelined_realize_add_scalar() {
12493        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
12494        let graph = Arc::new(RwLock::new(Graph::new()));
12495        let (in_id, op_id) = {
12496            let mut g = graph.write().unwrap();
12497            let in_id = g.push(Node {
12498                op: Op::Const,
12499                inputs: vec![],
12500                shape: Shape::from_dims(&[3]),
12501                dtype: DType::F32,
12502            });
12503            let op_id = g.push(Node {
12504                op: Op::AddScalar(10.0),
12505                inputs: vec![in_id],
12506                shape: Shape::from_dims(&[3]),
12507                dtype: DType::F32,
12508            });
12509            g.set_target_backend(op_id, BackendId::Cpu);
12510            (in_id, op_id)
12511        };
12512        let mut inputs = StorageCache::new();
12513        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12514        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12515        let guard = result_arc.read().unwrap();
12516        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12517            panic!("expected Cpu storage");
12518        };
12519        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 12.0, 13.0]);
12520    }
12521
12522    /// E2E: Clamp — clamp values to [-2, 2].
12523    #[test]
12524    fn pipelined_realize_clamp() {
12525        let storage = fuel_memory::from_slice_cpu(&[-5.0_f32, 0.5, 100.0]);
12526        let graph = Arc::new(RwLock::new(Graph::new()));
12527        let (in_id, op_id) = {
12528            let mut g = graph.write().unwrap();
12529            let in_id = g.push(Node {
12530                op: Op::Const,
12531                inputs: vec![],
12532                shape: Shape::from_dims(&[3]),
12533                dtype: DType::F32,
12534            });
12535            let op_id = g.push(Node {
12536                op: Op::Clamp {
12537                    min: -2.0,
12538                    max: 2.0,
12539                },
12540                inputs: vec![in_id],
12541                shape: Shape::from_dims(&[3]),
12542                dtype: DType::F32,
12543            });
12544            g.set_target_backend(op_id, BackendId::Cpu);
12545            (in_id, op_id)
12546        };
12547        let mut inputs = StorageCache::new();
12548        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12549        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12550        let guard = result_arc.read().unwrap();
12551        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12552            panic!("expected Cpu storage");
12553        };
12554        assert_eq!(c.as_slice::<f32>().unwrap(), &[-2.0, 0.5, 2.0]);
12555    }
12556
12557    /// E2E: Maximum — elementwise tensor max.
12558    #[test]
12559    fn pipelined_realize_maximum_elementwise() {
12560        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, -3.0]);
12561        let rhs_storage = fuel_memory::from_slice_cpu(&[2.0_f32, 1.0, -1.0]);
12562        let graph = Arc::new(RwLock::new(Graph::new()));
12563        let (lhs_id, rhs_id, op_id) = {
12564            let mut g = graph.write().unwrap();
12565            let lhs = g.push(Node {
12566                op: Op::Const,
12567                inputs: vec![],
12568                shape: Shape::from_dims(&[3]),
12569                dtype: DType::F32,
12570            });
12571            let rhs = g.push(Node {
12572                op: Op::Const,
12573                inputs: vec![],
12574                shape: Shape::from_dims(&[3]),
12575                dtype: DType::F32,
12576            });
12577            let op = g.push(Node {
12578                op: Op::Maximum,
12579                inputs: vec![lhs, rhs],
12580                shape: Shape::from_dims(&[3]),
12581                dtype: DType::F32,
12582            });
12583            g.set_target_backend(op, BackendId::Cpu);
12584            (lhs, rhs, op)
12585        };
12586        let mut inputs = StorageCache::new();
12587        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
12588        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
12589        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12590        let guard = result_arc.read().unwrap();
12591        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12592            panic!("expected Cpu storage");
12593        };
12594        assert_eq!(c.as_slice::<f32>().unwrap(), &[2.0, 5.0, -1.0]);
12595    }
12596
12597    /// E2E: Const + Const + Conv2D — the 2×2 sum-kernel test from
12598    /// byte_kernels driven through the pipelined executor.
12599    #[test]
12600    fn pipelined_realize_conv2d_2x2_sum_kernel() {
12601        // x [1, 1, 3, 3]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
12602        // weight [1, 1, 2, 2]: all-ones
12603        // → out [1, 1, 2, 2]: [[12, 16], [24, 28]]
12604        let x_storage =
12605            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
12606        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
12607
12608        let graph = Arc::new(RwLock::new(Graph::new()));
12609        let (x_id, w_id, c_id) = {
12610            let mut g = graph.write().unwrap();
12611            let x = g.push(Node {
12612                op: Op::Const,
12613                inputs: vec![],
12614                shape: Shape::from_dims(&[1, 1, 3, 3]),
12615                dtype: DType::F32,
12616            });
12617            let w = g.push(Node {
12618                op: Op::Const,
12619                inputs: vec![],
12620                shape: Shape::from_dims(&[1, 1, 2, 2]),
12621                dtype: DType::F32,
12622            });
12623            let c = g.push(Node {
12624                op: Op::Fused(
12625                    fuel_graph::registry::FusedOps::CONV2D,
12626                    fuel_graph::registry::FusedOpParams::Conv2D {
12627                        stride: (1, 1),
12628                        padding: (0, 0),
12629                        groups: 1,
12630                    },
12631                ),
12632                inputs: vec![x, w],
12633                shape: Shape::from_dims(&[1, 1, 2, 2]),
12634                dtype: DType::F32,
12635            });
12636            g.set_target_backend(c, BackendId::Cpu);
12637            (x, w, c)
12638        };
12639        let mut inputs = StorageCache::new();
12640        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12641        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12642
12643        let (result_arc, result_layout) =
12644            PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12645        assert_eq!(result_layout.shape().dims(), &[1, 1, 2, 2]);
12646
12647        let guard = result_arc.read().unwrap();
12648        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12649            panic!("expected Cpu storage");
12650        };
12651        assert_eq!(c.as_slice::<f32>().unwrap(), &[12.0, 16.0, 24.0, 28.0]);
12652    }
12653
12654    /// E2E: Conv2D with bias (3 inputs).
12655    #[test]
12656    fn pipelined_realize_conv2d_with_bias() {
12657        let x_storage =
12658            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
12659        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
12660        let bias_storage = fuel_memory::from_slice_cpu(&[100.0_f32]);
12661
12662        let graph = Arc::new(RwLock::new(Graph::new()));
12663        let (x_id, w_id, b_id, c_id) = {
12664            let mut g = graph.write().unwrap();
12665            let x = g.push(Node {
12666                op: Op::Const,
12667                inputs: vec![],
12668                shape: Shape::from_dims(&[1, 1, 3, 3]),
12669                dtype: DType::F32,
12670            });
12671            let w = g.push(Node {
12672                op: Op::Const,
12673                inputs: vec![],
12674                shape: Shape::from_dims(&[1, 1, 2, 2]),
12675                dtype: DType::F32,
12676            });
12677            let b = g.push(Node {
12678                op: Op::Const,
12679                inputs: vec![],
12680                shape: Shape::from_dims(&[1]),
12681                dtype: DType::F32,
12682            });
12683            let c = g.push(Node {
12684                op: Op::Fused(
12685                    fuel_graph::registry::FusedOps::CONV2D,
12686                    fuel_graph::registry::FusedOpParams::Conv2D {
12687                        stride: (1, 1),
12688                        padding: (0, 0),
12689                        groups: 1,
12690                    },
12691                ),
12692                inputs: vec![x, w, b],
12693                shape: Shape::from_dims(&[1, 1, 2, 2]),
12694                dtype: DType::F32,
12695            });
12696            g.set_target_backend(c, BackendId::Cpu);
12697            (x, w, b, c)
12698        };
12699        let mut inputs = StorageCache::new();
12700        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12701        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12702        inputs.insert(b_id, Arc::new(RwLock::new(bias_storage)));
12703
12704        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12705        let guard = result_arc.read().unwrap();
12706        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12707            panic!("expected Cpu storage");
12708        };
12709        assert_eq!(c.as_slice::<f32>().unwrap(), &[112.0, 116.0, 124.0, 128.0]);
12710    }
12711
12712    /// E2E: Conv2D in F64 — same 2x2 sum-kernel test as F32, on doubles.
12713    #[test]
12714    fn pipelined_realize_conv2d_f64() {
12715        let x_storage =
12716            fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
12717        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f64, 1.0, 1.0, 1.0]);
12718
12719        let graph = Arc::new(RwLock::new(Graph::new()));
12720        let (x_id, w_id, c_id) = {
12721            let mut g = graph.write().unwrap();
12722            let x = g.push(Node {
12723                op: Op::Const,
12724                inputs: vec![],
12725                shape: Shape::from_dims(&[1, 1, 3, 3]),
12726                dtype: DType::F64,
12727            });
12728            let w = g.push(Node {
12729                op: Op::Const,
12730                inputs: vec![],
12731                shape: Shape::from_dims(&[1, 1, 2, 2]),
12732                dtype: DType::F64,
12733            });
12734            let c = g.push(Node {
12735                op: Op::Fused(
12736                    fuel_graph::registry::FusedOps::CONV2D,
12737                    fuel_graph::registry::FusedOpParams::Conv2D {
12738                        stride: (1, 1),
12739                        padding: (0, 0),
12740                        groups: 1,
12741                    },
12742                ),
12743                inputs: vec![x, w],
12744                shape: Shape::from_dims(&[1, 1, 2, 2]),
12745                dtype: DType::F64,
12746            });
12747            g.set_target_backend(c, BackendId::Cpu);
12748            (x, w, c)
12749        };
12750        let mut inputs = StorageCache::new();
12751        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12752        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12753        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12754        let guard = result_arc.read().unwrap();
12755        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12756            panic!("expected Cpu storage");
12757        };
12758        assert_eq!(c.as_slice::<f64>().unwrap(), &[12.0, 16.0, 24.0, 28.0]);
12759    }
12760
12761    /// E2E: Conv2D in BF16 — f32-accumulator path. Tolerant compare.
12762    #[test]
12763    fn pipelined_realize_conv2d_bf16() {
12764        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]
12765            .iter()
12766            .map(|v| half::bf16::from_f32(*v))
12767            .collect();
12768        let w_data: Vec<half::bf16> = [1.0_f32, 1.0, 1.0, 1.0]
12769            .iter()
12770            .map(|v| half::bf16::from_f32(*v))
12771            .collect();
12772        let x_storage = fuel_memory::from_slice_cpu(&x_data);
12773        let w_storage = fuel_memory::from_slice_cpu(&w_data);
12774
12775        let graph = Arc::new(RwLock::new(Graph::new()));
12776        let (x_id, w_id, c_id) = {
12777            let mut g = graph.write().unwrap();
12778            let x = g.push(Node {
12779                op: Op::Const,
12780                inputs: vec![],
12781                shape: Shape::from_dims(&[1, 1, 3, 3]),
12782                dtype: DType::BF16,
12783            });
12784            let w = g.push(Node {
12785                op: Op::Const,
12786                inputs: vec![],
12787                shape: Shape::from_dims(&[1, 1, 2, 2]),
12788                dtype: DType::BF16,
12789            });
12790            let c = g.push(Node {
12791                op: Op::Fused(
12792                    fuel_graph::registry::FusedOps::CONV2D,
12793                    fuel_graph::registry::FusedOpParams::Conv2D {
12794                        stride: (1, 1),
12795                        padding: (0, 0),
12796                        groups: 1,
12797                    },
12798                ),
12799                inputs: vec![x, w],
12800                shape: Shape::from_dims(&[1, 1, 2, 2]),
12801                dtype: DType::BF16,
12802            });
12803            g.set_target_backend(c, BackendId::Cpu);
12804            (x, w, c)
12805        };
12806        let mut inputs = StorageCache::new();
12807        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12808        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12809        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12810        let guard = result_arc.read().unwrap();
12811        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12812            panic!("expected Cpu storage");
12813        };
12814        let got: Vec<f32> = c
12815            .as_slice::<half::bf16>()
12816            .unwrap()
12817            .iter()
12818            .map(|v| v.to_f32())
12819            .collect();
12820        let want = [12.0_f32, 16.0, 24.0, 28.0];
12821        for (g, w) in got.iter().zip(want.iter()) {
12822            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
12823        }
12824    }
12825
12826    /// E2E: Conv2D in F16 — f32-accumulator path. Tolerant compare.
12827    #[test]
12828    fn pipelined_realize_conv2d_f16() {
12829        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]
12830            .iter()
12831            .map(|v| half::f16::from_f32(*v))
12832            .collect();
12833        let w_data: Vec<half::f16> = [1.0_f32, 1.0, 1.0, 1.0]
12834            .iter()
12835            .map(|v| half::f16::from_f32(*v))
12836            .collect();
12837        let x_storage = fuel_memory::from_slice_cpu(&x_data);
12838        let w_storage = fuel_memory::from_slice_cpu(&w_data);
12839
12840        let graph = Arc::new(RwLock::new(Graph::new()));
12841        let (x_id, w_id, c_id) = {
12842            let mut g = graph.write().unwrap();
12843            let x = g.push(Node {
12844                op: Op::Const,
12845                inputs: vec![],
12846                shape: Shape::from_dims(&[1, 1, 3, 3]),
12847                dtype: DType::F16,
12848            });
12849            let w = g.push(Node {
12850                op: Op::Const,
12851                inputs: vec![],
12852                shape: Shape::from_dims(&[1, 1, 2, 2]),
12853                dtype: DType::F16,
12854            });
12855            let c = g.push(Node {
12856                op: Op::Fused(
12857                    fuel_graph::registry::FusedOps::CONV2D,
12858                    fuel_graph::registry::FusedOpParams::Conv2D {
12859                        stride: (1, 1),
12860                        padding: (0, 0),
12861                        groups: 1,
12862                    },
12863                ),
12864                inputs: vec![x, w],
12865                shape: Shape::from_dims(&[1, 1, 2, 2]),
12866                dtype: DType::F16,
12867            });
12868            g.set_target_backend(c, BackendId::Cpu);
12869            (x, w, c)
12870        };
12871        let mut inputs = StorageCache::new();
12872        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12873        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12874        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12875        let guard = result_arc.read().unwrap();
12876        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12877            panic!("expected Cpu storage");
12878        };
12879        let got: Vec<f32> = c
12880            .as_slice::<half::f16>()
12881            .unwrap()
12882            .iter()
12883            .map(|v| v.to_f32())
12884            .collect();
12885        let want = [12.0_f32, 16.0, 24.0, 28.0];
12886        for (g, w) in got.iter().zip(want.iter()) {
12887            assert!((g - w).abs() < 0.05, "got {got:?} want {want:?}");
12888        }
12889    }
12890
12891    /// E2E: Op::PagedAttn — F32, single-head, B=1, Sq=1.
12892    /// Same setup as the FlashAttn smoke test, but the K/V live in a
12893    /// paged cache that we look up via block_table.
12894    /// Layout:
12895    ///   block_size=2, num_blocks=1, max_blocks_per_seq=1.
12896    ///   k_cache shape [1, 2, 1, 2] = num_blocks × block_size × Hkv × D.
12897    ///   k_cache[block 0, slot 0, h 0] = [1, 0]
12898    ///   k_cache[block 0, slot 1, h 0] = [0, 1]
12899    ///   v_cache values: [10, 0] / [0, 10]
12900    ///   block_table[b=0, logical_block 0] = 0 (physical)
12901    ///   context_lens[0] = 2
12902    ///   q[0, 0, 0] = [2, 0]
12903    /// Causal is implicit (q_pos = ctx_len - Sq + sq = 2 - 1 + 0 = 1, both keys admissible).
12904    /// Same softmax math as FlashAttn → ~[8.808, 1.192].
12905    #[test]
12906    fn pipelined_realize_paged_attn_f32() {
12907        let q = fuel_memory::from_slice_cpu(&[2.0_f32, 0.0]);
12908        let k_cache = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
12909        let v_cache = fuel_memory::from_slice_cpu(&[10.0_f32, 0.0, 0.0, 10.0]);
12910        let block_table_u32 = fuel_memory::Storage::new(
12911            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
12912                0_u32,
12913            ])),
12914            DType::U32,
12915        );
12916        let context_lens_u32 = fuel_memory::Storage::new(
12917            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
12918                2_u32,
12919            ])),
12920            DType::U32,
12921        );
12922        let graph = Arc::new(RwLock::new(Graph::new()));
12923        let (q_id, kc_id, vc_id, bt_id, cl_id, op_id) = {
12924            let mut g = graph.write().unwrap();
12925            let q = g.push(Node {
12926                op: Op::Const,
12927                inputs: vec![],
12928                shape: Shape::from_dims(&[1, 1, 1, 2]),
12929                dtype: DType::F32,
12930            });
12931            let kc = g.push(Node {
12932                op: Op::Const,
12933                inputs: vec![],
12934                shape: Shape::from_dims(&[1, 2, 1, 2]),
12935                dtype: DType::F32,
12936            });
12937            let vc = g.push(Node {
12938                op: Op::Const,
12939                inputs: vec![],
12940                shape: Shape::from_dims(&[1, 2, 1, 2]),
12941                dtype: DType::F32,
12942            });
12943            let bt = g.push(Node {
12944                op: Op::Const,
12945                inputs: vec![],
12946                shape: Shape::from_dims(&[1, 1]),
12947                dtype: DType::U32,
12948            });
12949            let cl = g.push(Node {
12950                op: Op::Const,
12951                inputs: vec![],
12952                shape: Shape::from_dims(&[1]),
12953                dtype: DType::U32,
12954            });
12955            let op = g.push(Node {
12956                op: Op::Fused(
12957                    fuel_graph::registry::FusedOps::PAGED_ATTN,
12958                    fuel_graph::registry::FusedOpParams::PagedAttn {
12959                        softmax_scale: 1.0,
12960                        block_size: 2,
12961                        softcap: None,
12962                    },
12963                ),
12964                inputs: vec![q, kc, vc, bt, cl],
12965                shape: Shape::from_dims(&[1, 1, 1, 2]),
12966                dtype: DType::F32,
12967            });
12968            g.set_target_backend(op, BackendId::Cpu);
12969            (q, kc, vc, bt, cl, op)
12970        };
12971        let mut inputs = StorageCache::new();
12972        inputs.insert(q_id, Arc::new(RwLock::new(q)));
12973        inputs.insert(kc_id, Arc::new(RwLock::new(k_cache)));
12974        inputs.insert(vc_id, Arc::new(RwLock::new(v_cache)));
12975        inputs.insert(bt_id, Arc::new(RwLock::new(block_table_u32)));
12976        inputs.insert(cl_id, Arc::new(RwLock::new(context_lens_u32)));
12977        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12978        let guard = result_arc.read().unwrap();
12979        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12980            panic!("expected Cpu storage");
12981        };
12982        let r = c.as_slice::<f32>().unwrap();
12983        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
12984        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
12985        assert!(
12986            (r[0] - 10.0 * expected_p0).abs() < 1e-5,
12987            "row[0]: got {} expected {}",
12988            r[0],
12989            10.0 * expected_p0
12990        );
12991        assert!(
12992            (r[1] - 10.0 * expected_p1).abs() < 1e-5,
12993            "row[1]: got {} expected {}",
12994            r[1],
12995            10.0 * expected_p1
12996        );
12997    }
12998
12999    /// E2E: PagedAttn BF16 — same single-row test, tolerant.
13000    #[test]
13001    fn pipelined_realize_paged_attn_bf16() {
13002        let q_v: Vec<half::bf16> = [2.0_f32, 0.0]
13003            .iter()
13004            .map(|x| half::bf16::from_f32(*x))
13005            .collect();
13006        let kc_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0]
13007            .iter()
13008            .map(|x| half::bf16::from_f32(*x))
13009            .collect();
13010        let vc_v: Vec<half::bf16> = [10.0_f32, 0.0, 0.0, 10.0]
13011            .iter()
13012            .map(|x| half::bf16::from_f32(*x))
13013            .collect();
13014        let q = fuel_memory::from_slice_cpu(&q_v);
13015        let k_cache = fuel_memory::from_slice_cpu(&kc_v);
13016        let v_cache = fuel_memory::from_slice_cpu(&vc_v);
13017        let bt = fuel_memory::Storage::new(
13018            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
13019                0_u32,
13020            ])),
13021            DType::U32,
13022        );
13023        let cl = fuel_memory::Storage::new(
13024            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
13025                2_u32,
13026            ])),
13027            DType::U32,
13028        );
13029        let graph = Arc::new(RwLock::new(Graph::new()));
13030        let (q_id, kc_id, vc_id, bt_id, cl_id, op_id) = {
13031            let mut g = graph.write().unwrap();
13032            let q = g.push(Node {
13033                op: Op::Const,
13034                inputs: vec![],
13035                shape: Shape::from_dims(&[1, 1, 1, 2]),
13036                dtype: DType::BF16,
13037            });
13038            let kc = g.push(Node {
13039                op: Op::Const,
13040                inputs: vec![],
13041                shape: Shape::from_dims(&[1, 2, 1, 2]),
13042                dtype: DType::BF16,
13043            });
13044            let vc = g.push(Node {
13045                op: Op::Const,
13046                inputs: vec![],
13047                shape: Shape::from_dims(&[1, 2, 1, 2]),
13048                dtype: DType::BF16,
13049            });
13050            let bt = g.push(Node {
13051                op: Op::Const,
13052                inputs: vec![],
13053                shape: Shape::from_dims(&[1, 1]),
13054                dtype: DType::U32,
13055            });
13056            let cl = g.push(Node {
13057                op: Op::Const,
13058                inputs: vec![],
13059                shape: Shape::from_dims(&[1]),
13060                dtype: DType::U32,
13061            });
13062            let op = g.push(Node {
13063                op: Op::Fused(
13064                    fuel_graph::registry::FusedOps::PAGED_ATTN,
13065                    fuel_graph::registry::FusedOpParams::PagedAttn {
13066                        softmax_scale: 1.0,
13067                        block_size: 2,
13068                        softcap: None,
13069                    },
13070                ),
13071                inputs: vec![q, kc, vc, bt, cl],
13072                shape: Shape::from_dims(&[1, 1, 1, 2]),
13073                dtype: DType::BF16,
13074            });
13075            g.set_target_backend(op, BackendId::Cpu);
13076            (q, kc, vc, bt, cl, op)
13077        };
13078        let mut inputs = StorageCache::new();
13079        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13080        inputs.insert(kc_id, Arc::new(RwLock::new(k_cache)));
13081        inputs.insert(vc_id, Arc::new(RwLock::new(v_cache)));
13082        inputs.insert(bt_id, Arc::new(RwLock::new(bt)));
13083        inputs.insert(cl_id, Arc::new(RwLock::new(cl)));
13084        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13085        let guard = result_arc.read().unwrap();
13086        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13087            panic!("expected Cpu storage");
13088        };
13089        let got: Vec<f32> = c
13090            .as_slice::<half::bf16>()
13091            .unwrap()
13092            .iter()
13093            .map(|v| v.to_f32())
13094            .collect();
13095        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
13096        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
13097        let want = [10.0 * expected_p0, 10.0 * expected_p1];
13098        for (g, w) in got.iter().zip(want.iter()) {
13099            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
13100        }
13101    }
13102
13103    /// E2E: Op::FlashAttn — F32 single-head, single-batch, no mask.
13104    /// q = [[2.0, 0.0]], k = [[1.0, 0.0], [0.0, 1.0]], v = [[10, 0], [0, 10]]
13105    /// scale = 1.0
13106    /// scores = q · kᵀ = [2.0, 0.0]
13107    /// softmax = [e^2/(e^2+1), 1/(e^2+1)] ≈ [0.8808, 0.1192]
13108    /// out = softmax @ v = [10*0.8808, 10*0.1192] ≈ [8.808, 1.192]
13109    #[test]
13110    fn pipelined_realize_flash_attn_f32() {
13111        // [B=1, H=1, S=1or2, D=2]
13112        let q = fuel_memory::from_slice_cpu(&[2.0_f32, 0.0]);
13113        let k = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13114        let v = fuel_memory::from_slice_cpu(&[10.0_f32, 0.0, 0.0, 10.0]);
13115        let graph = Arc::new(RwLock::new(Graph::new()));
13116        let (q_id, k_id, v_id, op_id) = {
13117            let mut g = graph.write().unwrap();
13118            let q = g.push(Node {
13119                op: Op::Const,
13120                inputs: vec![],
13121                shape: Shape::from_dims(&[1, 1, 1, 2]),
13122                dtype: DType::F32,
13123            });
13124            let k = g.push(Node {
13125                op: Op::Const,
13126                inputs: vec![],
13127                shape: Shape::from_dims(&[1, 1, 2, 2]),
13128                dtype: DType::F32,
13129            });
13130            let v = g.push(Node {
13131                op: Op::Const,
13132                inputs: vec![],
13133                shape: Shape::from_dims(&[1, 1, 2, 2]),
13134                dtype: DType::F32,
13135            });
13136            let op = g.push(Node {
13137                op: Op::Fused(
13138                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13139                    fuel_graph::registry::FusedOpParams::FlashAttn {
13140                        softmax_scale: 1.0,
13141                        causal: false,
13142                        window_size_left: None,
13143                        window_size_right: None,
13144                        softcap: None,
13145                        k_len: None,
13146                    },
13147                ),
13148                inputs: vec![q, k, v],
13149                shape: Shape::from_dims(&[1, 1, 1, 2]),
13150                dtype: DType::F32,
13151            });
13152            g.set_target_backend(op, BackendId::Cpu);
13153            (q, k, v, op)
13154        };
13155        let mut inputs = StorageCache::new();
13156        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13157        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13158        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13159        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13160        let guard = result_arc.read().unwrap();
13161        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13162            panic!("expected Cpu storage");
13163        };
13164        let r = c.as_slice::<f32>().unwrap();
13165        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
13166        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
13167        assert!(
13168            (r[0] - 10.0 * expected_p0).abs() < 1e-5,
13169            "row[0]: got {} expected {}",
13170            r[0],
13171            10.0 * expected_p0
13172        );
13173        assert!(
13174            (r[1] - 10.0 * expected_p1).abs() < 1e-5,
13175            "row[1]: got {} expected {}",
13176            r[1],
13177            10.0 * expected_p1
13178        );
13179    }
13180
13181    /// E2E: FlashAttn with causal mask — second query position
13182    /// attends to both keys (positions 0 and 1), first only attends
13183    /// to key 0 (everything beyond is masked).
13184    #[test]
13185    fn pipelined_realize_flash_attn_causal_f32() {
13186        // q [1,1,2,2]: query 0 = [1, 0], query 1 = [0, 1]
13187        // k [1,1,2,2]: keys = [[1, 0], [0, 1]]
13188        // v [1,1,2,2]: values = [[5, 6], [7, 8]]
13189        // softmax_scale=1, causal:
13190        //   query 0: only key 0 admissible → out = v[0] = [5, 6]
13191        //   query 1: both admissible. scores = q1·k = [0, 1]
13192        //            softmax = [1/(e+1), e/(e+1)]
13193        //            out = scores · v = [(5)/(e+1) + 7e/(e+1), 6/(e+1) + 8e/(e+1)]
13194        let q = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13195        let k = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13196        let v = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0, 7.0, 8.0]);
13197        let graph = Arc::new(RwLock::new(Graph::new()));
13198        let (q_id, k_id, v_id, op_id) = {
13199            let mut g = graph.write().unwrap();
13200            let q = g.push(Node {
13201                op: Op::Const,
13202                inputs: vec![],
13203                shape: Shape::from_dims(&[1, 1, 2, 2]),
13204                dtype: DType::F32,
13205            });
13206            let k = g.push(Node {
13207                op: Op::Const,
13208                inputs: vec![],
13209                shape: Shape::from_dims(&[1, 1, 2, 2]),
13210                dtype: DType::F32,
13211            });
13212            let v = g.push(Node {
13213                op: Op::Const,
13214                inputs: vec![],
13215                shape: Shape::from_dims(&[1, 1, 2, 2]),
13216                dtype: DType::F32,
13217            });
13218            let op = g.push(Node {
13219                op: Op::Fused(
13220                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13221                    fuel_graph::registry::FusedOpParams::FlashAttn {
13222                        softmax_scale: 1.0,
13223                        causal: true,
13224                        window_size_left: None,
13225                        window_size_right: None,
13226                        softcap: None,
13227                        k_len: None,
13228                    },
13229                ),
13230                inputs: vec![q, k, v],
13231                shape: Shape::from_dims(&[1, 1, 2, 2]),
13232                dtype: DType::F32,
13233            });
13234            g.set_target_backend(op, BackendId::Cpu);
13235            (q, k, v, op)
13236        };
13237        let mut inputs = StorageCache::new();
13238        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13239        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13240        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13241        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13242        let guard = result_arc.read().unwrap();
13243        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13244            panic!("expected Cpu storage");
13245        };
13246        let r = c.as_slice::<f32>().unwrap();
13247        // Query 0 sees only key 0 → output = v[0]
13248        assert!((r[0] - 5.0).abs() < 1e-5, "got {}", r[0]);
13249        assert!((r[1] - 6.0).abs() < 1e-5, "got {}", r[1]);
13250        // Query 1 sees both. softmax([0, 1]) = [1/(e+1), e/(e+1)]
13251        let denom = (1.0_f32).exp() + 1.0;
13252        let expected_a = 5.0 / denom + 7.0 * (1.0_f32).exp() / denom;
13253        let expected_b = 6.0 / denom + 8.0 * (1.0_f32).exp() / denom;
13254        assert!(
13255            (r[2] - expected_a).abs() < 1e-5,
13256            "row1[0]: got {} expected {}",
13257            r[2],
13258            expected_a
13259        );
13260        assert!(
13261            (r[3] - expected_b).abs() < 1e-5,
13262            "row1[1]: got {} expected {}",
13263            r[3],
13264            expected_b
13265        );
13266    }
13267
13268    /// E2E: FlashAttn over a fixed-**capacity** K/V with a runtime
13269    /// `k_len` resolved through a `SymEnv` (Phase D symbolic extents).
13270    /// Only the first `k_len` rows are attended; trailing "poison" rows
13271    /// in the capacity buffer are ignored, and the causal mask is
13272    /// bottom-right-aligned at offset `k_len - Sq`. This is flash decode
13273    /// over a persistent KV-cache: K/V are `[.., max_seq, ..]` capacity
13274    /// and the live prefix grows per token.
13275    #[test]
13276    fn pipelined_realize_flash_attn_dynamic_k_len() {
13277        use fuel_ir::{DynScalar, SymId};
13278        // q [1,1,2,2]; K/V capacity [1,1,4,2]; bind k_len = 3 so row 3
13279        // (the "poison" row) is never attended.
13280        let q = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13281        let k = fuel_memory::from_slice_cpu(&[
13282            1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0, 100.0,
13283            100.0, // poison row 3 — must be ignored (k_len=3)
13284        ]);
13285        let v = fuel_memory::from_slice_cpu(&[
13286            5.0_f32, 6.0, 7.0, 8.0, 9.0, 10.0, 999.0,
13287            999.0, // poison row 3 — must be ignored
13288        ]);
13289        let sym = SymId(0);
13290        let graph = Arc::new(RwLock::new(Graph::new()));
13291        let (q_id, k_id, v_id, op_id) = {
13292            let mut g = graph.write().unwrap();
13293            let q = g.push(Node {
13294                op: Op::Const,
13295                inputs: vec![],
13296                shape: Shape::from_dims(&[1, 1, 2, 2]),
13297                dtype: DType::F32,
13298            });
13299            let k = g.push(Node {
13300                op: Op::Const,
13301                inputs: vec![],
13302                shape: Shape::from_dims(&[1, 1, 4, 2]),
13303                dtype: DType::F32,
13304            });
13305            let v = g.push(Node {
13306                op: Op::Const,
13307                inputs: vec![],
13308                shape: Shape::from_dims(&[1, 1, 4, 2]),
13309                dtype: DType::F32,
13310            });
13311            let op = g.push(Node {
13312                op: Op::Fused(
13313                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13314                    fuel_graph::registry::FusedOpParams::FlashAttn {
13315                        softmax_scale: 1.0,
13316                        causal: true,
13317                        window_size_left: None,
13318                        window_size_right: None,
13319                        softcap: None,
13320                        k_len: Some(DynScalar::Sym(sym)),
13321                    },
13322                ),
13323                inputs: vec![q, k, v],
13324                shape: Shape::from_dims(&[1, 1, 2, 2]),
13325                dtype: DType::F32,
13326            });
13327            g.set_target_backend(op, BackendId::Cpu);
13328            (q, k, v, op)
13329        };
13330        let mut inputs = StorageCache::new();
13331        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13332        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13333        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13334        let mut env = SymEnv::new();
13335        env.bind(sym, 3).unwrap();
13336        let (result_arc, _) = PipelinedExecutor::realize_with_env(graph, op_id, inputs, env)
13337            .expect("realize_with_env");
13338        let guard = result_arc.read().unwrap();
13339        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13340            panic!("expected Cpu storage");
13341        };
13342        let r = c.as_slice::<f32>().unwrap();
13343        let e = 1.0_f32.exp();
13344        // causal_offset = k_len - Sq = 3 - 2 = 1.
13345        // Query 0 (abs pos 1): keys {0,1}. scores [1,0] → softmax [e,1]/(e+1).
13346        let d0 = e + 1.0;
13347        let e0x = (5.0 * e + 7.0) / d0;
13348        let e0y = (6.0 * e + 8.0) / d0;
13349        // Query 1 (abs pos 2): keys {0,1,2}. scores [0,1,1] → [1,e,e]/(1+2e).
13350        let d1 = 1.0 + 2.0 * e;
13351        let e1x = (5.0 + 7.0 * e + 9.0 * e) / d1;
13352        let e1y = (6.0 + 8.0 * e + 10.0 * e) / d1;
13353        for (got, want) in r.iter().zip([e0x, e0y, e1x, e1y].iter()) {
13354            assert!(
13355                (got - want).abs() < 1e-4,
13356                "flash dyn k_len: got {got}, want {want} (full output {r:?}); \
13357                 a poison-contaminated value means the capacity rows past k_len leaked in",
13358            );
13359        }
13360    }
13361
13362    /// A flash `k_len` symbol unbound in the `SymEnv` surfaces a typed
13363    /// error at realize (never a panic).
13364    #[test]
13365    fn pipelined_realize_flash_attn_dynamic_k_len_unbound_errors() {
13366        use fuel_ir::{DynScalar, SymId};
13367        let q = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13368        let k = fuel_memory::from_slice_cpu(&[0.0_f32; 16]);
13369        let v = fuel_memory::from_slice_cpu(&[0.0_f32; 16]);
13370        let graph = Arc::new(RwLock::new(Graph::new()));
13371        let (q_id, k_id, v_id, op_id) = {
13372            let mut g = graph.write().unwrap();
13373            let q = g.push(Node {
13374                op: Op::Const,
13375                inputs: vec![],
13376                shape: Shape::from_dims(&[1, 1, 2, 2]),
13377                dtype: DType::F32,
13378            });
13379            let k = g.push(Node {
13380                op: Op::Const,
13381                inputs: vec![],
13382                shape: Shape::from_dims(&[1, 1, 4, 2]),
13383                dtype: DType::F32,
13384            });
13385            let v = g.push(Node {
13386                op: Op::Const,
13387                inputs: vec![],
13388                shape: Shape::from_dims(&[1, 1, 4, 2]),
13389                dtype: DType::F32,
13390            });
13391            let op = g.push(Node {
13392                op: Op::Fused(
13393                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13394                    fuel_graph::registry::FusedOpParams::FlashAttn {
13395                        softmax_scale: 1.0,
13396                        causal: true,
13397                        window_size_left: None,
13398                        window_size_right: None,
13399                        softcap: None,
13400                        k_len: Some(DynScalar::Sym(SymId(0))),
13401                    },
13402                ),
13403                inputs: vec![q, k, v],
13404                shape: Shape::from_dims(&[1, 1, 2, 2]),
13405                dtype: DType::F32,
13406            });
13407            g.set_target_backend(op, BackendId::Cpu);
13408            (q, k, v, op)
13409        };
13410        let mut inputs = StorageCache::new();
13411        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13412        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13413        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13414        // Empty env — the k_len symbol is unbound.
13415        let result = PipelinedExecutor::realize_with_env(graph, op_id, inputs, SymEnv::new());
13416        assert!(
13417            result.is_err(),
13418            "unbound flash k_len symbol must surface a typed error"
13419        );
13420    }
13421
13422    /// E2E: FlashAttn BF16 — same single-row test as f32, tolerant.
13423    #[test]
13424    fn pipelined_realize_flash_attn_bf16() {
13425        let q_v: Vec<half::bf16> = [2.0_f32, 0.0]
13426            .iter()
13427            .map(|x| half::bf16::from_f32(*x))
13428            .collect();
13429        let k_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0]
13430            .iter()
13431            .map(|x| half::bf16::from_f32(*x))
13432            .collect();
13433        let v_v: Vec<half::bf16> = [10.0_f32, 0.0, 0.0, 10.0]
13434            .iter()
13435            .map(|x| half::bf16::from_f32(*x))
13436            .collect();
13437        let q = fuel_memory::from_slice_cpu(&q_v);
13438        let k = fuel_memory::from_slice_cpu(&k_v);
13439        let v = fuel_memory::from_slice_cpu(&v_v);
13440        let graph = Arc::new(RwLock::new(Graph::new()));
13441        let (q_id, k_id, v_id, op_id) = {
13442            let mut g = graph.write().unwrap();
13443            let q = g.push(Node {
13444                op: Op::Const,
13445                inputs: vec![],
13446                shape: Shape::from_dims(&[1, 1, 1, 2]),
13447                dtype: DType::BF16,
13448            });
13449            let k = g.push(Node {
13450                op: Op::Const,
13451                inputs: vec![],
13452                shape: Shape::from_dims(&[1, 1, 2, 2]),
13453                dtype: DType::BF16,
13454            });
13455            let v = g.push(Node {
13456                op: Op::Const,
13457                inputs: vec![],
13458                shape: Shape::from_dims(&[1, 1, 2, 2]),
13459                dtype: DType::BF16,
13460            });
13461            let op = g.push(Node {
13462                op: Op::Fused(
13463                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13464                    fuel_graph::registry::FusedOpParams::FlashAttn {
13465                        softmax_scale: 1.0,
13466                        causal: false,
13467                        window_size_left: None,
13468                        window_size_right: None,
13469                        softcap: None,
13470                        k_len: None,
13471                    },
13472                ),
13473                inputs: vec![q, k, v],
13474                shape: Shape::from_dims(&[1, 1, 1, 2]),
13475                dtype: DType::BF16,
13476            });
13477            g.set_target_backend(op, BackendId::Cpu);
13478            (q, k, v, op)
13479        };
13480        let mut inputs = StorageCache::new();
13481        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13482        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13483        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13484        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13485        let guard = result_arc.read().unwrap();
13486        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13487            panic!("expected Cpu storage");
13488        };
13489        let got: Vec<f32> = c
13490            .as_slice::<half::bf16>()
13491            .unwrap()
13492            .iter()
13493            .map(|v| v.to_f32())
13494            .collect();
13495        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
13496        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
13497        let want = [10.0 * expected_p0, 10.0 * expected_p1];
13498        for (g, w) in got.iter().zip(want.iter()) {
13499            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
13500        }
13501    }
13502
13503    /// E2E: Op::FusedLinear — F32. a[1,2,3] @ b[1,3,2] + bias[2].
13504    /// a = [[[1,2,3],[4,5,6]]], b = [[[1,0],[0,1],[1,1]]], bias=[10,20]
13505    /// matmul = [[1+0+3, 0+2+3], [4+0+6, 0+5+6]] = [[4, 5], [10, 11]]
13506    /// + bias = [[14, 25], [20, 31]]
13507    #[test]
13508    fn pipelined_realize_fused_linear_f32() {
13509        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
13510        let b = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0]);
13511        let bias = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
13512        let graph = Arc::new(RwLock::new(Graph::new()));
13513        let (a_id, b_id, bias_id, op_id) = {
13514            let mut g = graph.write().unwrap();
13515            let a = g.push(Node {
13516                op: Op::Const,
13517                inputs: vec![],
13518                shape: Shape::from_dims(&[1, 2, 3]),
13519                dtype: DType::F32,
13520            });
13521            let b = g.push(Node {
13522                op: Op::Const,
13523                inputs: vec![],
13524                shape: Shape::from_dims(&[1, 3, 2]),
13525                dtype: DType::F32,
13526            });
13527            let bias = g.push(Node {
13528                op: Op::Const,
13529                inputs: vec![],
13530                shape: Shape::from_dims(&[2]),
13531                dtype: DType::F32,
13532            });
13533            let op = g.push(Node {
13534                op: Op::Fused(
13535                    fuel_graph::registry::FusedOps::FUSED_LINEAR,
13536                    fuel_graph::registry::FusedOpParams::FusedLinear,
13537                ),
13538                inputs: vec![a, b, bias],
13539                shape: Shape::from_dims(&[1, 2, 2]),
13540                dtype: DType::F32,
13541            });
13542            g.set_target_backend(op, BackendId::Cpu);
13543            (a, b, bias, op)
13544        };
13545        let mut inputs = StorageCache::new();
13546        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13547        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13548        inputs.insert(bias_id, Arc::new(RwLock::new(bias)));
13549        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13550        let guard = result_arc.read().unwrap();
13551        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13552            panic!("expected Cpu storage");
13553        };
13554        assert_eq!(c.as_slice::<f32>().unwrap(), &[14.0, 25.0, 20.0, 31.0]);
13555    }
13556
13557    /// E2E: FusedLinear F64 — same shape test on doubles.
13558    #[test]
13559    fn pipelined_realize_fused_linear_f64() {
13560        let a = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
13561        let b = fuel_memory::from_slice_cpu(&[1.0_f64, 0.0, 0.0, 1.0, 1.0, 1.0]);
13562        let bias = fuel_memory::from_slice_cpu(&[10.0_f64, 20.0]);
13563        let graph = Arc::new(RwLock::new(Graph::new()));
13564        let (a_id, b_id, bias_id, op_id) = {
13565            let mut g = graph.write().unwrap();
13566            let a = g.push(Node {
13567                op: Op::Const,
13568                inputs: vec![],
13569                shape: Shape::from_dims(&[1, 2, 3]),
13570                dtype: DType::F64,
13571            });
13572            let b = g.push(Node {
13573                op: Op::Const,
13574                inputs: vec![],
13575                shape: Shape::from_dims(&[1, 3, 2]),
13576                dtype: DType::F64,
13577            });
13578            let bias = g.push(Node {
13579                op: Op::Const,
13580                inputs: vec![],
13581                shape: Shape::from_dims(&[2]),
13582                dtype: DType::F64,
13583            });
13584            let op = g.push(Node {
13585                op: Op::Fused(
13586                    fuel_graph::registry::FusedOps::FUSED_LINEAR,
13587                    fuel_graph::registry::FusedOpParams::FusedLinear,
13588                ),
13589                inputs: vec![a, b, bias],
13590                shape: Shape::from_dims(&[1, 2, 2]),
13591                dtype: DType::F64,
13592            });
13593            g.set_target_backend(op, BackendId::Cpu);
13594            (a, b, bias, op)
13595        };
13596        let mut inputs = StorageCache::new();
13597        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13598        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13599        inputs.insert(bias_id, Arc::new(RwLock::new(bias)));
13600        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13601        let guard = result_arc.read().unwrap();
13602        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13603            panic!("expected Cpu storage");
13604        };
13605        assert_eq!(c.as_slice::<f64>().unwrap(), &[14.0, 25.0, 20.0, 31.0]);
13606    }
13607
13608    /// E2E: FusedLinear BF16 — tolerant compare.
13609    #[test]
13610    fn pipelined_realize_fused_linear_bf16() {
13611        let a_v: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]
13612            .iter()
13613            .map(|x| half::bf16::from_f32(*x))
13614            .collect();
13615        let b_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0]
13616            .iter()
13617            .map(|x| half::bf16::from_f32(*x))
13618            .collect();
13619        let bias_v: Vec<half::bf16> = [10.0_f32, 20.0]
13620            .iter()
13621            .map(|x| half::bf16::from_f32(*x))
13622            .collect();
13623        let a = fuel_memory::from_slice_cpu(&a_v);
13624        let b = fuel_memory::from_slice_cpu(&b_v);
13625        let bias = fuel_memory::from_slice_cpu(&bias_v);
13626        let graph = Arc::new(RwLock::new(Graph::new()));
13627        let (a_id, b_id, bias_id, op_id) = {
13628            let mut g = graph.write().unwrap();
13629            let a = g.push(Node {
13630                op: Op::Const,
13631                inputs: vec![],
13632                shape: Shape::from_dims(&[1, 2, 3]),
13633                dtype: DType::BF16,
13634            });
13635            let b = g.push(Node {
13636                op: Op::Const,
13637                inputs: vec![],
13638                shape: Shape::from_dims(&[1, 3, 2]),
13639                dtype: DType::BF16,
13640            });
13641            let bias = g.push(Node {
13642                op: Op::Const,
13643                inputs: vec![],
13644                shape: Shape::from_dims(&[2]),
13645                dtype: DType::BF16,
13646            });
13647            let op = g.push(Node {
13648                op: Op::Fused(
13649                    fuel_graph::registry::FusedOps::FUSED_LINEAR,
13650                    fuel_graph::registry::FusedOpParams::FusedLinear,
13651                ),
13652                inputs: vec![a, b, bias],
13653                shape: Shape::from_dims(&[1, 2, 2]),
13654                dtype: DType::BF16,
13655            });
13656            g.set_target_backend(op, BackendId::Cpu);
13657            (a, b, bias, op)
13658        };
13659        let mut inputs = StorageCache::new();
13660        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13661        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13662        inputs.insert(bias_id, Arc::new(RwLock::new(bias)));
13663        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13664        let guard = result_arc.read().unwrap();
13665        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13666            panic!("expected Cpu storage");
13667        };
13668        let got: Vec<f32> = c
13669            .as_slice::<half::bf16>()
13670            .unwrap()
13671            .iter()
13672            .map(|v| v.to_f32())
13673            .collect();
13674        let want = [14.0_f32, 25.0, 20.0, 31.0];
13675        for (g, w) in got.iter().zip(want.iter()) {
13676            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
13677        }
13678    }
13679
13680    /// E2E: Op::ReduceSumTo — sum the leading axis of a [2,3] tensor.
13681    /// Input [[1,2,3],[4,5,6]] → output [5,7,9].
13682    #[test]
13683    fn pipelined_realize_reduce_sum_to_f32_drops_leading_axis() {
13684        let v = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
13685        let graph = Arc::new(RwLock::new(Graph::new()));
13686        let (in_id, op_id) = {
13687            let mut g = graph.write().unwrap();
13688            let in_id = g.push(Node {
13689                op: Op::Const,
13690                inputs: vec![],
13691                shape: Shape::from_dims(&[2, 3]),
13692                dtype: DType::F32,
13693            });
13694            let op_id = g.push(Node {
13695                op: Op::ReduceSumTo(Shape::from_dims(&[3])),
13696                inputs: vec![in_id],
13697                shape: Shape::from_dims(&[3]),
13698                dtype: DType::F32,
13699            });
13700            g.set_target_backend(op_id, BackendId::Cpu);
13701            (in_id, op_id)
13702        };
13703        let mut inputs = StorageCache::new();
13704        inputs.insert(in_id, Arc::new(RwLock::new(v)));
13705        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13706        let guard = result_arc.read().unwrap();
13707        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13708            panic!("expected Cpu storage");
13709        };
13710        assert_eq!(c.as_slice::<f32>().unwrap(), &[5.0, 7.0, 9.0]);
13711    }
13712
13713    /// E2E: Op::ReduceSumTo — keep-dim with 1 in the middle.
13714    /// Input [2,3,4] → [2,1,4] sums along dim 1.
13715    #[test]
13716    fn pipelined_realize_reduce_sum_to_f32_keepdim_middle() {
13717        // [2,3,4]: layer 0 = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
13718        //          layer 1 = [[13..16],[17..20],[21..24]]
13719        let mut v: Vec<f32> = (1..=24).map(|x| x as f32).collect();
13720        let _ = &mut v;
13721        let s = fuel_memory::from_slice_cpu(&v);
13722        let graph = Arc::new(RwLock::new(Graph::new()));
13723        let (in_id, op_id) = {
13724            let mut g = graph.write().unwrap();
13725            let in_id = g.push(Node {
13726                op: Op::Const,
13727                inputs: vec![],
13728                shape: Shape::from_dims(&[2, 3, 4]),
13729                dtype: DType::F32,
13730            });
13731            let op_id = g.push(Node {
13732                op: Op::ReduceSumTo(Shape::from_dims(&[2, 1, 4])),
13733                inputs: vec![in_id],
13734                shape: Shape::from_dims(&[2, 1, 4]),
13735                dtype: DType::F32,
13736            });
13737            g.set_target_backend(op_id, BackendId::Cpu);
13738            (in_id, op_id)
13739        };
13740        let mut inputs = StorageCache::new();
13741        inputs.insert(in_id, Arc::new(RwLock::new(s)));
13742        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13743        let guard = result_arc.read().unwrap();
13744        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13745            panic!("expected Cpu storage");
13746        };
13747        // layer0 dim1-sum: col j = 1+5+9, 2+6+10, 3+7+11, 4+8+12 = [15,18,21,24]
13748        // layer1 dim1-sum: col j = 13+17+21, 14+18+22, 15+19+23, 16+20+24 = [51,54,57,60]
13749        assert_eq!(
13750            c.as_slice::<f32>().unwrap(),
13751            &[15.0, 18.0, 21.0, 24.0, 51.0, 54.0, 57.0, 60.0],
13752        );
13753    }
13754
13755    /// E2E: ReduceSumTo F64 — same drop-leading-axis test on doubles.
13756    #[test]
13757    fn pipelined_realize_reduce_sum_to_f64() {
13758        let v = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
13759        let graph = Arc::new(RwLock::new(Graph::new()));
13760        let (in_id, op_id) = {
13761            let mut g = graph.write().unwrap();
13762            let in_id = g.push(Node {
13763                op: Op::Const,
13764                inputs: vec![],
13765                shape: Shape::from_dims(&[2, 3]),
13766                dtype: DType::F64,
13767            });
13768            let op_id = g.push(Node {
13769                op: Op::ReduceSumTo(Shape::from_dims(&[3])),
13770                inputs: vec![in_id],
13771                shape: Shape::from_dims(&[3]),
13772                dtype: DType::F64,
13773            });
13774            g.set_target_backend(op_id, BackendId::Cpu);
13775            (in_id, op_id)
13776        };
13777        let mut inputs = StorageCache::new();
13778        inputs.insert(in_id, Arc::new(RwLock::new(v)));
13779        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13780        let guard = result_arc.read().unwrap();
13781        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13782            panic!("expected Cpu storage");
13783        };
13784        assert_eq!(c.as_slice::<f64>().unwrap(), &[5.0, 7.0, 9.0]);
13785    }
13786
13787    /// E2E: Op::ReduceMaxTo F32 — drop the leading axis with max-reduce.
13788    #[test]
13789    fn pipelined_realize_reduce_max_to_f32_drops_leading_axis() {
13790        // Input [2,3]: row 0 = [1, 7, 3], row 1 = [4, 2, 6]. Max along
13791        // dim 0: [4, 7, 6].
13792        let v = fuel_memory::from_slice_cpu(&[1.0_f32, 7.0, 3.0, 4.0, 2.0, 6.0]);
13793        let graph = Arc::new(RwLock::new(Graph::new()));
13794        let (in_id, op_id) = {
13795            let mut g = graph.write().unwrap();
13796            let in_id = g.push(Node {
13797                op: Op::Const,
13798                inputs: vec![],
13799                shape: Shape::from_dims(&[2, 3]),
13800                dtype: DType::F32,
13801            });
13802            let op_id = g.push(Node {
13803                op: Op::ReduceMaxTo(Shape::from_dims(&[3])),
13804                inputs: vec![in_id],
13805                shape: Shape::from_dims(&[3]),
13806                dtype: DType::F32,
13807            });
13808            g.set_target_backend(op_id, BackendId::Cpu);
13809            (in_id, op_id)
13810        };
13811        let mut inputs = StorageCache::new();
13812        inputs.insert(in_id, Arc::new(RwLock::new(v)));
13813        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13814        let guard = result_arc.read().unwrap();
13815        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13816            panic!("expected Cpu storage");
13817        };
13818        assert_eq!(c.as_slice::<f32>().unwrap(), &[4.0, 7.0, 6.0]);
13819    }
13820
13821    /// E2E: Op::ReduceMaxTo F32 — keep-dim with 1 in the trailing axis.
13822    /// Mirrors the SoftmaxLastDim lowering's max-side shape: input
13823    /// [..., last] → [..., 1].
13824    #[test]
13825    fn pipelined_realize_reduce_max_to_f32_keepdim_trailing() {
13826        // Input [2, 3]: row maxes = [3, 6].
13827        let v = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
13828        let graph = Arc::new(RwLock::new(Graph::new()));
13829        let (in_id, op_id) = {
13830            let mut g = graph.write().unwrap();
13831            let in_id = g.push(Node {
13832                op: Op::Const,
13833                inputs: vec![],
13834                shape: Shape::from_dims(&[2, 3]),
13835                dtype: DType::F32,
13836            });
13837            let op_id = g.push(Node {
13838                op: Op::ReduceMaxTo(Shape::from_dims(&[2, 1])),
13839                inputs: vec![in_id],
13840                shape: Shape::from_dims(&[2, 1]),
13841                dtype: DType::F32,
13842            });
13843            g.set_target_backend(op_id, BackendId::Cpu);
13844            (in_id, op_id)
13845        };
13846        let mut inputs = StorageCache::new();
13847        inputs.insert(in_id, Arc::new(RwLock::new(v)));
13848        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13849        let guard = result_arc.read().unwrap();
13850        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13851            panic!("expected Cpu storage");
13852        };
13853        assert_eq!(c.as_slice::<f32>().unwrap(), &[3.0, 6.0]);
13854    }
13855
13856    /// E2E: ReduceSumTo BF16 — tolerant compare via f32-acc.
13857    #[test]
13858    fn pipelined_realize_reduce_sum_to_bf16() {
13859        let v: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]
13860            .iter()
13861            .map(|x| half::bf16::from_f32(*x))
13862            .collect();
13863        let s = fuel_memory::from_slice_cpu(&v);
13864        let graph = Arc::new(RwLock::new(Graph::new()));
13865        let (in_id, op_id) = {
13866            let mut g = graph.write().unwrap();
13867            let in_id = g.push(Node {
13868                op: Op::Const,
13869                inputs: vec![],
13870                shape: Shape::from_dims(&[2, 3]),
13871                dtype: DType::BF16,
13872            });
13873            let op_id = g.push(Node {
13874                op: Op::ReduceSumTo(Shape::from_dims(&[3])),
13875                inputs: vec![in_id],
13876                shape: Shape::from_dims(&[3]),
13877                dtype: DType::BF16,
13878            });
13879            g.set_target_backend(op_id, BackendId::Cpu);
13880            (in_id, op_id)
13881        };
13882        let mut inputs = StorageCache::new();
13883        inputs.insert(in_id, Arc::new(RwLock::new(s)));
13884        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13885        let guard = result_arc.read().unwrap();
13886        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13887            panic!("expected Cpu storage");
13888        };
13889        let got: Vec<f32> = c
13890            .as_slice::<half::bf16>()
13891            .unwrap()
13892            .iter()
13893            .map(|v| v.to_f32())
13894            .collect();
13895        let want = [5.0_f32, 7.0, 9.0];
13896        for (g, w) in got.iter().zip(want.iter()) {
13897            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
13898        }
13899    }
13900
13901    /// E2E: Op::ConvTranspose2D — F32 spread test.
13902    /// x = [[1, 2], [3, 4]] shape [1,1,2,2], all-ones kernel
13903    /// shape [1,1,2,2], stride=1, padding=0, dilation=1, no bias.
13904    /// Expected output (3x3):
13905    ///   [[1,  3, 2],
13906    ///    [4, 10, 6],
13907    ///    [3,  7, 4]]
13908    #[test]
13909    fn pipelined_realize_conv_transpose2d_f32() {
13910        let x_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
13911        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
13912        let graph = Arc::new(RwLock::new(Graph::new()));
13913        let (x_id, w_id, c_id) = {
13914            let mut g = graph.write().unwrap();
13915            let x = g.push(Node {
13916                op: Op::Const,
13917                inputs: vec![],
13918                shape: Shape::from_dims(&[1, 1, 2, 2]),
13919                dtype: DType::F32,
13920            });
13921            let w = g.push(Node {
13922                op: Op::Const,
13923                inputs: vec![],
13924                shape: Shape::from_dims(&[1, 1, 2, 2]),
13925                dtype: DType::F32,
13926            });
13927            let c = g.push(Node {
13928                op: Op::Fused(
13929                    fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D,
13930                    fuel_graph::registry::FusedOpParams::ConvTranspose2D {
13931                        stride: (1, 1),
13932                        padding: (0, 0),
13933                        output_padding: (0, 0),
13934                        dilation: (1, 1),
13935                        groups: 1,
13936                    },
13937                ),
13938                inputs: vec![x, w],
13939                shape: Shape::from_dims(&[1, 1, 3, 3]),
13940                dtype: DType::F32,
13941            });
13942            g.set_target_backend(c, BackendId::Cpu);
13943            (x, w, c)
13944        };
13945        let mut inputs = StorageCache::new();
13946        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
13947        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
13948        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
13949        let guard = result_arc.read().unwrap();
13950        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13951            panic!("expected Cpu storage");
13952        };
13953        assert_eq!(
13954            c.as_slice::<f32>().unwrap(),
13955            &[1.0, 3.0, 2.0, 4.0, 10.0, 6.0, 3.0, 7.0, 4.0],
13956        );
13957    }
13958
13959    /// E2E: ConvTranspose2D F64 — same shape test.
13960    #[test]
13961    fn pipelined_realize_conv_transpose2d_f64() {
13962        let x_storage = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0]);
13963        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f64, 1.0, 1.0, 1.0]);
13964        let graph = Arc::new(RwLock::new(Graph::new()));
13965        let (x_id, w_id, c_id) = {
13966            let mut g = graph.write().unwrap();
13967            let x = g.push(Node {
13968                op: Op::Const,
13969                inputs: vec![],
13970                shape: Shape::from_dims(&[1, 1, 2, 2]),
13971                dtype: DType::F64,
13972            });
13973            let w = g.push(Node {
13974                op: Op::Const,
13975                inputs: vec![],
13976                shape: Shape::from_dims(&[1, 1, 2, 2]),
13977                dtype: DType::F64,
13978            });
13979            let c = g.push(Node {
13980                op: Op::Fused(
13981                    fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D,
13982                    fuel_graph::registry::FusedOpParams::ConvTranspose2D {
13983                        stride: (1, 1),
13984                        padding: (0, 0),
13985                        output_padding: (0, 0),
13986                        dilation: (1, 1),
13987                        groups: 1,
13988                    },
13989                ),
13990                inputs: vec![x, w],
13991                shape: Shape::from_dims(&[1, 1, 3, 3]),
13992                dtype: DType::F64,
13993            });
13994            g.set_target_backend(c, BackendId::Cpu);
13995            (x, w, c)
13996        };
13997        let mut inputs = StorageCache::new();
13998        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
13999        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
14000        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
14001        let guard = result_arc.read().unwrap();
14002        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14003            panic!("expected Cpu storage");
14004        };
14005        assert_eq!(
14006            c.as_slice::<f64>().unwrap(),
14007            &[1.0, 3.0, 2.0, 4.0, 10.0, 6.0, 3.0, 7.0, 4.0],
14008        );
14009    }
14010
14011    /// E2E: ConvTranspose2D BF16 — tolerant compare via f32-acc.
14012    #[test]
14013    fn pipelined_realize_conv_transpose2d_bf16() {
14014        let x: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0]
14015            .iter()
14016            .map(|v| half::bf16::from_f32(*v))
14017            .collect();
14018        let w: Vec<half::bf16> = [1.0_f32, 1.0, 1.0, 1.0]
14019            .iter()
14020            .map(|v| half::bf16::from_f32(*v))
14021            .collect();
14022        let x_storage = fuel_memory::from_slice_cpu(&x);
14023        let w_storage = fuel_memory::from_slice_cpu(&w);
14024        let graph = Arc::new(RwLock::new(Graph::new()));
14025        let (x_id, w_id, c_id) = {
14026            let mut g = graph.write().unwrap();
14027            let x = g.push(Node {
14028                op: Op::Const,
14029                inputs: vec![],
14030                shape: Shape::from_dims(&[1, 1, 2, 2]),
14031                dtype: DType::BF16,
14032            });
14033            let w = g.push(Node {
14034                op: Op::Const,
14035                inputs: vec![],
14036                shape: Shape::from_dims(&[1, 1, 2, 2]),
14037                dtype: DType::BF16,
14038            });
14039            let c = g.push(Node {
14040                op: Op::Fused(
14041                    fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D,
14042                    fuel_graph::registry::FusedOpParams::ConvTranspose2D {
14043                        stride: (1, 1),
14044                        padding: (0, 0),
14045                        output_padding: (0, 0),
14046                        dilation: (1, 1),
14047                        groups: 1,
14048                    },
14049                ),
14050                inputs: vec![x, w],
14051                shape: Shape::from_dims(&[1, 1, 3, 3]),
14052                dtype: DType::BF16,
14053            });
14054            g.set_target_backend(c, BackendId::Cpu);
14055            (x, w, c)
14056        };
14057        let mut inputs = StorageCache::new();
14058        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
14059        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
14060        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
14061        let guard = result_arc.read().unwrap();
14062        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14063            panic!("expected Cpu storage");
14064        };
14065        let got: Vec<f32> = c
14066            .as_slice::<half::bf16>()
14067            .unwrap()
14068            .iter()
14069            .map(|v| v.to_f32())
14070            .collect();
14071        let want = [1.0_f32, 3.0, 2.0, 4.0, 10.0, 6.0, 3.0, 7.0, 4.0];
14072        for (g, w) in got.iter().zip(want.iter()) {
14073            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
14074        }
14075    }
14076
14077    /// E2E: GQA-style matmul through the pipelined executor.
14078    /// lhs has 4 batch heads, rhs has 2; each rhs head is shared
14079    /// by 2 lhs heads. Output's batch dim follows lhs (4 heads).
14080    #[test]
14081    fn pipelined_realize_matmul_gqa() {
14082        // lhs [4, 1, 2]: heads 0..3 are [[1,2]], [[3,4]], [[5,6]], [[7,8]]
14083        // rhs [2, 2, 1]: heads 0,1 are [[1],[0]], [[0],[1]]
14084        // Expected out [4, 1, 1]: [[1]], [[3]], [[6]], [[8]]
14085        let lhs_storage =
14086            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]);
14087        let rhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
14088
14089        let graph = Arc::new(RwLock::new(Graph::new()));
14090        let (lhs_id, rhs_id, mm_id) = {
14091            let mut g = graph.write().unwrap();
14092            let lhs = g.push(Node {
14093                op: Op::Const,
14094                inputs: vec![],
14095                shape: Shape::from_dims(&[4, 1, 2]),
14096                dtype: DType::F32,
14097            });
14098            let rhs = g.push(Node {
14099                op: Op::Const,
14100                inputs: vec![],
14101                shape: Shape::from_dims(&[2, 2, 1]),
14102                dtype: DType::F32,
14103            });
14104            let mm = g.push(Node {
14105                op: Op::MatMul,
14106                inputs: vec![lhs, rhs],
14107                shape: Shape::from_dims(&[4, 1, 1]),
14108                dtype: DType::F32,
14109            });
14110            g.set_target_backend(mm, BackendId::Cpu);
14111            (lhs, rhs, mm)
14112        };
14113        let mut inputs = StorageCache::new();
14114        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
14115        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
14116
14117        let (result_arc, result_layout) =
14118            PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
14119        assert_eq!(result_layout.shape().dims(), &[4, 1, 1]);
14120
14121        let guard = result_arc.read().unwrap();
14122        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14123            panic!("expected Cpu storage");
14124        };
14125        assert_eq!(c.as_slice::<f32>().unwrap(), &[1.0, 3.0, 6.0, 8.0]);
14126    }
14127
14128    /// E2E: matmul with a transposed rhs — proves stage 3+4
14129    /// integration carries through the matmul path. The transpose
14130    /// is metadata-only; auto-Contiguize materializes the strided
14131    /// rhs before the matmul kernel sees it.
14132    #[test]
14133    fn pipelined_realize_matmul_with_transposed_rhs() {
14134        // lhs [[1, 2], [3, 4]], rhs original [[5, 6], [7, 8]]
14135        // rhs.T = [[5, 7], [6, 8]]
14136        // lhs @ rhs.T = [[1*5+2*6, 1*7+2*8], [3*5+4*6, 3*7+4*8]]
14137        //             = [[17, 23], [39, 53]]
14138        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
14139        let rhs_storage = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0, 7.0, 8.0]);
14140
14141        let graph = Arc::new(RwLock::new(Graph::new()));
14142        let (lhs_id, rhs_id, t_id, mm_id) = {
14143            let mut g = graph.write().unwrap();
14144            let lhs = g.push(Node {
14145                op: Op::Const,
14146                inputs: vec![],
14147                shape: Shape::from_dims(&[2, 2]),
14148                dtype: DType::F32,
14149            });
14150            let rhs = g.push(Node {
14151                op: Op::Const,
14152                inputs: vec![],
14153                shape: Shape::from_dims(&[2, 2]),
14154                dtype: DType::F32,
14155            });
14156            let t = g.push(Node {
14157                op: Op::Transpose,
14158                inputs: vec![rhs],
14159                shape: Shape::from_dims(&[2, 2]),
14160                dtype: DType::F32,
14161            });
14162            let mm = g.push(Node {
14163                op: Op::MatMul,
14164                inputs: vec![lhs, t],
14165                shape: Shape::from_dims(&[2, 2]),
14166                dtype: DType::F32,
14167            });
14168            g.set_target_backend(mm, BackendId::Cpu);
14169            (lhs, rhs, t, mm)
14170        };
14171        let _ = t_id;
14172        let mut inputs = StorageCache::new();
14173        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
14174        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
14175
14176        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
14177        let guard = result_arc.read().unwrap();
14178        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14179            panic!("expected Cpu storage");
14180        };
14181        assert_eq!(c.as_slice::<f32>().unwrap(), &[17.0, 23.0, 39.0, 53.0]);
14182    }
14183
14184    /// E2E: Const + Reshape — contiguous-input reshape is zero
14185    /// copy. The output Storage Arc is the input Arc; the layout
14186    /// is contiguous in the new shape.
14187    #[test]
14188    fn pipelined_realize_reshape_zero_copy_when_contiguous() {
14189        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14190        let graph = Arc::new(RwLock::new(Graph::new()));
14191        let (in_id, r_id) = {
14192            let mut g = graph.write().unwrap();
14193            let in_id = g.push(Node {
14194                op: Op::Const,
14195                inputs: vec![],
14196                shape: Shape::from_dims(&[2, 3]),
14197                dtype: DType::F32,
14198            });
14199            let r_id = g.push(Node {
14200                op: Op::Reshape(Shape::from_dims(&[3, 2])),
14201                inputs: vec![in_id],
14202                shape: Shape::from_dims(&[3, 2]),
14203                dtype: DType::F32,
14204            });
14205            (in_id, r_id)
14206        };
14207        let mut inputs = StorageCache::new();
14208        let in_arc = Arc::new(RwLock::new(storage));
14209        inputs.insert(in_id, Arc::clone(&in_arc));
14210
14211        let (result_arc, result_layout) =
14212            PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
14213
14214        // Zero copy — same Arc.
14215        assert!(
14216            Arc::ptr_eq(&result_arc, &in_arc),
14217            "contiguous reshape must zero-copy"
14218        );
14219        assert_eq!(result_layout.shape().dims(), &[3, 2]);
14220        assert!(result_layout.is_contiguous());
14221
14222        // Bytes are unchanged; just reinterpreted as [3, 2].
14223        let guard = result_arc.read().unwrap();
14224        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14225            panic!("expected Cpu storage");
14226        };
14227        assert_eq!(
14228            c.as_slice::<f32>().unwrap(),
14229            &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
14230        );
14231    }
14232
14233    /// E2E: Const + Transpose + Reshape — reshape on a strided
14234    /// input auto-contiguizes the bytes. Output Arc is fresh
14235    /// (NOT the input Arc); the bytes are the materialized
14236    /// transposed layout.
14237    #[test]
14238    fn pipelined_realize_reshape_materializes_when_strided() {
14239        // shape [2, 3]: 1 2 3 / 4 5 6
14240        // Transpose → [3, 2] strided
14241        // Reshape → [6] (forces materialization)
14242        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14243        let graph = Arc::new(RwLock::new(Graph::new()));
14244        let (in_id, t_id, r_id) = {
14245            let mut g = graph.write().unwrap();
14246            let in_id = g.push(Node {
14247                op: Op::Const,
14248                inputs: vec![],
14249                shape: Shape::from_dims(&[2, 3]),
14250                dtype: DType::F32,
14251            });
14252            let t_id = g.push(Node {
14253                op: Op::Transpose,
14254                inputs: vec![in_id],
14255                shape: Shape::from_dims(&[3, 2]),
14256                dtype: DType::F32,
14257            });
14258            let r_id = g.push(Node {
14259                op: Op::Reshape(Shape::from_dims(&[6])),
14260                inputs: vec![t_id],
14261                shape: Shape::from_dims(&[6]),
14262                dtype: DType::F32,
14263            });
14264            (in_id, t_id, r_id)
14265        };
14266        let _ = t_id;
14267        let mut inputs = StorageCache::new();
14268        let in_arc = Arc::new(RwLock::new(storage));
14269        inputs.insert(in_id, Arc::clone(&in_arc));
14270
14271        let (result_arc, result_layout) =
14272            PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
14273
14274        // Fresh Arc — auto-contiguize allocated new bytes.
14275        assert!(!Arc::ptr_eq(&result_arc, &in_arc));
14276        assert_eq!(result_layout.shape().dims(), &[6]);
14277        assert!(result_layout.is_contiguous());
14278
14279        // Materialized transposed bytes flattened: [1, 4, 2, 5, 3, 6].
14280        let guard = result_arc.read().unwrap();
14281        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14282            panic!("expected Cpu storage");
14283        };
14284        assert_eq!(
14285            c.as_slice::<f32>().unwrap(),
14286            &[1.0, 4.0, 2.0, 5.0, 3.0, 6.0]
14287        );
14288    }
14289
14290    /// E2E: Const + Transpose + SumDim — exercises stage 3
14291    /// (metadata-only Transpose, strided intermediate Layout) +
14292    /// stage 4 (auto-Contiguize before reduce kernel) end-to-end.
14293    /// The transpose makes the intermediate non-contiguous; the
14294    /// reduce wrapper would have failed in stage 2; with stage 4's
14295    /// auto-Contiguize, the kernel sees the materialized contiguous
14296    /// transposed bytes and produces the right answer.
14297    #[test]
14298    fn pipelined_realize_transpose_then_sum_dim_e2e() {
14299        // shape [2, 3]: rows are [1, 2, 3], [4, 5, 6]
14300        // After transpose: shape [3, 2], rows are [1, 4], [2, 5], [3, 6]
14301        // After SumDim(1): shape [3], values [5, 7, 9]
14302        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14303        let graph = Arc::new(RwLock::new(Graph::new()));
14304        let (in_id, t_id, sum_id) = {
14305            let mut g = graph.write().unwrap();
14306            let in_id = g.push(Node {
14307                op: Op::Const,
14308                inputs: vec![],
14309                shape: Shape::from_dims(&[2, 3]),
14310                dtype: DType::F32,
14311            });
14312            let t_id = g.push(Node {
14313                op: Op::Transpose,
14314                inputs: vec![in_id],
14315                shape: Shape::from_dims(&[3, 2]),
14316                dtype: DType::F32,
14317            });
14318            let sum_id = g.push(Node {
14319                op: Op::SumDim(1),
14320                inputs: vec![t_id],
14321                shape: Shape::from_dims(&[3]),
14322                dtype: DType::F32,
14323            });
14324            // Only the reduce kernel runs on the backend; the
14325            // transpose is metadata-only and doesn't need a target.
14326            g.set_target_backend(sum_id, BackendId::Cpu);
14327            (in_id, t_id, sum_id)
14328        };
14329        let _ = t_id;
14330        let mut inputs = StorageCache::new();
14331        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14332
14333        let (result_arc, result_layout) =
14334            PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
14335
14336        // The reduce output is contiguous (kernel-produced).
14337        assert_eq!(result_layout.shape().dims(), &[3]);
14338        assert!(result_layout.is_contiguous());
14339
14340        let guard = result_arc.read().unwrap();
14341        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14342            panic!("expected Cpu storage");
14343        };
14344        let typed: &[f32] = c.as_slice().unwrap();
14345        assert_eq!(typed, &[5.0, 7.0, 9.0]);
14346    }
14347
14348    /// E2E: Const + BroadcastTo + Add — broadcast intermediate
14349    /// auto-contiguizes for the Add kernel; the result is the
14350    /// expected sum.
14351    #[test]
14352    fn pipelined_realize_broadcast_then_add_e2e() {
14353        // shape [3]: [10, 20, 30]
14354        // BroadcastTo [2, 3]: [[10, 20, 30], [10, 20, 30]]
14355        // Plus shape [2, 3]: [[1, 2, 3], [4, 5, 6]]
14356        // Result: [[11, 22, 33], [14, 25, 36]]
14357        let bc_input = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
14358        let plus_input = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14359        let graph = Arc::new(RwLock::new(Graph::new()));
14360        let (bc_in_id, plus_in_id, b_id, add_id) = {
14361            let mut g = graph.write().unwrap();
14362            let bc_in = g.push(Node {
14363                op: Op::Const,
14364                inputs: vec![],
14365                shape: Shape::from_dims(&[3]),
14366                dtype: DType::F32,
14367            });
14368            let plus_in = g.push(Node {
14369                op: Op::Const,
14370                inputs: vec![],
14371                shape: Shape::from_dims(&[2, 3]),
14372                dtype: DType::F32,
14373            });
14374            let b = g.push(Node {
14375                op: Op::BroadcastTo(Shape::from_dims(&[2, 3])),
14376                inputs: vec![bc_in],
14377                shape: Shape::from_dims(&[2, 3]),
14378                dtype: DType::F32,
14379            });
14380            let add = g.push(Node {
14381                op: Op::Add,
14382                inputs: vec![b, plus_in],
14383                shape: Shape::from_dims(&[2, 3]),
14384                dtype: DType::F32,
14385            });
14386            g.set_target_backend(add, BackendId::Cpu);
14387            (bc_in, plus_in, b, add)
14388        };
14389        let _ = b_id;
14390        let mut inputs = StorageCache::new();
14391        inputs.insert(bc_in_id, Arc::new(RwLock::new(bc_input)));
14392        inputs.insert(plus_in_id, Arc::new(RwLock::new(plus_input)));
14393
14394        let (result_arc, _result_layout) =
14395            PipelinedExecutor::realize(graph, add_id, inputs).expect("realize");
14396        let guard = result_arc.read().unwrap();
14397        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14398            panic!("expected Cpu storage");
14399        };
14400        let typed: &[f32] = c.as_slice().unwrap();
14401        assert_eq!(typed, &[11.0, 22.0, 33.0, 14.0, 25.0, 36.0]);
14402    }
14403
14404    /// E2E: Const + SumDim — verifies that `OpParams::Reduce`
14405    /// flows from the graph (input shape via `op_to_op_params`)
14406    /// through compile_one and reaches the reduce kernel.
14407    #[test]
14408    fn pipelined_realize_sum_dim() {
14409        // shape [2, 3]; reduce dim 1 → output shape [2]
14410        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14411        let graph = Arc::new(RwLock::new(Graph::new()));
14412        let (in_id, sum_id) = {
14413            let mut g = graph.write().unwrap();
14414            let in_id = g.push(Node {
14415                op: Op::Const,
14416                inputs: vec![],
14417                shape: Shape::from_dims(&[2, 3]),
14418                dtype: DType::F32,
14419            });
14420            let sum_id = g.push(Node {
14421                op: Op::SumDim(1),
14422                inputs: vec![in_id],
14423                shape: Shape::from_dims(&[2]),
14424                dtype: DType::F32,
14425            });
14426            g.set_target_backend(sum_id, BackendId::Cpu);
14427            (in_id, sum_id)
14428        };
14429        let mut inputs = StorageCache::new();
14430        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14431
14432        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
14433        let guard = result_arc.read().unwrap();
14434        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14435            let typed: &[f32] = c.as_slice().unwrap();
14436            assert_eq!(typed, &[6.0, 15.0]);
14437        }
14438    }
14439
14440    /// E2E: SumAll on a rank-3 input, exercising the all-dims branch
14441    /// of `op_to_op_params` (every dim reduced, rank-0 output).
14442    #[test]
14443    fn pipelined_realize_sum_all_rank3() {
14444        let data: Vec<f32> = (1..=24).map(|x| x as f32).collect();
14445        let storage = fuel_memory::from_slice_cpu(&data);
14446        let graph = Arc::new(RwLock::new(Graph::new()));
14447        let (in_id, sum_id) = {
14448            let mut g = graph.write().unwrap();
14449            let in_id = g.push(Node {
14450                op: Op::Const,
14451                inputs: vec![],
14452                shape: Shape::from_dims(&[2, 3, 4]),
14453                dtype: DType::F32,
14454            });
14455            let sum_id = g.push(Node {
14456                op: Op::SumAll,
14457                inputs: vec![in_id],
14458                shape: Shape::from_dims(&[]),
14459                dtype: DType::F32,
14460            });
14461            g.set_target_backend(sum_id, BackendId::Cpu);
14462            (in_id, sum_id)
14463        };
14464        let mut inputs = StorageCache::new();
14465        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14466
14467        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
14468        let guard = result_arc.read().unwrap();
14469        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14470            let typed: &[f32] = c.as_slice().unwrap();
14471            // 1 + 2 + ... + 24 = 300
14472            assert_eq!(typed, &[300.0]);
14473        }
14474    }
14475
14476    /// E2E: MaxDim + MeanDim chained — verifies all four reduce
14477    /// OpKinds reach their wrappers via the OpParams plumbing.
14478    #[test]
14479    fn pipelined_realize_max_then_mean() {
14480        // shape [2, 3], MaxDim(1) → [2], MeanDim(0) → []
14481        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 9.0, 3.0, 4.0, 2.0, 8.0]);
14482        let graph = Arc::new(RwLock::new(Graph::new()));
14483        let (in_id, mean_id) = {
14484            let mut g = graph.write().unwrap();
14485            let in_id = g.push(Node {
14486                op: Op::Const,
14487                inputs: vec![],
14488                shape: Shape::from_dims(&[2, 3]),
14489                dtype: DType::F32,
14490            });
14491            let max_id = g.push(Node {
14492                op: Op::MaxDim(1),
14493                inputs: vec![in_id],
14494                shape: Shape::from_dims(&[2]),
14495                dtype: DType::F32,
14496            });
14497            let mean_id = g.push(Node {
14498                op: Op::MeanDim(0),
14499                inputs: vec![max_id],
14500                shape: Shape::from_dims(&[]),
14501                dtype: DType::F32,
14502            });
14503            g.set_target_backend(max_id, BackendId::Cpu);
14504            g.set_target_backend(mean_id, BackendId::Cpu);
14505            (in_id, mean_id)
14506        };
14507        let mut inputs = StorageCache::new();
14508        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14509
14510        let (result_arc, _) = PipelinedExecutor::realize(graph, mean_id, inputs).expect("realize");
14511        let guard = result_arc.read().unwrap();
14512        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14513            let typed: &[f32] = c.as_slice().unwrap();
14514            // MaxDim(1) on [[1,9,3],[4,2,8]] = [9, 8]; MeanDim(0) = 8.5
14515            assert_eq!(typed, &[8.5]);
14516        }
14517    }
14518
14519    /// E2E: Sigmoid + Silu — exercises two of the more compositional
14520    /// new unary kernels through the pipelined executor. Verifies
14521    /// the additional `op_to_op_kind` mappings reach the right
14522    /// dispatch wrappers.
14523    #[test]
14524    fn pipelined_realize_sigmoid_then_silu() {
14525        let storage = fuel_memory::from_slice_cpu(&[0.0_f32, 1.0, -1.0]);
14526        let graph = Arc::new(RwLock::new(Graph::new()));
14527        let (in_id, sig_id, silu_id) = {
14528            let mut g = graph.write().unwrap();
14529            let in_id = g.push(Node {
14530                op: Op::Const,
14531                inputs: vec![],
14532                shape: Shape::from_dims(&[3]),
14533                dtype: DType::F32,
14534            });
14535            let sig_id = g.push(Node {
14536                op: Op::Sigmoid,
14537                inputs: vec![in_id],
14538                shape: Shape::from_dims(&[3]),
14539                dtype: DType::F32,
14540            });
14541            // Silu of the sigmoid output — chains to confirm cache flow.
14542            let silu_id = g.push(Node {
14543                op: Op::Silu,
14544                inputs: vec![sig_id],
14545                shape: Shape::from_dims(&[3]),
14546                dtype: DType::F32,
14547            });
14548            g.set_target_backend(sig_id, BackendId::Cpu);
14549            g.set_target_backend(silu_id, BackendId::Cpu);
14550            (in_id, sig_id, silu_id)
14551        };
14552        let _ = sig_id;
14553        let mut inputs = StorageCache::new();
14554        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14555
14556        let (result_arc, _) = PipelinedExecutor::realize(graph, silu_id, inputs).expect("realize");
14557        let guard = result_arc.read().unwrap();
14558        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14559            let typed: &[f32] = c.as_slice().unwrap();
14560            // sigmoid(0) = 0.5; silu(0.5) = 0.5 * sigmoid(0.5) ≈ 0.3112
14561            assert!((typed[0] - 0.5 * (1.0 / (1.0 + (-0.5_f32).exp()))).abs() < 1e-6);
14562        }
14563    }
14564
14565    /// E2E: chained unary ops — Const + Sqr + Sqrt should be a noop
14566    /// for non-negative inputs. Exercises the cache reuse path.
14567    #[test]
14568    fn pipelined_realize_chained_unary_sqr_then_sqrt() {
14569        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 4.0, 9.0]);
14570        let graph = Arc::new(RwLock::new(Graph::new()));
14571        let (in_id, sqrt_id) = {
14572            let mut g = graph.write().unwrap();
14573            let in_id = g.push(Node {
14574                op: Op::Const,
14575                inputs: vec![],
14576                shape: Shape::from_dims(&[3]),
14577                dtype: DType::F32,
14578            });
14579            let sqr_id = g.push(Node {
14580                op: Op::Sqr,
14581                inputs: vec![in_id],
14582                shape: Shape::from_dims(&[3]),
14583                dtype: DType::F32,
14584            });
14585            let sqrt_id = g.push(Node {
14586                op: Op::Sqrt,
14587                inputs: vec![sqr_id],
14588                shape: Shape::from_dims(&[3]),
14589                dtype: DType::F32,
14590            });
14591            g.set_target_backend(sqr_id, BackendId::Cpu);
14592            g.set_target_backend(sqrt_id, BackendId::Cpu);
14593            (in_id, sqrt_id)
14594        };
14595        let mut inputs = StorageCache::new();
14596        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14597
14598        let (result_arc, _) = PipelinedExecutor::realize(graph, sqrt_id, inputs).expect("realize");
14599        let guard = result_arc.read().unwrap();
14600        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14601            let typed: &[f32] = c.as_slice().unwrap();
14602            // sqrt(sqr(x)) == |x| == x for non-negative inputs.
14603            assert_eq!(typed, &[1.0, 4.0, 9.0]);
14604        }
14605    }
14606
14607    /// Multi-stage pipelined: Const + Const + Add + Add (chain of
14608    /// two adds). Tests that work items are processed in topo order
14609    /// and intermediate results are cached and reused.
14610    #[test]
14611    fn pipelined_realize_chained_adds() {
14612        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
14613        let b_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
14614        let c_storage = fuel_memory::from_slice_cpu(&[100.0_f32, 200.0]);
14615
14616        let graph = Arc::new(RwLock::new(Graph::new()));
14617        let (a_id, b_id, c_id, ab_id, abc_id) = {
14618            let mut g = graph.write().unwrap();
14619            let a = g.push(Node {
14620                op: Op::Const,
14621                inputs: vec![],
14622                shape: Shape::from_dims(&[2]),
14623                dtype: DType::F32,
14624            });
14625            let b = g.push(Node {
14626                op: Op::Const,
14627                inputs: vec![],
14628                shape: Shape::from_dims(&[2]),
14629                dtype: DType::F32,
14630            });
14631            let c = g.push(Node {
14632                op: Op::Const,
14633                inputs: vec![],
14634                shape: Shape::from_dims(&[2]),
14635                dtype: DType::F32,
14636            });
14637            let ab = g.push(Node {
14638                op: Op::Add,
14639                inputs: vec![a, b],
14640                shape: Shape::from_dims(&[2]),
14641                dtype: DType::F32,
14642            });
14643            let abc = g.push(Node {
14644                op: Op::Add,
14645                inputs: vec![ab, c],
14646                shape: Shape::from_dims(&[2]),
14647                dtype: DType::F32,
14648            });
14649            g.set_target_backend(ab, BackendId::Cpu);
14650            g.set_target_backend(abc, BackendId::Cpu);
14651            (a, b, c, ab, abc)
14652        };
14653
14654        let mut inputs = StorageCache::new();
14655        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
14656        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
14657        inputs.insert(c_id, Arc::new(RwLock::new(c_storage)));
14658
14659        let (result_arc, _) = PipelinedExecutor::realize(graph, abc_id, inputs).expect("realize");
14660        // Suppress unused warning for the intermediate id.
14661        let _ = ab_id;
14662
14663        let guard = result_arc.read().unwrap();
14664        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14665            let typed: &[f32] = c.as_slice().unwrap();
14666            // (1+10) + 100 = 111;  (2+20) + 200 = 222.
14667            assert_eq!(typed, &[111.0, 222.0]);
14668        }
14669    }
14670
14671    /// E2E: triu(diagonal=0) on a 3×3 matrix.
14672    /// Input:  [1 2 3 / 4 5 6 / 7 8 9]
14673    /// Output: [1 2 3 / 0 5 6 / 0 0 9]
14674    #[test]
14675    fn pipelined_realize_triu_3x3_diag0() {
14676        let storage =
14677            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
14678        let graph = Arc::new(RwLock::new(Graph::new()));
14679        let (in_id, out_id) = {
14680            let mut g = graph.write().unwrap();
14681            let in_id = g.push(Node {
14682                op: Op::Const,
14683                inputs: vec![],
14684                shape: Shape::from_dims(&[3, 3]),
14685                dtype: DType::F32,
14686            });
14687            let out_id = g.push(Node {
14688                op: Op::Triu { diagonal: 0 },
14689                inputs: vec![in_id],
14690                shape: Shape::from_dims(&[3, 3]),
14691                dtype: DType::F32,
14692            });
14693            g.set_target_backend(out_id, BackendId::Cpu);
14694            (in_id, out_id)
14695        };
14696        let mut inputs = StorageCache::new();
14697        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14698        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
14699        let guard = result_arc.read().unwrap();
14700        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14701            panic!("expected Cpu storage");
14702        };
14703        let out: &[f32] = c.as_slice().unwrap();
14704        assert_eq!(out, &[1.0, 2.0, 3.0, 0.0, 5.0, 6.0, 0.0, 0.0, 9.0,]);
14705    }
14706
14707    /// E2E: tril(diagonal=0) on a 3×3 matrix — the canonical causal mask.
14708    /// Output: [1 0 0 / 4 5 0 / 7 8 9]
14709    #[test]
14710    fn pipelined_realize_tril_3x3_diag0_causal_mask() {
14711        let storage =
14712            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
14713        let graph = Arc::new(RwLock::new(Graph::new()));
14714        let (in_id, out_id) = {
14715            let mut g = graph.write().unwrap();
14716            let in_id = g.push(Node {
14717                op: Op::Const,
14718                inputs: vec![],
14719                shape: Shape::from_dims(&[3, 3]),
14720                dtype: DType::F32,
14721            });
14722            let out_id = g.push(Node {
14723                op: Op::Tril { diagonal: 0 },
14724                inputs: vec![in_id],
14725                shape: Shape::from_dims(&[3, 3]),
14726                dtype: DType::F32,
14727            });
14728            g.set_target_backend(out_id, BackendId::Cpu);
14729            (in_id, out_id)
14730        };
14731        let mut inputs = StorageCache::new();
14732        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14733        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
14734        let guard = result_arc.read().unwrap();
14735        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14736            panic!("expected Cpu storage");
14737        };
14738        let out: &[f32] = c.as_slice().unwrap();
14739        assert_eq!(out, &[1.0, 0.0, 0.0, 4.0, 5.0, 0.0, 7.0, 8.0, 9.0,]);
14740    }
14741
14742    /// E2E: log_softmax over a 2×3 input. Rows are [1,2,3] and [3,2,1].
14743    /// log_softmax(row) = row - max - log(sum exp(row - max)).
14744    /// Row 0: max=3, exp(-2)+exp(-1)+exp(0) = 0.135+0.368+1.0 = 1.503;
14745    ///        log(1.503) ≈ 0.4076; out = [1-3-0.4076, 2-3-0.4076, 3-3-0.4076]
14746    ///                              = [-2.4076, -1.4076, -0.4076]
14747    /// Row 1 is row 0 reversed: [-0.4076, -1.4076, -2.4076].
14748    #[test]
14749    fn pipelined_realize_log_softmax_last_dim() {
14750        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 3.0, 2.0, 1.0]);
14751        let graph = Arc::new(RwLock::new(Graph::new()));
14752        let (in_id, out_id) = {
14753            let mut g = graph.write().unwrap();
14754            let in_id = g.push(Node {
14755                op: Op::Const,
14756                inputs: vec![],
14757                shape: Shape::from_dims(&[2, 3]),
14758                dtype: DType::F32,
14759            });
14760            let out_id = g.push(Node {
14761                op: Op::LogSoftmaxLastDim,
14762                inputs: vec![in_id],
14763                shape: Shape::from_dims(&[2, 3]),
14764                dtype: DType::F32,
14765            });
14766            g.set_target_backend(out_id, BackendId::Cpu);
14767            (in_id, out_id)
14768        };
14769        let mut inputs = StorageCache::new();
14770        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14771        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
14772        let guard = result_arc.read().unwrap();
14773        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14774            panic!("expected Cpu storage");
14775        };
14776        let out: &[f32] = c.as_slice().unwrap();
14777        let expected = [
14778            -2.407_606,
14779            -1.4076059,
14780            -0.40760595_f32,
14781            -0.40760595,
14782            -1.4076059,
14783            -2.407_606,
14784        ];
14785        for (a, b) in out.iter().zip(expected.iter()) {
14786            assert!((a - b).abs() < 1e-5, "log_softmax mismatch: {a} vs {b}");
14787        }
14788        // The exp() of the output should sum to 1 per row.
14789        for row in out.chunks(3) {
14790            let sum: f32 = row.iter().map(|x| x.exp()).sum();
14791            assert!(
14792                (sum - 1.0).abs() < 1e-5,
14793                "softmax(log_softmax) row sum != 1: {sum}"
14794            );
14795        }
14796    }
14797
14798    // --- side-effect roots + destructive cleanup (9c Phase B) -----
14799
14800    /// Side-effect roots get merged into the realize walk even when
14801    /// not reachable from the user's targets. The production trigger
14802    /// is `Op::Release` (emitted by `ResidencyEvictionRule`); this
14803    /// test uses that exact shape.
14804    ///
14805    /// Graph: Const(a) + Const(b) → Add (user target); separate
14806    /// Const(c) → Release(c) (side-effect root, not reachable from
14807    /// Add). After realize_many on `[add]`, the Add should be in the
14808    /// output AND the Release should have fired (verified by the
14809    /// fact that realize succeeded — Op::Release in the walk used to
14810    /// fail compilation pre-Phase B+).
14811    #[test]
14812    fn pipelined_realize_merges_op_release_side_effect_root() {
14813        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
14814        let b = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
14815        let c = fuel_memory::from_slice_cpu(&[100.0_f32, 200.0]);
14816        let graph = Arc::new(RwLock::new(Graph::new()));
14817        let (a_id, b_id, c_id, add_id, release_id) = {
14818            let mut g = graph.write().unwrap();
14819            let a = g.push(Node {
14820                op: Op::Const,
14821                inputs: vec![],
14822                shape: Shape::from_dims(&[2]),
14823                dtype: DType::F32,
14824            });
14825            let b = g.push(Node {
14826                op: Op::Const,
14827                inputs: vec![],
14828                shape: Shape::from_dims(&[2]),
14829                dtype: DType::F32,
14830            });
14831            // c is NOT reachable from add; its Release IS marked as
14832            // a side-effect root.
14833            let c = g.push(Node {
14834                op: Op::Const,
14835                inputs: vec![],
14836                shape: Shape::from_dims(&[2]),
14837                dtype: DType::F32,
14838            });
14839            let add = g.push(Node {
14840                op: Op::Add,
14841                inputs: vec![a, b],
14842                shape: Shape::from_dims(&[2]),
14843                dtype: DType::F32,
14844            });
14845            // Production shape: Op::Release on c, marked as
14846            // side-effect root so it fires even though no graph
14847            // node reads its output.
14848            let release = g.push(Node {
14849                op: Op::Release,
14850                inputs: vec![c],
14851                shape: Shape::from_dims(&[0]),
14852                dtype: DType::F32,
14853            });
14854            g.set_target_backend(add, BackendId::Cpu);
14855            g.set_target_backend(release, BackendId::Cpu);
14856            g.add_side_effect_root(release);
14857            (a, b, c, add, release)
14858        };
14859        let mut inputs = StorageCache::new();
14860        inputs.insert(a_id, Arc::new(RwLock::new(a)));
14861        inputs.insert(b_id, Arc::new(RwLock::new(b)));
14862        let c_arc = Arc::new(RwLock::new(c));
14863        let c_arc_external = Arc::clone(&c_arc);
14864        inputs.insert(c_id, c_arc);
14865
14866        // Only `add` is requested. The Release on c is a side-effect
14867        // root that must still fire.
14868        let out = PipelinedExecutor::realize_many(graph, &[add_id], inputs).expect("realize_many");
14869        assert_eq!(out.len(), 1);
14870        let add_guard = out[0].0.read().unwrap();
14871        let fuel_memory::BackendStorage::Cpu(arr) = &add_guard.inner else {
14872            panic!()
14873        };
14874        assert_eq!(arr.as_slice::<f32>().unwrap(), &[11.0, 22.0]);
14875
14876        // The Release's destructive_input cleanup dropped the
14877        // cache's Arc to c. The only Arc to c that survives is the
14878        // external one this test holds — confirms the eviction
14879        // actually freed the cache's reference.
14880        assert_eq!(
14881            Arc::strong_count(&c_arc_external),
14882            1,
14883            "Op::Release should evict the cache's Arc to its source; \
14884             only the test's external clone should remain",
14885        );
14886        let _ = release_id;
14887    }
14888
14889    /// `compile_one` emits a `WorkItemKind::ReleaseMarker` for
14890    /// `Op::Release` with `destructive_input = Some(0)`. Verify
14891    /// the WorkItem shape via a direct compile_one call.
14892    #[test]
14893    fn compile_one_emits_release_marker_with_destructive_input() {
14894        let graph_rc = Arc::new(RwLock::new(Graph::new()));
14895        let (src_id, release_id) = {
14896            let mut g = graph_rc.write().unwrap();
14897            let src = g.push(Node {
14898                op: Op::Const,
14899                inputs: vec![],
14900                shape: Shape::from_dims(&[2]),
14901                dtype: DType::F32,
14902            });
14903            let release = g.push(Node {
14904                op: Op::Release,
14905                inputs: vec![src],
14906                shape: Shape::from_dims(&[0]),
14907                dtype: DType::F32,
14908            });
14909            g.set_target_backend(release, BackendId::Cpu);
14910            (src, release)
14911        };
14912        let g = graph_rc.read().unwrap();
14913        let bindings = crate::dispatch::global_bindings();
14914        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
14915        let item = compile_one(
14916            &g,
14917            release_id,
14918            &mut layout_cache,
14919            &bindings,
14920            &SymEnv::default(),
14921        )
14922        .expect("compile_one Op::Release");
14923        assert!(matches!(item.kind, WorkItemKind::ReleaseMarker));
14924        assert_eq!(item.destructive_input, Some(0));
14925        assert_eq!(item.inputs, vec![src_id]);
14926        assert_eq!(
14927            item.elem_count, 0,
14928            "Release output is the zero-element marker"
14929        );
14930    }
14931
14932    // --- Op::Move (executor-unification Session 1, gap 13) --------
14933
14934    /// `compile_one` emits a `WorkItemKind::Move` for `Op::Move` with
14935    /// `destructive_input = Some(0)` and a resolved transfer kernel
14936    /// (binding-table lookup at `(OpKind::Copy, [dt, dt], source
14937    /// backend)` — Move shares Op::Copy's data-movement kernel).
14938    #[test]
14939    fn compile_one_emits_move_with_destructive_input() {
14940        let graph_rc = Arc::new(RwLock::new(Graph::new()));
14941        let (src_id, move_id) = {
14942            let mut g = graph_rc.write().unwrap();
14943            let src = g.push(Node {
14944                op: Op::Const,
14945                inputs: vec![],
14946                shape: Shape::from_dims(&[2]),
14947                dtype: DType::F32,
14948            });
14949            let mv = g.push(Node {
14950                op: Op::Move {
14951                    target: DeviceLocation::Cpu,
14952                },
14953                inputs: vec![src],
14954                shape: Shape::from_dims(&[2]),
14955                dtype: DType::F32,
14956            });
14957            g.set_target_backend(mv, BackendId::Cpu);
14958            (src, mv)
14959        };
14960        let g = graph_rc.read().unwrap();
14961        let bindings = crate::dispatch::global_bindings();
14962        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
14963        let item = compile_one(
14964            &g,
14965            move_id,
14966            &mut layout_cache,
14967            &bindings,
14968            &SymEnv::default(),
14969        )
14970        .expect("compile_one Op::Move");
14971        assert!(matches!(
14972            item.kind,
14973            WorkItemKind::Move {
14974                target_location: DeviceLocation::Cpu
14975            },
14976        ));
14977        assert_eq!(item.destructive_input, Some(0), "Move destroys its source");
14978        assert_eq!(item.inputs, vec![src_id]);
14979        assert!(
14980            item.compiled.is_some(),
14981            "Move resolves a transfer kernel at (OpKind::Copy, [dt, dt], source backend)",
14982        );
14983    }
14984
14985    // --- runtime fused op (JIT-adopted Tier-2 kernel) --------------
14986
14987    /// `compile_one` resolves an `Op::Fused(fid, Runtime)` node with
14988    /// `fid.is_runtime()` from the runtime-kernel sidecar (never the
14989    /// binding table): `WorkItemKind::Kernel`, `compiled.op ==
14990    /// OpKind::RuntimeFused`, and the kernel pointer is exactly the one
14991    /// `adopt_runtime_fused` bound.
14992    #[test]
14993    fn compile_one_resolves_runtime_fused_from_the_sidecar() {
14994        fn sentinel_kernel(
14995            _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
14996            _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
14997            _layouts: &[Layout],
14998            _params: &crate::kernel::OpParams,
14999        ) -> Result<()> {
15000            Ok(())
15001        }
15002        // A region shape unique to this test (process-global sidecar; see
15003        // runtime_fused_pathfinder's tests for the collision rationale).
15004        let region = fuel_graph::jit::PatternNode::Op {
15005            op: fuel_graph::jit::OpTag::Exp,
15006            attrs: fuel_graph::jit::OpAttrs::default(),
15007            operands: vec![fuel_graph::jit::PatternNode::Op {
15008                op: fuel_graph::jit::OpTag::Sub,
15009                attrs: fuel_graph::jit::OpAttrs::default(),
15010                operands: vec![
15011                    fuel_graph::jit::PatternNode::Bind { index: 0 },
15012                    fuel_graph::jit::PatternNode::Bind { index: 1 },
15013                ],
15014            }],
15015        };
15016        let rid = crate::runtime_fused_kernels::adopt_runtime_fused(
15017            "test::compile_one::exp_sub",
15018            region,
15019            sentinel_kernel as crate::kernel::KernelRef,
15020            vec![DType::F32, DType::F32, DType::F32],
15021            BackendId::Cpu,
15022        )
15023        .expect("registrable region");
15024
15025        let graph_rc = Arc::new(RwLock::new(Graph::new()));
15026        let fused_id = {
15027            let mut g = graph_rc.write().unwrap();
15028            let s = Shape::from_dims(&[4]);
15029            let a = g.push(Node {
15030                op: Op::Const,
15031                inputs: vec![],
15032                shape: s.clone(),
15033                dtype: DType::F32,
15034            });
15035            let b = g.push(Node {
15036                op: Op::Const,
15037                inputs: vec![],
15038                shape: s.clone(),
15039                dtype: DType::F32,
15040            });
15041            let fused = g.push(Node {
15042                op: Op::Fused(
15043                    rid,
15044                    fuel_graph::registry::FusedOpParams::Runtime {
15045                        scalars: Vec::new(),
15046                    },
15047                ),
15048                inputs: vec![a, b],
15049                shape: s,
15050                dtype: DType::F32,
15051            });
15052            // The arm emitter pins the backend; mirror that here.
15053            g.set_target_backend(fused, BackendId::Cpu);
15054            fused
15055        };
15056        let g = graph_rc.read().unwrap();
15057        let bindings = crate::dispatch::global_bindings();
15058        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
15059        let item = compile_one(
15060            &g,
15061            fused_id,
15062            &mut layout_cache,
15063            &bindings,
15064            &SymEnv::default(),
15065        )
15066        .expect("compile_one runtime fused op");
15067        assert!(matches!(item.kind, WorkItemKind::Kernel));
15068        let compiled = item.compiled.expect("resolved a kernel");
15069        assert_eq!(compiled.op, fuel_ir::dispatch::OpKind::RuntimeFused);
15070        assert_eq!(compiled.backend, BackendId::Cpu);
15071        assert!(
15072            std::ptr::fn_addr_eq(compiled.kernel, sentinel_kernel as crate::kernel::KernelRef),
15073            "the kernel pointer is exactly the adopted one",
15074        );
15075        assert!(
15076            layout_cache.contains_key(&fused_id),
15077            "output layout cached for consumers"
15078        );
15079    }
15080
15081    /// The dtype belt-and-suspenders guard: an `Op::Fused(runtime)` node
15082    /// whose per-operand dtypes disagree with the adopted kernel's tuple is
15083    /// a typed error, not a silent wrong-kernel dispatch.
15084    #[test]
15085    fn compile_one_rejects_runtime_fused_dtype_mismatch() {
15086        fn noop_kernel(
15087            _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
15088            _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
15089            _layouts: &[Layout],
15090            _params: &crate::kernel::OpParams,
15091        ) -> Result<()> {
15092            Ok(())
15093        }
15094        let region = fuel_graph::jit::PatternNode::Op {
15095            op: fuel_graph::jit::OpTag::Log,
15096            attrs: fuel_graph::jit::OpAttrs::default(),
15097            operands: vec![fuel_graph::jit::PatternNode::Op {
15098                op: fuel_graph::jit::OpTag::Maximum,
15099                attrs: fuel_graph::jit::OpAttrs::default(),
15100                operands: vec![
15101                    fuel_graph::jit::PatternNode::Bind { index: 0 },
15102                    fuel_graph::jit::PatternNode::Bind { index: 1 },
15103                ],
15104            }],
15105        };
15106        // Adopted for F32 operands…
15107        let rid = crate::runtime_fused_kernels::adopt_runtime_fused(
15108            "test::compile_one::log_maximum",
15109            region,
15110            noop_kernel as crate::kernel::KernelRef,
15111            vec![DType::F32, DType::F32, DType::F32],
15112            BackendId::Cpu,
15113        )
15114        .expect("registrable region");
15115
15116        let graph_rc = Arc::new(RwLock::new(Graph::new()));
15117        let fused_id = {
15118            let mut g = graph_rc.write().unwrap();
15119            let s = Shape::from_dims(&[4]);
15120            // …but the node's operands are F64.
15121            let a = g.push(Node {
15122                op: Op::Const,
15123                inputs: vec![],
15124                shape: s.clone(),
15125                dtype: DType::F64,
15126            });
15127            let b = g.push(Node {
15128                op: Op::Const,
15129                inputs: vec![],
15130                shape: s.clone(),
15131                dtype: DType::F64,
15132            });
15133            let fused = g.push(Node {
15134                op: Op::Fused(
15135                    rid,
15136                    fuel_graph::registry::FusedOpParams::Runtime {
15137                        scalars: Vec::new(),
15138                    },
15139                ),
15140                inputs: vec![a, b],
15141                shape: s,
15142                dtype: DType::F64,
15143            });
15144            g.set_target_backend(fused, BackendId::Cpu);
15145            fused
15146        };
15147        let g = graph_rc.read().unwrap();
15148        let bindings = crate::dispatch::global_bindings();
15149        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
15150        let err = match compile_one(
15151            &g,
15152            fused_id,
15153            &mut layout_cache,
15154            &bindings,
15155            &SymEnv::default(),
15156        ) {
15157            Ok(_) => panic!("dtype mismatch must be a typed error"),
15158            Err(e) => e,
15159        };
15160        // Post-fold, the dtype tuple IS the binding key: a mismatch is the
15161        // same honest `NoBackendForOp` miss as an absent kernel — reported
15162        // with the `RuntimeFused` diagnostic op tag, never a wrong-kernel bind.
15163        assert!(
15164            matches!(
15165                err,
15166                fuel_ir::Error::NoBackendForOp {
15167                    op: fuel_ir::dispatch::OpKind::RuntimeFused,
15168                    ..
15169                }
15170            ),
15171            "a dtype mismatch is an honest binding miss: {err}",
15172        );
15173    }
15174
15175    /// A runtime fused node carrying live `Runtime { scalars }` compiles with
15176    /// `OpParams::JitScalars` — the launch channel for the kernel's trailing
15177    /// `p{i}` args. (A param-free node keeps `OpParams::None`, covered by
15178    /// `compile_one_resolves_runtime_fused_from_the_sidecar`.)
15179    #[test]
15180    fn compile_one_maps_runtime_scalars_to_jit_scalars() {
15181        fn noop_kernel(
15182            _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
15183            _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
15184            _layouts: &[Layout],
15185            _params: &crate::kernel::OpParams,
15186        ) -> Result<()> {
15187            Ok(())
15188        }
15189        // Unique slot-template region (process-global sidecar).
15190        let region = fuel_graph::jit::PatternNode::Op {
15191            op: fuel_graph::jit::OpTag::Floor,
15192            attrs: fuel_graph::jit::OpAttrs::default(),
15193            operands: vec![fuel_graph::jit::PatternNode::Op {
15194                op: fuel_graph::jit::OpTag::MulScalar,
15195                attrs: fuel_graph::jit::OpAttrs::default(), // open slot
15196                operands: vec![fuel_graph::jit::PatternNode::Bind { index: 0 }],
15197            }],
15198        };
15199        let rid = crate::runtime_fused_kernels::adopt_runtime_fused(
15200            "test::compile_one::floor_mul_scalar",
15201            region,
15202            noop_kernel as crate::kernel::KernelRef,
15203            vec![DType::F32, DType::F32],
15204            BackendId::Cpu,
15205        )
15206        .expect("slot template registrable");
15207
15208        let graph_rc = Arc::new(RwLock::new(Graph::new()));
15209        let fused_id = {
15210            let mut g = graph_rc.write().unwrap();
15211            let s = Shape::from_dims(&[4]);
15212            let x = g.push(Node {
15213                op: Op::Const,
15214                inputs: vec![],
15215                shape: s.clone(),
15216                dtype: DType::F32,
15217            });
15218            let fused = g.push(Node {
15219                op: Op::Fused(
15220                    rid,
15221                    fuel_graph::registry::FusedOpParams::Runtime {
15222                        scalars: vec![3.5, -1.25],
15223                    },
15224                ),
15225                inputs: vec![x],
15226                shape: s,
15227                dtype: DType::F32,
15228            });
15229            g.set_target_backend(fused, BackendId::Cpu);
15230            fused
15231        };
15232        let g = graph_rc.read().unwrap();
15233        let bindings = crate::dispatch::global_bindings();
15234        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
15235        let item = compile_one(
15236            &g,
15237            fused_id,
15238            &mut layout_cache,
15239            &bindings,
15240            &SymEnv::default(),
15241        )
15242        .expect("compile_one runtime fused op with scalars");
15243        let compiled = item.compiled.expect("resolved a kernel");
15244        assert!(
15245            matches!(
15246                &compiled.op_params,
15247                crate::kernel::OpParams::JitScalars { scalars } if scalars == &vec![3.5, -1.25]
15248            ),
15249            "Runtime scalars ride into OpParams::JitScalars, got {:?}",
15250            compiled.op_params,
15251        );
15252    }
15253
15254    /// Move-to-same-device is the degenerate case: per the legacy
15255    /// `GraphExecutor` contract (`Op::Copy | Op::Move` shared arm →
15256    /// `backend.copy_to`) it is a plain copy — fresh storage on the
15257    /// same device, data intact — and the source is still evicted
15258    /// afterward (destructive semantics don't depend on the devices
15259    /// differing).
15260    #[test]
15261    fn pipelined_op_move_same_device_is_plain_copy() {
15262        let src = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
15263        let graph = Arc::new(RwLock::new(Graph::new()));
15264        let (src_id, move_id) = {
15265            let mut g = graph.write().unwrap();
15266            let src = g.push(Node {
15267                op: Op::Const,
15268                inputs: vec![],
15269                shape: Shape::from_dims(&[4]),
15270                dtype: DType::F32,
15271            });
15272            let mv = g.push(Node {
15273                op: Op::Move {
15274                    target: DeviceLocation::Cpu,
15275                },
15276                inputs: vec![src],
15277                shape: Shape::from_dims(&[4]),
15278                dtype: DType::F32,
15279            });
15280            g.set_target_backend(mv, BackendId::Cpu);
15281            (src, mv)
15282        };
15283        let src_arc = Arc::new(RwLock::new(src));
15284        let src_arc_external = Arc::clone(&src_arc);
15285        let mut inputs = StorageCache::new();
15286        inputs.insert(src_id, src_arc);
15287
15288        let (out, layout) =
15289            PipelinedExecutor::realize(graph, move_id, inputs).expect("realize Op::Move");
15290        let guard = out.read().unwrap();
15291        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15292            panic!()
15293        };
15294        assert_eq!(
15295            c.as_slice::<f32>().unwrap(),
15296            &[1.0, 2.0, 3.0, 4.0],
15297            "Op::Move output should carry input's data to target",
15298        );
15299        assert!(layout.is_contiguous());
15300        drop(guard);
15301        assert!(
15302            !Arc::ptr_eq(&out, &src_arc_external),
15303            "same-device Move is a plain copy — fresh storage, not an alias",
15304        );
15305        // The realize loop's destructive_input cleanup dropped the
15306        // cache's Arc to the source; only the test's external clone
15307        // survives.
15308        assert_eq!(
15309            Arc::strong_count(&src_arc_external),
15310            1,
15311            "Op::Move should evict the cache's Arc to its source",
15312        );
15313    }
15314
15315    /// The multiple-consumer-source case: a Move must NOT strand
15316    /// another consumer of its source. `execution_plan` (via
15317    /// `derive_ordering`, keyed off `destructive_input`) pins the
15318    /// Move AFTER the sibling reader; the executor's post-Move cache
15319    /// eviction then can't break the reader. Mirrors the legacy
15320    /// `op_move_pinned_after_sibling_reader_via_derive_ordering`
15321    /// test in fuel-graph-router/tests/cross_device.rs.
15322    ///
15323    ///   a   = const [1, 2, 3, 4]
15324    ///   b   = relu(a)        (non-destructive sibling reader)
15325    ///   m   = move(a, Cpu)   (destructive — evicts a once run)
15326    ///   out = add(b, m)      → [2, 4, 6, 8]
15327    #[test]
15328    fn pipelined_op_move_multi_consumer_source_not_stranded() {
15329        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
15330        let graph = Arc::new(RwLock::new(Graph::new()));
15331        let (a_id, out_id) = {
15332            let mut g = graph.write().unwrap();
15333            let a = g.push(Node {
15334                op: Op::Const,
15335                inputs: vec![],
15336                shape: Shape::from_dims(&[4]),
15337                dtype: DType::F32,
15338            });
15339            let b = g.push(Node {
15340                op: Op::Relu,
15341                inputs: vec![a],
15342                shape: Shape::from_dims(&[4]),
15343                dtype: DType::F32,
15344            });
15345            let m = g.push(Node {
15346                op: Op::Move {
15347                    target: DeviceLocation::Cpu,
15348                },
15349                inputs: vec![a],
15350                shape: Shape::from_dims(&[4]),
15351                dtype: DType::F32,
15352            });
15353            let out = g.push(Node {
15354                op: Op::Add,
15355                inputs: vec![b, m],
15356                shape: Shape::from_dims(&[4]),
15357                dtype: DType::F32,
15358            });
15359            g.set_target_backend(b, BackendId::Cpu);
15360            g.set_target_backend(m, BackendId::Cpu);
15361            g.set_target_backend(out, BackendId::Cpu);
15362            (a, out)
15363        };
15364        let mut inputs = StorageCache::new();
15365        inputs.insert(a_id, Arc::new(RwLock::new(a)));
15366
15367        let (out, _) = PipelinedExecutor::realize(graph, out_id, inputs)
15368            .expect("realize add(relu(a), move(a))");
15369        let guard = out.read().unwrap();
15370        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15371            panic!()
15372        };
15373        assert_eq!(
15374            c.as_slice::<f32>().unwrap(),
15375            &[2.0, 4.0, 6.0, 8.0],
15376            "relu(a) must run before move(a) evicts a",
15377        );
15378    }
15379
15380    /// A Move whose source is itself in the realize target set must
15381    /// not evict it — the caller asked for the source's storage. The
15382    /// destructive cleanup's `target_set` gate covers Move exactly
15383    /// like Release.
15384    #[test]
15385    fn pipelined_op_move_source_in_target_set_not_evicted() {
15386        let a = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0]);
15387        let graph = Arc::new(RwLock::new(Graph::new()));
15388        let (a_id, move_id) = {
15389            let mut g = graph.write().unwrap();
15390            let a = g.push(Node {
15391                op: Op::Const,
15392                inputs: vec![],
15393                shape: Shape::from_dims(&[2]),
15394                dtype: DType::F32,
15395            });
15396            let mv = g.push(Node {
15397                op: Op::Move {
15398                    target: DeviceLocation::Cpu,
15399                },
15400                inputs: vec![a],
15401                shape: Shape::from_dims(&[2]),
15402                dtype: DType::F32,
15403            });
15404            g.set_target_backend(mv, BackendId::Cpu);
15405            (a, mv)
15406        };
15407        let a_arc = Arc::new(RwLock::new(a));
15408        let a_arc_external = Arc::clone(&a_arc);
15409        let mut inputs = StorageCache::new();
15410        inputs.insert(a_id, a_arc);
15411
15412        let out = PipelinedExecutor::realize_many(graph, &[move_id, a_id], inputs)
15413            .expect("realize_many [move, source]");
15414        assert_eq!(out.len(), 2);
15415        let mv_guard = out[0].0.read().unwrap();
15416        let fuel_memory::BackendStorage::Cpu(c) = &mv_guard.inner else {
15417            panic!()
15418        };
15419        assert_eq!(c.as_slice::<f32>().unwrap(), &[5.0, 6.0]);
15420        assert!(
15421            Arc::ptr_eq(&out[1].0, &a_arc_external),
15422            "requested source must survive the Move's destructive cleanup",
15423        );
15424    }
15425
15426    // --- realize_many (Phase 7.6 step 9c Phase A) ----------------
15427
15428    /// realize_many on empty targets returns an empty Vec — no graph
15429    /// walk, no panic.
15430    #[test]
15431    fn pipelined_realize_many_empty_targets() {
15432        let graph = Arc::new(RwLock::new(Graph::new()));
15433        let inputs = StorageCache::new();
15434        let out = PipelinedExecutor::realize_many(graph, &[], inputs).expect("realize_many");
15435        assert!(out.is_empty());
15436    }
15437
15438    /// realize_many with two independent target chains. Each chain's
15439    /// output is in the cache; the shared topo walk realizes both.
15440    /// Verifies parallel chain handling + return order matches input.
15441    #[test]
15442    fn pipelined_realize_many_two_independent_targets() {
15443        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
15444        let rhs = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
15445        let graph = Arc::new(RwLock::new(Graph::new()));
15446        let (lhs_id, rhs_id, add_id, mul_id) = {
15447            let mut g = graph.write().unwrap();
15448            let lhs = g.push(Node {
15449                op: Op::Const,
15450                inputs: vec![],
15451                shape: Shape::from_dims(&[3]),
15452                dtype: DType::F32,
15453            });
15454            let rhs = g.push(Node {
15455                op: Op::Const,
15456                inputs: vec![],
15457                shape: Shape::from_dims(&[3]),
15458                dtype: DType::F32,
15459            });
15460            let add = g.push(Node {
15461                op: Op::Add,
15462                inputs: vec![lhs, rhs],
15463                shape: Shape::from_dims(&[3]),
15464                dtype: DType::F32,
15465            });
15466            let mul = g.push(Node {
15467                op: Op::Mul,
15468                inputs: vec![lhs, rhs],
15469                shape: Shape::from_dims(&[3]),
15470                dtype: DType::F32,
15471            });
15472            g.set_target_backend(add, BackendId::Cpu);
15473            g.set_target_backend(mul, BackendId::Cpu);
15474            (lhs, rhs, add, mul)
15475        };
15476        let mut inputs = StorageCache::new();
15477        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs)));
15478        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs)));
15479
15480        // Pass mul first to confirm return order matches targets order
15481        // (not graph order — graph order would put add first).
15482        let out = PipelinedExecutor::realize_many(graph, &[mul_id, add_id], inputs)
15483            .expect("realize_many");
15484        assert_eq!(out.len(), 2);
15485
15486        let mul_guard = out[0].0.read().unwrap();
15487        let fuel_memory::BackendStorage::Cpu(c) = &mul_guard.inner else {
15488            panic!()
15489        };
15490        assert_eq!(c.as_slice::<f32>().unwrap(), &[10.0, 40.0, 90.0]);
15491
15492        let add_guard = out[1].0.read().unwrap();
15493        let fuel_memory::BackendStorage::Cpu(c) = &add_guard.inner else {
15494            panic!()
15495        };
15496        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 22.0, 33.0]);
15497    }
15498
15499    /// realize_many with the same NodeId twice — caller asking for
15500    /// the same output twice. Both outputs are the same Arc (cheap).
15501    #[test]
15502    fn pipelined_realize_many_duplicate_target_returns_same_arc() {
15503        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
15504        let graph = Arc::new(RwLock::new(Graph::new()));
15505        let (in_id, neg_id) = {
15506            let mut g = graph.write().unwrap();
15507            let in_id = g.push(Node {
15508                op: Op::Const,
15509                inputs: vec![],
15510                shape: Shape::from_dims(&[3]),
15511                dtype: DType::F32,
15512            });
15513            let neg = g.push(Node {
15514                op: Op::Neg,
15515                inputs: vec![in_id],
15516                shape: Shape::from_dims(&[3]),
15517                dtype: DType::F32,
15518            });
15519            g.set_target_backend(neg, BackendId::Cpu);
15520            (in_id, neg)
15521        };
15522        let mut inputs = StorageCache::new();
15523        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
15524
15525        let out = PipelinedExecutor::realize_many(graph, &[neg_id, neg_id], inputs)
15526            .expect("realize_many");
15527        assert_eq!(out.len(), 2);
15528        assert!(
15529            Arc::ptr_eq(&out[0].0, &out[1].0),
15530            "duplicate target should share the same storage Arc",
15531        );
15532    }
15533
15534    /// realize_many with shared upstream nodes evaluates the shared
15535    /// chunk exactly once. Two targets `f = a + b` and `g = (a + b) * a`
15536    /// — `a + b` is computed once.
15537    #[test]
15538    fn pipelined_realize_many_shared_subgraph_evaluates_once() {
15539        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
15540        let b_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
15541        let graph = Arc::new(RwLock::new(Graph::new()));
15542        let (a_id, b_id, add_id, mul_id) = {
15543            let mut g = graph.write().unwrap();
15544            let a = g.push(Node {
15545                op: Op::Const,
15546                inputs: vec![],
15547                shape: Shape::from_dims(&[3]),
15548                dtype: DType::F32,
15549            });
15550            let b = g.push(Node {
15551                op: Op::Const,
15552                inputs: vec![],
15553                shape: Shape::from_dims(&[3]),
15554                dtype: DType::F32,
15555            });
15556            let add = g.push(Node {
15557                op: Op::Add,
15558                inputs: vec![a, b],
15559                shape: Shape::from_dims(&[3]),
15560                dtype: DType::F32,
15561            });
15562            let mul = g.push(Node {
15563                op: Op::Mul,
15564                inputs: vec![add, a],
15565                shape: Shape::from_dims(&[3]),
15566                dtype: DType::F32,
15567            });
15568            g.set_target_backend(add, BackendId::Cpu);
15569            g.set_target_backend(mul, BackendId::Cpu);
15570            (a, b, add, mul)
15571        };
15572        let mut inputs = StorageCache::new();
15573        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
15574        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
15575
15576        let out = PipelinedExecutor::realize_many(graph, &[add_id, mul_id], inputs)
15577            .expect("realize_many");
15578        assert_eq!(out.len(), 2);
15579
15580        let add_guard = out[0].0.read().unwrap();
15581        let fuel_memory::BackendStorage::Cpu(c) = &add_guard.inner else {
15582            panic!()
15583        };
15584        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 22.0, 33.0]);
15585
15586        let mul_guard = out[1].0.read().unwrap();
15587        let fuel_memory::BackendStorage::Cpu(c) = &mul_guard.inner else {
15588            panic!()
15589        };
15590        // (a + b) * a = [11*1, 22*2, 33*3] = [11, 44, 99].
15591        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 44.0, 99.0]);
15592    }
15593
15594    /// E2E: masked_fill with -inf — the attention masking pattern.
15595    /// x = [1, 2, 3, 4]; mask = [0, 1, 0, 1]; value = -1000.
15596    /// out = [1, -1000, 3, -1000].
15597    #[test]
15598    fn pipelined_realize_masked_fill_attention_pattern() {
15599        let x_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
15600        let mut mask_storage = fuel_memory::from_slice_cpu(&[0u8, 1, 0, 1]);
15601        mask_storage.dtype = DType::Bool; // GAP-168(c): a Bool mask, not U8 bytes
15602        let graph = Arc::new(RwLock::new(Graph::new()));
15603        let (x_id, mask_id, out_id) = {
15604            let mut g = graph.write().unwrap();
15605            let x = g.push(Node {
15606                op: Op::Const,
15607                inputs: vec![],
15608                shape: Shape::from_dims(&[4]),
15609                dtype: DType::F32,
15610            });
15611            let mask = g.push(Node {
15612                op: Op::Const,
15613                inputs: vec![],
15614                shape: Shape::from_dims(&[4]),
15615                dtype: DType::Bool,
15616            });
15617            let out = g.push(Node {
15618                op: Op::MaskedFill {
15619                    value: fuel_ir::Scalar::F32(-1000.0),
15620                },
15621                inputs: vec![x, mask],
15622                shape: Shape::from_dims(&[4]),
15623                dtype: DType::F32,
15624            });
15625            g.set_target_backend(out, BackendId::Cpu);
15626            (x, mask, out)
15627        };
15628        let mut inputs = StorageCache::new();
15629        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
15630        inputs.insert(mask_id, Arc::new(RwLock::new(mask_storage)));
15631        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
15632        let guard = result_arc.read().unwrap();
15633        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15634            panic!("expected Cpu storage");
15635        };
15636        let out: &[f32] = c.as_slice().unwrap();
15637        assert_eq!(out, &[1.0, -1000.0, 3.0, -1000.0]);
15638    }
15639
15640    // ---- WriteSlice (Phase 7.6 step 9c E.3.2) -------------------------------
15641
15642    /// E2E: pipelined realize of `Op::WriteSlice` writing a [1, 3, 2]
15643    /// source slab into a [4, 3, 2] destination at axis-0 row 2 — the
15644    /// canonical KV-cache append shape.
15645    #[test]
15646    fn pipelined_realize_write_slice_kv_cache_append() {
15647        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 24]);
15648        let src_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
15649        let graph = Arc::new(RwLock::new(Graph::new()));
15650        let (dest_id, src_id, ws_id) = {
15651            let mut g = graph.write().unwrap();
15652            let dest = g.push(Node {
15653                op: Op::Const,
15654                inputs: vec![],
15655                shape: Shape::from_dims(&[4, 3, 2]),
15656                dtype: DType::F32,
15657            });
15658            let src = g.push(Node {
15659                op: Op::Const,
15660                inputs: vec![],
15661                shape: Shape::from_dims(&[1, 3, 2]),
15662                dtype: DType::F32,
15663            });
15664            let ws = g.push(Node {
15665                op: Op::WriteSlice {
15666                    ranges: vec![(2, 3), (0, 3), (0, 2)],
15667                    dyn_offset: None,
15668                },
15669                inputs: vec![dest, src],
15670                shape: Shape::from_dims(&[4, 3, 2]), // adopts dest shape
15671                dtype: DType::F32,
15672            });
15673            g.set_target_backend(ws, BackendId::Cpu);
15674            (dest, src, ws)
15675        };
15676        let mut inputs = StorageCache::new();
15677        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
15678        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
15679        let (result_arc, _) = PipelinedExecutor::realize(graph, ws_id, inputs).expect("realize");
15680        let guard = result_arc.read().unwrap();
15681        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15682            panic!("expected Cpu storage");
15683        };
15684        let out: &[f32] = c.as_slice().unwrap();
15685        let expected = [
15686            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,
15687            6.0, // row 2 = source
15688            0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
15689        ];
15690        assert_eq!(out, &expected);
15691    }
15692
15693    /// E2E: pipelined realize of `Op::WriteSlice` adopts the
15694    /// destination's Storage Arc as the output slot (in-place
15695    /// alias) — the resulting Arc points to the SAME bytes the
15696    /// destination was constructed from.
15697    #[test]
15698    fn pipelined_realize_write_slice_aliases_dest_storage() {
15699        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
15700        let src_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
15701        let graph = Arc::new(RwLock::new(Graph::new()));
15702        let (dest_id, src_id, ws_id, dest_arc_external) = {
15703            let mut g = graph.write().unwrap();
15704            let dest = g.push(Node {
15705                op: Op::Const,
15706                inputs: vec![],
15707                shape: Shape::from_dims(&[3, 2]),
15708                dtype: DType::F32,
15709            });
15710            let src = g.push(Node {
15711                op: Op::Const,
15712                inputs: vec![],
15713                shape: Shape::from_dims(&[1, 2]),
15714                dtype: DType::F32,
15715            });
15716            let ws = g.push(Node {
15717                op: Op::WriteSlice {
15718                    ranges: vec![(1, 2), (0, 2)],
15719                    dyn_offset: None,
15720                },
15721                inputs: vec![dest, src],
15722                shape: Shape::from_dims(&[3, 2]),
15723                dtype: DType::F32,
15724            });
15725            g.set_target_backend(ws, BackendId::Cpu);
15726            let arc = Arc::new(RwLock::new(dest_storage));
15727            (dest, src, ws, arc)
15728        };
15729        let mut inputs = StorageCache::new();
15730        inputs.insert(dest_id, Arc::clone(&dest_arc_external));
15731        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
15732        let (result_arc, _) = PipelinedExecutor::realize(graph, ws_id, inputs).expect("realize");
15733        // Bytes were written into the same Arc the caller held —
15734        // the WriteSlice op aliases dest's Storage Arc, not allocates
15735        // a fresh buffer.
15736        assert!(
15737            Arc::ptr_eq(&result_arc, &dest_arc_external),
15738            "WriteSlice output Arc must be the same Arc as the destination's"
15739        );
15740        let guard = dest_arc_external.read().unwrap();
15741        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15742            panic!("expected Cpu storage");
15743        };
15744        let out: &[f32] = c.as_slice().unwrap();
15745        assert_eq!(out, &[0.0, 0.0, 10.0, 20.0, 0.0, 0.0]);
15746    }
15747
15748    // ---- WriteSlice dynamic offset (Phase D symbolic extents) ---------------
15749
15750    /// E2E: pipelined realize of `Op::WriteSlice` with a runtime start
15751    /// offset (`dyn_offset`) resolved through a per-pass `SymEnv`. The
15752    /// width-2 source slab lands at the bound offset (3), not the static
15753    /// `ranges[0].0` placeholder (0) — the persistent-decode KV-cache
15754    /// write at a per-token `cached_len`.
15755    #[test]
15756    fn pipelined_realize_write_slice_dynamic_offset() {
15757        use fuel_ir::{DynScalar, SymId};
15758        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
15759        let src_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0]);
15760        let graph = Arc::new(RwLock::new(Graph::new()));
15761        let sym = SymId(0);
15762        let (dest_id, src_id, ws_id) = {
15763            let mut g = graph.write().unwrap();
15764            let dest = g.push(Node {
15765                op: Op::Const,
15766                inputs: vec![],
15767                shape: Shape::from_dims(&[6]),
15768                dtype: DType::F32,
15769            });
15770            let src = g.push(Node {
15771                op: Op::Const,
15772                inputs: vec![],
15773                shape: Shape::from_dims(&[2]),
15774                dtype: DType::F32,
15775            });
15776            let ws = g.push(Node {
15777                // ranges[0] = (0, 2): the start is a placeholder (ignored —
15778                // overridden by dyn_offset); only the width (2) is read.
15779                op: Op::WriteSlice {
15780                    ranges: vec![(0, 2)],
15781                    dyn_offset: Some((0, DynScalar::Sym(sym))),
15782                },
15783                inputs: vec![dest, src],
15784                shape: Shape::from_dims(&[6]),
15785                dtype: DType::F32,
15786            });
15787            g.set_target_backend(ws, BackendId::Cpu);
15788            (dest, src, ws)
15789        };
15790        let mut inputs = StorageCache::new();
15791        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
15792        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
15793
15794        // Bind cached_len = 3: the slab must land at indices [3, 4].
15795        let mut env = SymEnv::new();
15796        env.bind(sym, 3).unwrap();
15797
15798        let (result_arc, _) = PipelinedExecutor::realize_with_env(graph, ws_id, inputs, env)
15799            .expect("realize_with_env");
15800        let guard = result_arc.read().unwrap();
15801        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15802            panic!("expected Cpu storage");
15803        };
15804        let out: &[f32] = c.as_slice().unwrap();
15805        assert_eq!(
15806            out,
15807            &[0.0, 0.0, 0.0, 7.0, 8.0, 0.0],
15808            "slab must land at the SymEnv-bound offset 3, not the static placeholder 0",
15809        );
15810    }
15811
15812    /// Increment 2a — the data-determined bind seam. After
15813    /// `Op::NonZeroIndices` realizes, the executor reads its runtime count
15814    /// from bundle slot 1 and PUBLISHES it into the produced `SymEnv` under
15815    /// `count_sym`. This is the first op to bind a *data-determined* symbol
15816    /// mid-realize (all prior binds are host-known before realize) — the
15817    /// keystone capability for SSM decode / MoE sparsity / MLA KV.
15818    #[test]
15819    fn pipelined_realize_nonzero_indices_publishes_count() {
15820        use fuel_ir::SymId;
15821        use fuel_ir::storage::{OutputViewSpec, compose_bundle};
15822        // flat [0,1,0,1,1,0] → 3 nonzeros at 1,3,4; capacity 6.
15823        let x_storage = fuel_memory::from_slice_cpu(&[0.0_f32, 1.0, 0.0, 1.0, 1.0, 0.0]);
15824        let graph = Arc::new(RwLock::new(Graph::new()));
15825        let count_sym = SymId(0);
15826        let (x_id, nzi_id) = {
15827            let mut g = graph.write().unwrap();
15828            let x = g.push(Node {
15829                op: Op::Const,
15830                inputs: vec![],
15831                shape: Shape::from_dims(&[2, 3]),
15832                dtype: DType::F32,
15833            });
15834            let capacity = 6usize;
15835            let idx_shape = Shape::from_dims(&[capacity]);
15836            let cnt_shape = Shape::from_dims(&[1]);
15837            let specs = vec![
15838                OutputViewSpec {
15839                    dtype: DType::U32,
15840                    shape: idx_shape.clone(),
15841                    layout: Layout::contiguous(idx_shape.clone()),
15842                    name: Some("indices"),
15843                },
15844                OutputViewSpec {
15845                    dtype: DType::U32,
15846                    shape: cnt_shape.clone(),
15847                    layout: Layout::contiguous(cnt_shape),
15848                    name: Some("count"),
15849                },
15850            ];
15851            let (_bytes, views) = compose_bundle(&specs).unwrap();
15852            let nzi = g.push(Node {
15853                op: Op::NonZeroIndices { count_sym },
15854                inputs: vec![x],
15855                shape: idx_shape,
15856                dtype: DType::U32,
15857            });
15858            g.set_output_views(nzi, Arc::from(views.into_boxed_slice()))
15859                .unwrap();
15860            g.set_target_backend(nzi, BackendId::Cpu);
15861            (x, nzi)
15862        };
15863        let mut inputs = StorageCache::new();
15864        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
15865
15866        let (_arc, _layout, produced) =
15867            PipelinedExecutor::realize_with_env_producing(graph, nzi_id, inputs, SymEnv::new())
15868                .expect("realize_with_env_producing");
15869
15870        assert_eq!(
15871            produced.get(count_sym),
15872            Some(3),
15873            "the executor must publish the data-determined nonzero count into the SymEnv",
15874        );
15875    }
15876
15877    /// A `dyn_offset` whose symbol is unbound in the `SymEnv` surfaces a
15878    /// typed error at realize (never a panic).
15879    #[test]
15880    fn pipelined_realize_write_slice_dynamic_offset_unbound_errors() {
15881        use fuel_ir::{DynScalar, SymId};
15882        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
15883        let src_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0]);
15884        let graph = Arc::new(RwLock::new(Graph::new()));
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                op: Op::WriteSlice {
15901                    ranges: vec![(0, 2)],
15902                    dyn_offset: Some((0, DynScalar::Sym(SymId(0)))),
15903                },
15904                inputs: vec![dest, src],
15905                shape: Shape::from_dims(&[6]),
15906                dtype: DType::F32,
15907            });
15908            g.set_target_backend(ws, BackendId::Cpu);
15909            (dest, src, ws)
15910        };
15911        let mut inputs = StorageCache::new();
15912        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
15913        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
15914        // Empty env — the symbol is unbound.
15915        let result = PipelinedExecutor::realize_with_env(graph, ws_id, inputs, SymEnv::new());
15916        assert!(
15917            result.is_err(),
15918            "unbound dyn_offset symbol must surface a typed error, not a panic",
15919        );
15920    }
15921
15922    /// A runtime offset whose resolved slab runs past the destination
15923    /// capacity errors at realize (never an out-of-bounds write).
15924    #[test]
15925    fn pipelined_realize_write_slice_dynamic_offset_out_of_capacity_errors() {
15926        use fuel_ir::{DynScalar, SymId};
15927        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
15928        let src_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0]);
15929        let graph = Arc::new(RwLock::new(Graph::new()));
15930        let sym = SymId(0);
15931        let (dest_id, src_id, ws_id) = {
15932            let mut g = graph.write().unwrap();
15933            let dest = g.push(Node {
15934                op: Op::Const,
15935                inputs: vec![],
15936                shape: Shape::from_dims(&[6]),
15937                dtype: DType::F32,
15938            });
15939            let src = g.push(Node {
15940                op: Op::Const,
15941                inputs: vec![],
15942                shape: Shape::from_dims(&[2]),
15943                dtype: DType::F32,
15944            });
15945            let ws = g.push(Node {
15946                op: Op::WriteSlice {
15947                    ranges: vec![(0, 2)],
15948                    dyn_offset: Some((0, DynScalar::Sym(sym))),
15949                },
15950                inputs: vec![dest, src],
15951                shape: Shape::from_dims(&[6]),
15952                dtype: DType::F32,
15953            });
15954            g.set_target_backend(ws, BackendId::Cpu);
15955            (dest, src, ws)
15956        };
15957        let mut inputs = StorageCache::new();
15958        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
15959        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
15960        // offset 5 + width 2 = 7 > capacity 6.
15961        let mut env = SymEnv::new();
15962        env.bind(sym, 5).unwrap();
15963        let result = PipelinedExecutor::realize_with_env(graph, ws_id, inputs, env);
15964        assert!(
15965            result.is_err(),
15966            "resolved slab past destination capacity must surface a typed error",
15967        );
15968    }
15969
15970    /// Regression for the PipelinedExecutor ordering-integration session.
15971    ///
15972    /// Graph: `x = Const`, `step_x = Step(x)`, `y = SigmoidInplace(x)`.
15973    /// `Step` and `SigmoidInplace` are both readers of `x`; `Step` is
15974    /// non-destructive, `SigmoidInplace` mutates `x`'s storage. The
15975    /// correct semantic is for `Step` to read PRE-mutation bytes.
15976    ///
15977    /// Pre-this-session (raw `topo_order_multi`): the two are siblings
15978    /// in topo order and the tie-break is unspecified — `SigmoidInplace`
15979    /// could run first, making `step_x` see post-sigmoid bytes
15980    /// (`[1, 1, 1, 1]` because every sigmoid output is positive).
15981    ///
15982    /// Post-this-session: `execution_plan` consults `derive_ordering`,
15983    /// which pins `SigmoidInplace` AFTER every other reader of `x`.
15984    /// `step_x` deterministically sees `x` and is `[1, 0, 1, 0]`.
15985    #[test]
15986    fn pipelined_inplace_with_multiple_readers_orders_correctly() {
15987        use fuel_ir::Shape;
15988        let data = [1.0_f32, -2.0, 3.0, -4.0];
15989        let src_storage = fuel_memory::from_slice_cpu(&data);
15990
15991        let graph = Arc::new(RwLock::new(Graph::new()));
15992        let (x_id, step_id, sig_id) = {
15993            let mut g = graph.write().unwrap();
15994            let x = g.push(Node {
15995                op: Op::Const,
15996                inputs: vec![],
15997                shape: Shape::from_dims(&[4]),
15998                dtype: DType::F32,
15999            });
16000            let step = g.push(Node {
16001                op: Op::Step,
16002                inputs: vec![x],
16003                shape: Shape::from_dims(&[4]),
16004                dtype: DType::F32,
16005            });
16006            let sig = g.push(Node {
16007                op: Op::SigmoidInplace,
16008                inputs: vec![x],
16009                shape: Shape::from_dims(&[4]),
16010                dtype: DType::F32,
16011            });
16012            g.set_target_backend(step, BackendId::Cpu);
16013            g.set_target_backend(sig, BackendId::Cpu);
16014            (x, step, sig)
16015        };
16016
16017        let mut cache = StorageCache::new();
16018        cache.insert(x_id, Arc::new(RwLock::new(src_storage)));
16019
16020        let results = PipelinedExecutor::realize_many(graph, &[step_id, sig_id], cache)
16021            .expect("realize_many");
16022
16023        // step_x must reflect pre-mutation x: sign of [1, -2, 3, -4] →
16024        // [1, 0, 1, 0]. If the executor ran SigmoidInplace first, step
16025        // would see all-positive sigmoid outputs and produce [1, 1, 1, 1].
16026        let step_guard = results[0].0.read().unwrap();
16027        let fuel_memory::BackendStorage::Cpu(c) = &step_guard.inner else {
16028            panic!("expected Cpu storage for step output");
16029        };
16030        let step_out: &[f32] = c.as_slice().expect("f32 cast");
16031        assert_eq!(
16032            step_out,
16033            &[1.0_f32, 0.0, 1.0, 0.0],
16034            "Step must run before SigmoidInplace; got post-mutation bytes"
16035        );
16036        drop(step_guard);
16037
16038        // SigmoidInplace's output Arc IS the mutated cache entry — bytes
16039        // approximate sigmoid([1, -2, 3, -4]).
16040        let sig_guard = results[1].0.read().unwrap();
16041        let fuel_memory::BackendStorage::Cpu(c) = &sig_guard.inner else {
16042            panic!("expected Cpu storage for sigmoid output");
16043        };
16044        let sig_out: &[f32] = c.as_slice().expect("f32 cast");
16045        let sig_ref = [
16046            1.0_f32 / (1.0 + (-1.0_f32).exp()),
16047            1.0_f32 / (1.0 + (2.0_f32).exp()),
16048            1.0_f32 / (1.0 + (-3.0_f32).exp()),
16049            1.0_f32 / (1.0 + (4.0_f32).exp()),
16050        ];
16051        for (got, want) in sig_out.iter().zip(sig_ref.iter()) {
16052            assert!((got - want).abs() < 1e-6, "sigmoid: got {got}, want {want}");
16053        }
16054    }
16055
16056    /// Regression for the PipelinedExecutor ordering-integration session.
16057    ///
16058    /// Canonical residual-connection pattern:
16059    ///   `x = Const`, `y = ReluInplace(x)`, `z = Add(y, x)`.
16060    ///
16061    /// Pre-this-session: `derive_ordering` was never run, so the cycle
16062    /// (Add must precede ReluInplace per ordering edge; Add must follow
16063    /// ReluInplace per data-flow edge through y) was undetected. The
16064    /// executor produced `z = relu(x) + relu(x) = [2, 0, 6, 0]` —
16065    /// silently wrong.
16066    ///
16067    /// Post-this-session: `insert_safety_copies` runs before
16068    /// `execution_plan`, inserts `Op::Copy(x) → x_safe`, rewires Add's
16069    /// `x` input to `x_safe`. Result: `z = relu(x) + x = [2, -2, 6, -4]`.
16070    #[test]
16071    fn pipelined_residual_connection_inserts_safety_copy() {
16072        use fuel_ir::Shape;
16073        let data = [1.0_f32, -2.0, 3.0, -4.0];
16074        let src_storage = fuel_memory::from_slice_cpu(&data);
16075
16076        let graph = Arc::new(RwLock::new(Graph::new()));
16077        let (x_id, _y_id, z_id) = {
16078            let mut g = graph.write().unwrap();
16079            let x = g.push(Node {
16080                op: Op::Const,
16081                inputs: vec![],
16082                shape: Shape::from_dims(&[4]),
16083                dtype: DType::F32,
16084            });
16085            let y = g.push(Node {
16086                op: Op::ReluInplace,
16087                inputs: vec![x],
16088                shape: Shape::from_dims(&[4]),
16089                dtype: DType::F32,
16090            });
16091            let z = g.push(Node {
16092                op: Op::Add,
16093                inputs: vec![y, x],
16094                shape: Shape::from_dims(&[4]),
16095                dtype: DType::F32,
16096            });
16097            g.set_target_backend(y, BackendId::Cpu);
16098            g.set_target_backend(z, BackendId::Cpu);
16099            (x, y, z)
16100        };
16101
16102        let mut cache = StorageCache::new();
16103        cache.insert(x_id, Arc::new(RwLock::new(src_storage)));
16104
16105        let (result_arc, _) = PipelinedExecutor::realize(graph, z_id, cache)
16106            .expect("realize z — insert_safety_copies must break the cycle");
16107
16108        let guard = result_arc.read().unwrap();
16109        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16110            panic!("expected Cpu storage");
16111        };
16112        let got: &[f32] = c.as_slice().expect("f32 cast");
16113        assert_eq!(
16114            got,
16115            &[2.0_f32, -2.0, 6.0, -4.0],
16116            "Add must read pre-mutation x via the inserted safety copy"
16117        );
16118    }
16119
16120    // ------------------------------------------------------------------
16121    // Item 3 end-to-end: SelectiveScan through the bundled-output
16122    // PipelinedExecutor path. The producer allocates bundled
16123    // (y_bytes + last_state_bytes), the kernel writes both slots,
16124    // and the bundled-tuple builder returns each via Op::View.
16125    // ------------------------------------------------------------------
16126
16127    fn cpu_const_f32(
16128        graph: &Arc<RwLock<Graph>>,
16129        cache: &mut StorageCache,
16130        data: &[f32],
16131        dims: &[usize],
16132    ) -> NodeId {
16133        let id = {
16134            let mut g = graph.write().unwrap();
16135            g.push(Node {
16136                op: Op::Const,
16137                inputs: vec![],
16138                shape: Shape::from_dims(dims),
16139                dtype: DType::F32,
16140            })
16141        };
16142        cache.insert(id, Arc::new(RwLock::new(fuel_memory::from_slice_cpu(data))));
16143        id
16144    }
16145
16146    /// `selective_scan_bundled` realizes both `y` and `last_state` in
16147    /// a single `realize_many` pass; the Views project the same
16148    /// producer's bundled Storage Arc and the numerics match the
16149    /// hand-computed single-step kernel test (b=1,s=1,d=1,k=1).
16150    #[test]
16151    fn pipelined_realize_selective_scan_bundled_produces_y_and_last_state() {
16152        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16153        let mut cache = StorageCache::new();
16154
16155        let u_id = cpu_const_f32(&graph, &mut cache, &[3.0], &[1, 1, 1]);
16156        let delta_id = cpu_const_f32(&graph, &mut cache, &[1.0], &[1, 1, 1]);
16157        let a_id = cpu_const_f32(&graph, &mut cache, &[-1.0], &[1, 1]);
16158        let b_id = cpu_const_f32(&graph, &mut cache, &[2.0], &[1, 1, 1]);
16159        let c_id = cpu_const_f32(&graph, &mut cache, &[0.5], &[1, 1, 1]);
16160
16161        let (y_id, last_state_id) = {
16162            let u_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), u_id);
16163            let delta_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), delta_id);
16164            let a_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), a_id);
16165            let b_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), b_id);
16166            let c_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), c_id);
16167            let (y, last_state) = u_t
16168                .selective_scan_bundled(&delta_t, &a_t, &b_t, &c_t, /* delta_softplus */ false)
16169                .expect("selective_scan_bundled");
16170            (y.id(), last_state.id())
16171        };
16172        // Set target_backend on the producer (View nodes inherit it).
16173        {
16174            let mut g = graph.write().unwrap();
16175            let producer = g.node(y_id).inputs[0];
16176            g.set_target_backend(producer, BackendId::Cpu);
16177        }
16178
16179        let outputs =
16180            PipelinedExecutor::realize_many(Arc::clone(&graph), &[y_id, last_state_id], cache)
16181                .expect("realize_many");
16182        let (y_arc, y_layout) = outputs[0].clone();
16183        let (last_state_arc, last_state_layout) = outputs[1].clone();
16184
16185        // Both Views project the same bundled producer Storage Arc.
16186        assert!(
16187            Arc::ptr_eq(&y_arc, &last_state_arc),
16188            "y and last_state Views project the SAME bundled producer Storage",
16189        );
16190
16191        // Hand-computed numerics (single-step recurrence):
16192        // h[0,0,0] = exp(1.0 * -1.0) * 0 + 1.0 * 2.0 * 3.0 = 6.0
16193        // y[0,0,0] = h * c = 6.0 * 0.5 = 3.0
16194        // last_state[0,0,0] = h = 6.0
16195        let guard = y_arc.read().unwrap();
16196        let fuel_memory::BackendStorage::Cpu(c_bytes) = &guard.inner else {
16197            panic!("expected Cpu storage");
16198        };
16199        let typed: &[f32] = c_bytes.as_slice().expect("f32 cast");
16200        assert_eq!(y_layout.start_offset(), 0);
16201        let y_value = typed[y_layout.start_offset()];
16202        assert!((y_value - 3.0).abs() < 1e-5, "y expected 3.0 got {y_value}");
16203        assert_eq!(
16204            last_state_layout.start_offset(),
16205            1,
16206            "slot 1 byte_offset 4 / sizeof(f32) = 1",
16207        );
16208        let ls_value = typed[last_state_layout.start_offset()];
16209        assert!(
16210            (ls_value - 6.0).abs() < 1e-5,
16211            "last_state expected 6.0 got {ls_value}"
16212        );
16213    }
16214
16215    // ---- Ordering-defect repros (MLA decode multi-round WriteSlice) -----
16216
16217    /// DIAGNOSTIC (not a repro by itself): a plain single-hop view chain
16218    /// `S = Slice(X); K = Relu(S)` competing with a SECOND destructive
16219    /// WriteSlice on `X` (`Y = WriteSlice(X, ...)`) within one
16220    /// `realize_many` call. `collect_alias_set` adds `S` to `X`'s alias
16221    /// set (Slice IS `is_view_op`), so `derive_ordering` pins `Y` after
16222    /// `S`'s reader `K` directly. This form is expected to STAY GREEN —
16223    /// recorded here as the control that isolates the Reshape-specific
16224    /// gap exercised by the next test.
16225    #[test]
16226    fn pipelined_write_slice_round2_plain_slice_reader_not_stranded() {
16227        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16228        let mut cache = StorageCache::new();
16229
16230        let b_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16231        let src1_id = cpu_const_f32(&graph, &mut cache, &[1.0, 2.0], &[2]);
16232        let src2_id = cpu_const_f32(&graph, &mut cache, &[99.0, 98.0], &[2]);
16233
16234        let (k_id, y_id) = {
16235            let mut g = graph.write().unwrap();
16236            let x_id = g.push(Node {
16237                op: Op::WriteSlice {
16238                    ranges: vec![(0, 2)],
16239                    dyn_offset: None,
16240                },
16241                inputs: vec![b_id, src1_id],
16242                shape: Shape::from_dims(&[4]),
16243                dtype: DType::F32,
16244            });
16245            let s_id = g.push(Node {
16246                op: Op::Slice {
16247                    dim: 0,
16248                    start: 0,
16249                    len: 2,
16250                },
16251                inputs: vec![x_id],
16252                shape: Shape::from_dims(&[2]),
16253                dtype: DType::F32,
16254            });
16255            let k_id = g.push(Node {
16256                op: Op::Relu,
16257                inputs: vec![s_id],
16258                shape: Shape::from_dims(&[2]),
16259                dtype: DType::F32,
16260            });
16261            // Round 2 OVERLAPS round 1's [0,2) range so a wrong-order
16262            // execution would be numerically visible in K's output.
16263            let y_id = g.push(Node {
16264                op: Op::WriteSlice {
16265                    ranges: vec![(0, 2)],
16266                    dyn_offset: None,
16267                },
16268                inputs: vec![x_id, src2_id],
16269                shape: Shape::from_dims(&[4]),
16270                dtype: DType::F32,
16271            });
16272            g.set_target_backend(x_id, BackendId::Cpu);
16273            g.set_target_backend(k_id, BackendId::Cpu);
16274            g.set_target_backend(y_id, BackendId::Cpu);
16275            (k_id, y_id)
16276        };
16277
16278        let plan = fuel_graph::opt::execution_plan(&graph.read().unwrap(), &[k_id, y_id]);
16279        eprintln!("[diagnostic plain-slice] execution_plan = {:?}", plan,);
16280
16281        let outputs = PipelinedExecutor::realize_many(Arc::clone(&graph), &[k_id, y_id], cache)
16282            .expect("realize_many: plain slice reader must not error");
16283        let (k_arc, _) = &outputs[0];
16284        let guard = k_arc.read().unwrap();
16285        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16286            panic!("expected Cpu storage");
16287        };
16288        let out: &[f32] = c.as_slice().unwrap();
16289        assert_eq!(
16290            out,
16291            &[1.0, 2.0],
16292            "K = relu(slice(X,0,2)) must read PRE-round-2 bytes; got {:?}",
16293            out,
16294        );
16295    }
16296
16297    /// CRITICAL SUSPECT #2 repro: `Op::Reshape`/`Op::Contiguize` compile
16298    /// to `WorkItemKind::ContiguizeOf`, which zero-copy ADOPTS the
16299    /// input's Storage Arc when the input is contiguous at offset 0 —
16300    /// but `Op::Reshape` is NOT in `collect_alias_set`'s alias-extending
16301    /// predicate (only `Op::is_view_op` + `Op::View{..}`). So for
16302    /// `X = write_slice(B, src1); S = X.slice(0, 0, 2) [offset-0
16303    /// contiguous]; R = S.reshape([2]); K = relu(R); Y =
16304    /// write_slice(X, src2)`, `collect_alias_set(X)` stops at `{X, S}`
16305    /// — `R` never enters the alias set, so `derive_ordering` never
16306    /// scans `R`'s consumers (`K`) for pinning against `Y`. `K` and `Y`
16307    /// become simultaneously "ready" once `R` completes, and
16308    /// `execution_plan`'s stable tiebreak (smaller `topo_order_multi`
16309    /// position wins) can schedule `Y` (destructive) BEFORE `K` — `K`
16310    /// then dereferences `R`'s adopted Arc (== `X`'s Arc, mutated
16311    /// in-place by `Y`) and silently reads POST-`Y` bytes. No error;
16312    /// wrong numbers.
16313    #[test]
16314    fn pipelined_write_slice_reshape_adopted_arc_reader_reads_pre_write_bytes() {
16315        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16316        let mut cache = StorageCache::new();
16317
16318        let b_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16319        let src1_id = cpu_const_f32(&graph, &mut cache, &[1.0, 2.0], &[2]);
16320        let src2_id = cpu_const_f32(&graph, &mut cache, &[99.0, 98.0], &[2]);
16321
16322        let (x_id, k_id, y_id) = {
16323            let mut g = graph.write().unwrap();
16324            let x_id = g.push(Node {
16325                op: Op::WriteSlice {
16326                    ranges: vec![(0, 2)],
16327                    dyn_offset: None,
16328                },
16329                inputs: vec![b_id, src1_id],
16330                shape: Shape::from_dims(&[4]),
16331                dtype: DType::F32,
16332            });
16333            let s_id = g.push(Node {
16334                // OFFSET-0 contiguous prefix slice — ContiguizeOf's
16335                // zero-copy fast path requires this at execute time.
16336                op: Op::Slice {
16337                    dim: 0,
16338                    start: 0,
16339                    len: 2,
16340                },
16341                inputs: vec![x_id],
16342                shape: Shape::from_dims(&[2]),
16343                dtype: DType::F32,
16344            });
16345            let r_id = g.push(Node {
16346                op: Op::Reshape(Shape::from_dims(&[2])),
16347                inputs: vec![s_id],
16348                shape: Shape::from_dims(&[2]),
16349                dtype: DType::F32,
16350            });
16351            let k_id = g.push(Node {
16352                op: Op::Relu,
16353                inputs: vec![r_id],
16354                shape: Shape::from_dims(&[2]),
16355                dtype: DType::F32,
16356            });
16357            // Round 2 OVERLAPS round 1's [0,2) range (not the [2,4)
16358            // tail) so a wrong-order execution is numerically visible
16359            // in K's output — a disjoint round 2 would corrupt bytes
16360            // K never reads, masking the defect.
16361            let y_id = g.push(Node {
16362                op: Op::WriteSlice {
16363                    ranges: vec![(0, 2)],
16364                    dyn_offset: None,
16365                },
16366                inputs: vec![x_id, src2_id],
16367                shape: Shape::from_dims(&[4]),
16368                dtype: DType::F32,
16369            });
16370            g.set_target_backend(x_id, BackendId::Cpu);
16371            g.set_target_backend(k_id, BackendId::Cpu);
16372            g.set_target_backend(y_id, BackendId::Cpu);
16373            (x_id, k_id, y_id)
16374        };
16375        let _ = x_id;
16376
16377        let plan = fuel_graph::opt::execution_plan(&graph.read().unwrap(), &[k_id, y_id]);
16378        eprintln!(
16379            "[diagnostic reshape-adopted-arc] execution_plan = {:?}",
16380            plan,
16381        );
16382
16383        let outputs = PipelinedExecutor::realize_many(Arc::clone(&graph), &[k_id, y_id], cache)
16384            .expect("realize_many");
16385        let (k_arc, _) = &outputs[0];
16386        let guard = k_arc.read().unwrap();
16387        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16388            panic!("expected Cpu storage");
16389        };
16390        let out: &[f32] = c.as_slice().unwrap();
16391        // K = relu(reshape(slice(X,0,2))) must read PRE-round-2 bytes:
16392        // relu([1.0, 2.0]) = [1.0, 2.0]. Round 2 overwrites the SAME
16393        // [0,2) range with [99.0, 98.0] — if Y (round 2) runs before K
16394        // (the ordering defect), K instead observes [99.0, 98.0].
16395        assert_eq!(
16396            out,
16397            &[1.0, 2.0],
16398            "K must read PRE-round-2 bytes through the adopted Arc; got {:?} \
16399             (post-round-2 corruption if this fails)",
16400            out,
16401        );
16402    }
16403
16404    /// The MLA-decode shape from `rebind_latent_cache_fresh_graph`'s doc
16405    /// (`fuel-core/src/lazy_deepseek2.rs`): layer L's post-append buffer
16406    /// `X_L_N` (round N) is read TWICE within one realize call — once
16407    /// (non-destructively) through a Slice+Reshape "attention math" view
16408    /// chain whose result becomes an ancestor of layer L+1's round-N
16409    /// write, and again as the DESTINATION of layer L's round-(N+1)
16410    /// append. Reproduces the same Reshape-adoption gap as
16411    /// `pipelined_write_slice_reshape_adopted_arc_reader_reads_pre_write_bytes`
16412    /// at 2-layer scale, confirming the defect is not an artifact of the
16413    /// single-hop minimal form.
16414    #[test]
16415    fn pipelined_write_slice_mla_two_layer_round2_reshape_reader_not_stranded() {
16416        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16417        let mut cache = StorageCache::new();
16418
16419        let b_l_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16420        let src_l_n_id = cpu_const_f32(&graph, &mut cache, &[1.0, 2.0], &[2]);
16421        let b_l1_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16422        let src_l_n1_id = cpu_const_f32(&graph, &mut cache, &[99.0, 98.0], &[2]);
16423
16424        let (x_l_n1_id, x_l1_n_id) = {
16425            let mut g = graph.write().unwrap();
16426            // Round N, layer L: append src_l_n into b_l.
16427            let x_l_n = g.push(Node {
16428                op: Op::WriteSlice {
16429                    ranges: vec![(0, 2)],
16430                    dyn_offset: None,
16431                },
16432                inputs: vec![b_l_id, src_l_n_id],
16433                shape: Shape::from_dims(&[4]),
16434                dtype: DType::F32,
16435            });
16436            // "Attention math" for round N at layer L: read the filled
16437            // prefix, reshape (head-split-style hop), then a kernel.
16438            let s_l_n = g.push(Node {
16439                op: Op::Slice {
16440                    dim: 0,
16441                    start: 0,
16442                    len: 2,
16443                },
16444                inputs: vec![x_l_n],
16445                shape: Shape::from_dims(&[2]),
16446                dtype: DType::F32,
16447            });
16448            let rs_l_n = g.push(Node {
16449                op: Op::Reshape(Shape::from_dims(&[2])),
16450                inputs: vec![s_l_n],
16451                shape: Shape::from_dims(&[2]),
16452                dtype: DType::F32,
16453            });
16454            let r_l_n = g.push(Node {
16455                op: Op::Relu,
16456                inputs: vec![rs_l_n],
16457                shape: Shape::from_dims(&[2]),
16458                dtype: DType::F32,
16459            });
16460            // Round N, layer L+1: append the attention-math result.
16461            let x_l1_n = g.push(Node {
16462                op: Op::WriteSlice {
16463                    ranges: vec![(0, 2)],
16464                    dyn_offset: None,
16465                },
16466                inputs: vec![b_l1_id, r_l_n],
16467                shape: Shape::from_dims(&[4]),
16468                dtype: DType::F32,
16469            });
16470            // Round N+1, layer L: append into x_l_n directly (SAME node
16471            // s_l_n/rs_l_n/r_l_n read from) — OVERLAPPING range so a
16472            // wrong-order execution is numerically visible downstream.
16473            let x_l_n1 = g.push(Node {
16474                op: Op::WriteSlice {
16475                    ranges: vec![(0, 2)],
16476                    dyn_offset: None,
16477                },
16478                inputs: vec![x_l_n, src_l_n1_id],
16479                shape: Shape::from_dims(&[4]),
16480                dtype: DType::F32,
16481            });
16482            g.set_target_backend(x_l_n, BackendId::Cpu);
16483            g.set_target_backend(r_l_n, BackendId::Cpu);
16484            g.set_target_backend(x_l1_n, BackendId::Cpu);
16485            g.set_target_backend(x_l_n1, BackendId::Cpu);
16486            (x_l_n1, x_l1_n)
16487        };
16488
16489        let plan = fuel_graph::opt::execution_plan(&graph.read().unwrap(), &[x_l1_n_id, x_l_n1_id]);
16490        eprintln!("[diagnostic mla-2-layer] execution_plan = {:?}", plan);
16491
16492        let outputs =
16493            PipelinedExecutor::realize_many(Arc::clone(&graph), &[x_l1_n_id, x_l_n1_id], cache)
16494                .expect("realize_many");
16495        // outputs[0] = x_l1_n = write_slice(b_l1, relu(reshape(slice(x_l_n))))
16496        // Must reflect round-N's PRE-round-(N+1) bytes: relu([1,2]) = [1,2].
16497        let (x_l1_n_arc, _) = &outputs[0];
16498        let guard = x_l1_n_arc.read().unwrap();
16499        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16500            panic!("expected Cpu storage");
16501        };
16502        let out: &[f32] = c.as_slice().unwrap();
16503        assert_eq!(
16504            out,
16505            &[1.0, 2.0, 0.0, 0.0],
16506            "layer L+1's round-N append must reflect PRE-round-(N+1) attention \
16507             math output; got {:?} (post-round-(N+1) corruption if this fails)",
16508            out,
16509        );
16510    }
16511}