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/// Persistent per-node output buffers for CUDA-graph capture (the
163/// "CapturedRun executor" build-out). Maps each compute node's [`NodeId`]
164/// to a FIXED-ADDRESS output [`Storage`] Arc that survives across realizes,
165/// so a captured graph's baked kernel-argument addresses stay valid on
166/// replay.
167///
168/// Two modes, both driven by the executor's Kernel arm:
169/// - **`Record`** (warm run): the executor allocates each kernel output as
170///   usual AND records the Arc here. Produces the fixed buffers.
171/// - **`Reuse`** (capture / replay run): the executor REUSES the recorded
172///   Arc for each node — no allocation (mandatory inside a capture scope) —
173///   and the kernel's write-into path writes into it in place.
174///
175/// `None` (the param default at every existing realize call site) preserves
176/// byte-identical behavior: fresh alloc every realize, nothing recorded.
177pub struct PersistentOutputs {
178    map: HashMap<NodeId, Arc<RwLock<Storage>>>,
179    mode: PersistentMode,
180}
181
182#[derive(Clone, Copy, PartialEq, Eq)]
183enum PersistentMode {
184    /// Warm run: allocate + record each kernel output.
185    Record,
186    /// Capture / replay run: reuse the recorded buffer (no alloc).
187    Reuse,
188}
189
190impl PersistentOutputs {
191    /// A fresh recording map for the warm run.
192    pub fn recording() -> Self {
193        Self {
194            map: HashMap::new(),
195            mode: PersistentMode::Record,
196        }
197    }
198
199    /// A reuse map for the capture / replay run, seeded with the buffers
200    /// a prior warm run recorded.
201    pub fn reuse(map: HashMap<NodeId, Arc<RwLock<Storage>>>) -> Self {
202        Self {
203            map,
204            mode: PersistentMode::Reuse,
205        }
206    }
207
208    /// Consume, yielding the recorded NodeId→buffer map (to seed a
209    /// [`reuse`](Self::reuse) map for the capture run).
210    pub fn into_map(self) -> HashMap<NodeId, Arc<RwLock<Storage>>> {
211        self.map
212    }
213}
214
215/// Whether a kernel op's CUDA dispatch wrapper writes its result INTO the
216/// executor-provided `outputs[0]` buffer (rather than allocating a fresh
217/// output and replacing it). Only write-into ops are safe in the
218/// executor's Reuse (capture) mode: a replace-the-buffer wrapper would
219/// allocate inside the capture scope AND change the output's device
220/// address, invalidating the captured graph. [`capture_decode`] rejects
221/// any graph whose compute nodes fall outside this set — a surfaced
222/// capability gap (telemetry-worthy), never a silent miscompile.
223///
224/// The set is the full decode op-set, all VERIFIED to replay bit-exact under
225/// capture (each with a forced-freed-memory-reuse test — see the `diag_*` and
226/// `capture_decode_*` GPU tests).
227///
228/// **History / the big correction (2026-07-10):** `MatMul` and `IndexSelect`
229/// were *briefly* excluded on the belief they weren't capture-safe (matmul's
230/// "cuBLAS internal state", index_select's "host arrays / driver anomaly").
231/// That was ALL WRONG — it was a single Fuel-side bug: `capture_decode`
232/// consumed `inputs` and retained only compute OUTPUTS, so any input buffer
233/// (weights, embedding table) the caller didn't independently hold was FREED
234/// after capture, and the captured graph replayed against freed/reused memory
235/// → intermittent partial-wrong output (cuBLAS "split-K columns", index_select
236/// "element 0"). Fixed by `CapturedDecode::retained_inputs`. cuBLAS gemm +
237/// index_select then replay bit-exact (0/50 even with forced reuse), so the
238/// baracuda GEMV + gather_rows are NOT needed for capture-safety.
239///
240/// **`Rope` (`OpKind::Rope`, corrected 2026-07-11)**: previously excluded on
241/// the (now-disproven) assumption that decode's rope always goes through
242/// `rope_with_tables` (decomposed to elementwise ops including `Concat`, see
243/// below) rather than this fused single-input kernel. Tracing a real Llama
244/// decode graph's capture_decode rejection (`capture_decode_matches_persistent`
245/// GPU test, `fuel-core`) found `Op::Rope` nodes placed by the optimizer
246/// (`rope_with_tables` is not always selected — shape-dependent). The
247/// dispatch wrapper (`cuda_rope_baracuda_wrapper!` in
248/// `baracuda_dispatch.rs`) already delegates to baracuda's write-into
249/// `rope_*_into` FFI — that mechanism predates this predicate fix, it was
250/// simply never added here. `rope.fkc.md`'s CUDA kernel is audited
251/// (`docs/architecture/10-decisions-log.md`, 2026-07-11): grid-stride,
252/// one thread per output element, reads only its own rotation-pair partner,
253/// no atomics/shared-memory/cross-thread state — genuinely capture-safe.
254///
255/// **`Concat` (4b-γ) is capture-safe ONLY for N==2 inputs** — baracuda's
256/// `concat2_into` write-into path covers exactly the decode graph's only
257/// Concat (the rope rotate-half's 2-input `concat(-x2, x1)`, from
258/// `rope_with_tables`'s CUDA decomposition). This predicate alone can't
259/// express the N-arity condition (a pure `OpKind -> bool` fn has no access
260/// to `OpParams`); `capture_decode`'s validation loop adds an explicit N>2
261/// rejection alongside the `op_kind_is_capture_writeinto` check so N>2
262/// Concat is refused at validation time, before the warm pass ever runs —
263/// the write-into wrapper's N>2 fallback (which still allocates internally
264/// for its N-2 intermediates) is therefore provably never invoked while
265/// `persistent.mode == Reuse`. N-ary write-into concat is a real future gap
266/// if a consumer needs it; not built here (no consumer today).
267///
268/// **`Op::Contiguize` (4b-γ)** — `WorkItemKind::ContiguizeOf`, not a
269/// `Kernel` work item, so this predicate never even sees it — became
270/// capture-safe via a separate write-into path (`contiguize_into`) wired
271/// directly into the `ContiguizeOf` executor arm's `PersistentOutputs`
272/// consultation, mirroring how `Kernel` nodes consult this predicate. No
273/// change needed here or in `capture_decode`'s validation loop: a given
274/// `ContiguizeOf` node's allocate-vs-zero-copy branch is a static
275/// layout/stride property, identical across the warm and capture passes
276/// (both replay the same compiled item list), so it's unconditionally safe
277/// once wired to `PersistentOutputs`.
278///
279/// LESSON: a bug reproduced through the full harness but not in isolation is
280/// the harness's fault, not the callee's — chase the differentiator (here,
281/// input lifetime), don't conclude "kernel/library not capture-safe" from it.
282///
283/// [`capture_decode`]: PipelinedExecutor::capture_decode
284/// GAP-217b: gated on `cuda` because its ONLY caller is
285/// `capture_decode` (`#[cfg(feature = "cuda")]`, ~:1266). Without this it
286/// reports as dead code on every default build — a false signal on a
287/// predicate whose doc comment is a record of hard-won capture-safety
288/// findings, i.e. exactly the kind of item someone eventually deletes for
289/// being "unused". Gating it makes the reachability claim honest instead of
290/// leaving a warning to argue the opposite.
291#[cfg(feature = "cuda")]
292fn op_kind_is_capture_writeinto(op: OpKind) -> bool {
293    matches!(
294        op,
295        // Binary elementwise — residual + gating.
296        OpKind::AddElementwise
297            | OpKind::SubElementwise
298            | OpKind::MulElementwise
299            | OpKind::DivElementwise
300            | OpKind::MaximumElementwise
301            | OpKind::MinimumElementwise
302            | OpKind::PowElementwise
303            | OpKind::RemElementwise
304            // Softmax.
305            | OpKind::SoftmaxLastDim
306            | OpKind::LogSoftmaxLastDim
307            // Affine (mul_scalar/add_scalar — the 1/√d attention scale).
308            | OpKind::Affine
309            // Dense matmul (cuBLAS gemm_dense — capture-safe; the earlier
310            // "not replay-stable" was the dangling-input bug, now fixed).
311            | OpKind::MatMul
312            // Embedding lookup (was the same dangling-input bug, not a kernel issue).
313            | OpKind::IndexSelect
314            // RMS-norm: capture-safe via the device's fixed workspace for its
315            // per-row RMS scratch (warm sizes it; capture + replay reuse, no alloc).
316            | OpKind::RmsNormLastDim
317            // Unary activations (write-into + workspace-free).
318            | OpKind::SiluElementwise
319            | OpKind::GeluTanhElementwise
320            | OpKind::GeluElementwise
321            // Negation (write-into + workspace-free) — the rope rotate-half
322            // decomposition's `neg_second` half (CapturedRun 4b-resume: rope
323            // runs decomposed on CUDA since there's no rotate-half fused kernel).
324            | OpKind::NegElementwise
325            // N==2 concat only (rope rotate-half) — see the doc comment
326            // above; N>2 is rejected explicitly in capture_decode's
327            // validation loop, not by this predicate.
328            | OpKind::Concat
329            // Rotary position embedding (fused single-input kernel) — see
330            // the doc comment above.
331            | OpKind::Rope
332    )
333}
334
335/// The product of [`PipelinedExecutor::capture_decode`]: a replayable
336/// CUDA-graph capture of a single-device decode step plus the handle to
337/// the fixed output buffer the captured launches write into.
338///
339/// Replay contract: update the fixed INPUT buffers (the Arcs passed into
340/// `capture_decode`) in place via H2D, call [`run`](Self::run)`.replay()`,
341/// then read [`output`](Self::output) — the captured launches recompute
342/// into it at the same device addresses. `persistent` holds every compute
343/// node's fixed buffer (the same addresses baked into the graph), exposed
344/// so a caller can inspect / retain them across replays.
345#[cfg(feature = "cuda")]
346pub struct CapturedDecode {
347    /// The instantiated, replayable capture.
348    pub run: fuel_cuda_backend::CapturedRun,
349    /// The realize target's fixed output buffer (written by replay).
350    pub output: Arc<RwLock<Storage>>,
351    /// The target's resolved output [`Layout`].
352    pub output_layout: Layout,
353    /// Every compute node's fixed output buffer (the capture-baked
354    /// addresses). Retained so they outlive the [`CapturedRun`].
355    pub persistent: HashMap<NodeId, Arc<RwLock<Storage>>>,
356    /// EVERY input buffer's Arc (weights, KV, per-token inputs), retained so
357    /// their device addresses — baked into the captured graph — stay valid
358    /// for the life of the capture. Without this, an input buffer the CALLER
359    /// doesn't independently hold is freed when `capture_decode` returns
360    /// (it consumes `inputs`), and replay reads freed/reused memory. This is
361    /// the fix for the "index_select / matmul mis-replay" — a dangling input
362    /// pointer, NOT a kernel/cuBLAS/driver capture issue.
363    pub retained_inputs: Vec<Arc<RwLock<Storage>>>,
364}
365
366/// Warm→capture→replay orchestration over [`capture_decode`] for a
367/// persistent decode loop (the CapturedRun build-out, Increment 4a).
368///
369/// Owns the FIXED per-token INPUT buffers — the ones that change each token
370/// (token-id, rope position, mask, KV write offset) — at stable device
371/// addresses, plus the [`CapturedDecode`]. Each generated token is one
372/// [`replay_token`](Self::replay_token): H2D-update the fixed input buffers
373/// IN PLACE (same addresses the captured graph reads), replay the captured
374/// graph (one `cuGraphLaunch`, no per-op launch overhead), then read the
375/// output at its fixed address.
376///
377/// The mechanism is graph-agnostic: [`capture`](Self::capture) runs a
378/// single-device CUDA decode graph through the persistent-output executor;
379/// the model layer (fuel-core's `DecodeSession`) supplies the held graph +
380/// the fixed buffers and drives the per-token updates. Every compute op must
381/// be capture-safe (`op_kind_is_capture_writeinto`) — `capture` surfaces any
382/// that are not (today: matmul, index_select — pending baracuda kernels).
383///
384/// [`capture_decode`]: PipelinedExecutor::capture_decode
385#[cfg(feature = "cuda")]
386pub struct CapturedDecodeSession {
387    device: fuel_cuda_backend::CudaDevice,
388    captured: CapturedDecode,
389    /// Per-token input buffers, keyed by NodeId — fixed device addresses
390    /// updated in place each token (the input addresses the captured graph
391    /// reads). A subset of the `inputs` handed to [`capture`](Self::capture).
392    per_token_inputs: HashMap<NodeId, Arc<RwLock<Storage>>>,
393    /// EVERY input buffer's Arc (weights, KV, per-token), retained so their
394    /// device addresses stay valid for the life of the capture. `capture_decode`
395    /// consumes `inputs` and only `CapturedDecode` retains the compute-output
396    /// buffers, so without this the WEIGHT input buffers would be freed and the
397    /// captured graph would replay against freed memory.
398    _retained_inputs: Vec<Arc<RwLock<Storage>>>,
399}
400
401#[cfg(feature = "cuda")]
402impl CapturedDecodeSession {
403    /// Capture the decode graph once against the given fixed input buffers.
404    ///
405    /// `inputs` are ALL the graph's leaves (weights, KV, per-token data) at
406    /// fixed device addresses; `per_token_input_ids` names the subset that
407    /// changes each token. The per-token Arcs are snapshotted (shared, not
408    /// copied) so overwriting them in place later feeds the captured graph's
409    /// fixed input reads. Returns a session ready for
410    /// [`replay_token`](Self::replay_token). Errors (never panics) if the
411    /// graph carries a capture-unsafe op or a per-token id is not an input.
412    pub fn capture(
413        graph: Arc<RwLock<Graph>>,
414        target: NodeId,
415        inputs: StorageCache,
416        per_token_input_ids: &[NodeId],
417        sym_env: SymEnv,
418    ) -> Result<Self> {
419        use fuel_memory::BackendStorage;
420        // Snapshot the per-token input Arcs + retain EVERY input Arc BEFORE
421        // `inputs` is consumed by capture_decode (so no input buffer's device
422        // address is freed while the captured graph still bakes it).
423        let retained_inputs: Vec<Arc<RwLock<Storage>>> = inputs.values().cloned().collect();
424        let mut per_token_inputs = HashMap::with_capacity(per_token_input_ids.len());
425        for &id in per_token_input_ids {
426            let arc = inputs.get(&id).cloned().ok_or_else(|| {
427                Error::Msg(format!(
428                    "CapturedDecodeSession::capture: per-token input {:?} not in inputs",
429                    id,
430                ))
431                .bt()
432            })?;
433            per_token_inputs.insert(id, arc);
434        }
435        // Derive the CUDA device from any input.
436        let device = {
437            let any = per_token_inputs
438                .values()
439                .next()
440                .or_else(|| inputs.values().next())
441                .ok_or_else(|| {
442                    Error::Msg("CapturedDecodeSession::capture: no inputs".into()).bt()
443                })?;
444            let guard = any.read().map_err(|_| poisoned("input storage"))?;
445            match &guard.inner {
446                BackendStorage::Cuda(c) => c.device().clone(),
447                other => {
448                    return Err(Error::Msg(format!(
449                        "CapturedDecodeSession::capture: input is BackendStorage::{:?}, not Cuda",
450                        other.backend_id(),
451                    ))
452                    .bt());
453                }
454            }
455        };
456        let captured = PipelinedExecutor::capture_decode(graph, target, inputs, sym_env)?;
457        Ok(Self {
458            device,
459            captured,
460            per_token_inputs,
461            _retained_inputs: retained_inputs,
462        })
463    }
464
465    /// Replay one token. For each `(node_id, host_bytes)` in `updates`,
466    /// overwrite that per-token input buffer IN PLACE (H2D, same device
467    /// address), then replay the captured graph and return the output buffer
468    /// (now holding this token's result). `host_bytes.len()` must equal the
469    /// buffer's byte length.
470    /// **Every compute node's output buffer, keyed by `NodeId`** — the
471    /// capture's inspection surface.
472    ///
473    /// Capture is usually described as a launch-overhead optimization, and that
474    /// is what Fuel currently exploits (measured 4.28x at k=1). But recording
475    /// the graph has a second, unexploited consequence: **every intermediate
476    /// gets a FIXED device address that survives across replays.** On the
477    /// ordinary path intermediates are transient — allocated, consumed, freed —
478    /// so there is nothing to look at after the fact.
479    ///
480    /// That makes a captured session a **whole-graph, per-node, addressable
481    /// snapshot of what actually executed**, which is a different artifact from
482    /// anything the planner records. `OptimizedGraph::placement_of` says what
483    /// the optimizer DECIDED; this says what the device HELD. Those can
484    /// disagree, and an independent second instrument is the only way to notice.
485    ///
486    /// Uses this enables, none of which need re-running the model:
487    /// - read any intermediate after a token;
488    /// - compare per-node against a CPU oracle — whole-graph differential,
489    ///   where FKC verification today is per-KERNEL;
490    /// - measure real per-op divergence for the tolerance/Judge work instead of
491    ///   modelling it.
492    ///
493    /// Buffers are live device memory owned by the capture; they are overwritten
494    /// by the next `replay_token`. Read them before replaying again.
495    pub fn node_outputs(&self) -> &HashMap<NodeId, Arc<RwLock<Storage>>> {
496        &self.captured.persistent
497    }
498
499    pub fn replay_token(&self, updates: &[(NodeId, &[u8])]) -> Result<Arc<RwLock<Storage>>> {
500        use fuel_memory::BackendStorage;
501        for (id, bytes) in updates {
502            let arc = self.per_token_inputs.get(id).ok_or_else(|| {
503                Error::Msg(format!(
504                    "CapturedDecodeSession::replay_token: {:?} is not a per-token input",
505                    id,
506                ))
507                .bt()
508            })?;
509            let guard = arc.read().map_err(|_| poisoned("per-token input"))?;
510            match &guard.inner {
511                BackendStorage::Cuda(c) => c.write_from_host(bytes)?,
512                other => {
513                    return Err(Error::Msg(format!(
514                        "CapturedDecodeSession::replay_token: input {:?} is \
515                         BackendStorage::{:?}, not Cuda",
516                        id,
517                        other.backend_id(),
518                    ))
519                    .bt());
520                }
521            }
522        }
523        self.captured.run.replay(&self.device)?;
524        self.device.synchronize()?;
525        Ok(Arc::clone(&self.captured.output))
526    }
527
528    /// The fixed output buffer, updated by each
529    /// [`replay_token`](Self::replay_token). Holds the warm-run result until
530    /// the first replay.
531    pub fn output(&self) -> &Arc<RwLock<Storage>> {
532        &self.captured.output
533    }
534
535    /// The output's resolved [`Layout`].
536    pub fn output_layout(&self) -> &Layout {
537        &self.captured.output_layout
538    }
539}
540
541/// What flavor of work item the executor is processing.
542/// Disambiguates the four cases:
543enum WorkItemKind {
544    /// `Op::Const` — its Storage Arc is already in the input cache.
545    /// Executor verifies the entry exists and moves on.
546    ConstAdopt,
547    /// Metadata-only view op (`Op::Transpose`, `Op::Permute`,
548    /// `Op::BroadcastTo`): the output's Storage Arc IS the
549    /// input's Storage Arc (bytes shared); `output_layout`
550    /// describes the strided view.
551    ViewOf { input: NodeId },
552    /// Reshape-style adoption: the output is contiguous in
553    /// `output_layout.shape()`. If the input is already contiguous
554    /// + zero offset, the output Arc is the input Arc (zero copy).
555    ///
556    /// Otherwise, the executor auto-contiguizes the input into a
557    /// fresh Arc and uses that.
558    ContiguizeOf { input: NodeId },
559    /// Computational kernel: allocate output, run the compiled
560    /// kernel, store the result. `compiled` is `Some(...)`.
561    Kernel,
562    /// `Op::Iota { len }` — 0-input F32 position generator
563    /// `[0.0, 1.0, …, (len-1)]`. Direct executor dispatch (no kernel /
564    /// binding-table lookup), like `WorkItemKind::Alloc`: a leaf has no
565    /// `inputs[0]` to inherit a backend from, so it can't take the normal
566    /// kernel path. The executor fills the sequence on CPU.
567    Iota { len: usize },
568    /// `Op::Release` — metadata-only "this storage is no longer
569    /// needed" directive. Per `Op::Release`'s contract: the output
570    /// is a zero-element marker (NodeId placeholder for graph
571    /// bookkeeping; never read by any consumer). The executor emits
572    /// a zero-byte CPU `Storage` at the node's slot so downstream
573    /// cache lookups don't surface "missing slot" errors; the actual
574    /// deallocation of `inputs[0]` is driven by `destructive_input`
575    /// in the realize loop (Phase B), which drops the Arc held by
576    /// the cache. The held Arc's Drop chain frees device memory
577    /// (sync for CPU, stream-deferred for async backends).
578    ReleaseMarker,
579    /// `Op::WriteSlice` — in-place scatter write. The output adopts
580    /// the destination input's Storage Arc (zero-copy alias); the
581    /// kernel mutates that Arc's bytes via a write lock. The source
582    /// input's slab is copied into the destination's rectangular
583    /// region defined by `OpParams::WriteSlice`'s `ranges`.
584    ///
585    /// Carries `dest`/`source` NodeIds so the executor can:
586    /// 1. Adopt the dest's Arc as the kernel's output slot.
587    /// 2. Pass only the source as a kernel input (the dest is not
588    ///    a read-input to the kernel; it's the destination buffer
589    ///    being mutated in place).
590    ///
591    /// The realize loop's `destructive_input` cleanup evicts the
592    /// `dest` NodeId from the cache after this op runs (per
593    /// `Op::WriteSlice`'s destructive_input == Some(0) contract).
594    /// Downstream consumers read post-write bytes via this op's
595    /// own NodeId, not the dest's.
596    WriteSlice { dest: NodeId, source: NodeId },
597    /// `Op::WriteSliceRotating` — like `WriteSlice` but the rotating
598    /// axis wraps modulo `modulus`. Carries `dest`/`source`/`position`
599    /// NodeIds; the kernel reads the U32 position from `position`'s
600    /// storage and splits the write across the ring boundary if
601    /// `position % modulus + slab_len > modulus`.
602    WriteSliceRotating {
603        dest: NodeId,
604        source: NodeId,
605        position: NodeId,
606    },
607    /// `Op::WriteSliceDoff` — like `WriteSlice` but the start on `axis`
608    /// is read from a device-resident rank-0 `I64` scalar (`offset`)
609    /// at kernel launch, not host-baked. Carries `dest`/`source`/
610    /// `offset` NodeIds; the CUDA wrapper threads `offset`'s device
611    /// pointer straight to the kernel (no D2H) so a captured graph
612    /// replays at the host-updated position. No ring wrap.
613    WriteSliceDoff {
614        dest: NodeId,
615        source: NodeId,
616        offset: NodeId,
617    },
618    /// `Op::Copy { target }` — produce a fresh Storage on
619    /// `target_location`, copying bytes from `inputs[0]`'s residency.
620    ///
621    /// The kernel lookup goes through the standard binding-table path
622    /// at `(OpKind::Copy, [dt, dt], source_backend)`, so D2H is a peer
623    /// of every other op (architecture identity check #1). The
624    /// dedicated WorkItemKind exists because Op::Copy is the one op
625    /// whose output's device differs from `target_backend`:
626    /// `target_backend` is the **source** backend (where the kernel
627    /// runs — it owns the download path), while `target_location`
628    /// drives output allocation. WorkItemKind::Kernel always allocates
629    /// output on `target_backend`; Copy needs the override.
630    ///
631    /// Phase 2 of the bridge-retirement trajectory. Replaces the
632    /// per-variant `match self` in `BackendStorage::read_to_cpu_bytes`
633    /// (deleted alongside this commit) with a graph-level node the
634    /// optimizer can see, cost, and eventually fuse.
635    Copy { target_location: DeviceLocation },
636    /// `Op::Move { target }` — `Op::Copy`'s destructive sibling:
637    /// produce a fresh Storage on `target_location` via the same
638    /// data-movement kernel (binding-table lookup at
639    /// `(OpKind::Copy, [dt, dt], source_backend)`; output allocation
640    /// driven by `target_location`), then release the source. The
641    /// release half is NOT handled in the executor's arm — it rides
642    /// the realize loop's `destructive_input` cleanup
643    /// (`Op::Move::destructive_input() == Some(0)`), exactly like
644    /// `Op::Release`: the cache's Arc to the source drops after the
645    /// move runs and the Drop chain frees device memory (sync for
646    /// CPU, stream-deferred for async backends).
647    ///
648    /// Ordering safety is the graph's job, not this arm's:
649    /// `execution_plan` integrates `derive_ordering`, which pins the
650    /// Move AFTER every non-destructive reader of the source's alias
651    /// set, and `insert_safety_copies` snapshots the source for any
652    /// reader that data-flow-depends on the Move's output. A Move
653    /// therefore never strands a sibling consumer of its source.
654    ///
655    /// Same-device moves are legal and match the legacy
656    /// `GraphExecutor` contract: a plain copy producing fresh
657    /// storage on the same device, with the source still evicted
658    /// afterward.
659    Move { target_location: DeviceLocation },
660    /// `Op::Alloc { target }` — produce a freshly-allocated, zero-
661    /// initialized Storage on `target_location` with the node's shape
662    /// + dtype. Zero inputs.
663    ///
664    /// Doesn't dispatch through the binding table — the executor's
665    /// arm calls each backend's native allocator directly. For
666    /// non-CPU targets it derives the device handle by searching the
667    /// input cache for any storage on `target_location`'s backend
668    /// (callers seed this via
669    /// `fuel-tensor::pipelined_bridge::device_seed_storage`).
670    ///
671    /// Phase 3a of the bridge-retirement trajectory (post-9c).
672    /// Replaces `fuel-tensor::inference_context::alloc_zeroed_on`'s
673    /// per-`DeviceLocation` match with a graph node the optimizer
674    /// can see; the per-backend match moves from fuel-core's bridge
675    /// layer into fuel-storage's executor (the architectural dispatch
676    /// layer).
677    Alloc { target_location: DeviceLocation },
678    /// `Op::ZeroFill` — fill the input's storage bytes with zero,
679    /// in place. Adopts the input's Storage Arc as the output (same
680    /// Storage; bytes mutated). Destructive on `inputs[0]`.
681    ///
682    /// Direct executor dispatch (no binding-table lookup) per the
683    /// same rationale as `WorkItemKind::Alloc`: structural op,
684    /// per-backend dispatch. Per-backend behaviour:
685    /// - CPU: `bytes_mut().fill(0)` via the CoW path.
686    /// - CUDA: `CudaStorageBytes::zero_async` via baracuda alpha.30's
687    ///   `DeviceBuffer::zero_async` (cuMemsetD8Async, in-place).
688    /// - Vulkan: `VulkanBackend::fill_bytes_zero` via
689    ///   `vkCmdFillBuffer` — device-side, ~2× the bandwidth of the
690    ///   old host-staged zeros path that `alloc_zeroed_on` used.
691    ///
692    /// Phase 3a follow-up of bridge-retirement (post-9c). Pairs with
693    /// the uninit-alloc `WorkItemKind::Alloc` to give the
694    /// architecturally clean "Op::Alloc (uninit) → Op::ZeroFill
695    /// (explicit fill)" pipeline.
696    ZeroFill,
697    /// In-place kernel — the output adopts the input at index
698    /// `target_idx`'s Storage Arc and the kernel mutates that Arc's
699    /// bytes through a single write lock. Phase 3 of the in-place ops
700    /// infrastructure
701    /// (`docs/session-prompts/in-place-ops-infrastructure.md`).
702    ///
703    /// Kernel lookup goes through the standard binding table at
704    /// `(op_to_op_kind, [target_dtype], target_backend)`. The wrapper's
705    /// `inputs` slice is empty; `outputs[0]` is the target Arc. The
706    /// wrapper acquires `outputs[0]`'s write lock and calls the
707    /// underlying single-pointer kernel (e.g. baracuda's
708    /// `affine_inplace_*` on CUDA, or the chassis with `src == dst`
709    /// on CPU).
710    ///
711    /// Output Arc adoption: identical to `WorkItemKind::WriteSlice`
712    /// (the output's slot = the target's Arc; the realize loop's
713    /// `destructive_input` cleanup evicts the target's NodeId from the
714    /// cache afterward). Downstream consumers read post-mutation bytes
715    /// through this op's NodeId, not the target's.
716    InplaceKernel {
717        /// Index into `inputs` whose Storage Arc the output adopts.
718        /// Always equal to the source `Op::destructive_input().unwrap()`;
719        /// stored explicitly so the executor doesn't re-derive it.
720        target_idx: usize,
721    },
722    /// `Op::View { slot }` — multi-output projection (Option C,
723    /// Session 4). The output's Storage Arc IS the producer's Arc;
724    /// the WorkItem's `output_layout` was prepared by
725    /// [`fuel_graph::NodeHandle::view`] with the slot's `byte_offset`
726    /// baked into `Layout::start_offset` so downstream kernels reading
727    /// the producer's bytes as `slot_dtype` elements land on the
728    /// slot's first byte. Structurally identical to [`Self::ViewOf`]
729    /// at execute time — kept distinct so error messages and
730    /// telemetry have a clean dispatch point.
731    SlotView { producer: NodeId },
732    /// `Op::ViewOwned { slot }` — multi-output projection with an
733    /// independent destination buffer. At realize time, allocate a
734    /// fresh contiguous Storage of the slot's `(shape, dtype)` on
735    /// the producer's device, then memcpy
736    /// `producer.bytes[slot.byte_offset .. slot.byte_offset + slot.len_bytes]`
737    /// into the new storage. Session 4 ships the CPU path; non-CPU
738    /// backends return a typed error until their copy-with-offset
739    /// hooks land in the followup session.
740    SlotOwn { producer: NodeId, slot: u32 },
741}
742
743/// One unit of work emitted by the compiler thread to the executor
744/// thread.
745/// Phase name of a work item's kind, for the executor's host-phase accounting
746/// (`op_profile::PhaseTimer`). One name per variant so the table splits the
747/// per-item executor time by what the item is.
748fn work_item_kind_name(kind: &WorkItemKind) -> &'static str {
749    match kind {
750        WorkItemKind::ConstAdopt => "item.ConstAdopt",
751        WorkItemKind::ViewOf { .. } => "item.ViewOf",
752        WorkItemKind::ContiguizeOf { .. } => "item.ContiguizeOf",
753        WorkItemKind::Kernel => "item.Kernel",
754        WorkItemKind::Iota { .. } => "item.Iota",
755        WorkItemKind::ReleaseMarker => "item.ReleaseMarker",
756        WorkItemKind::WriteSlice { .. } => "item.WriteSlice",
757        WorkItemKind::WriteSliceRotating { .. } => "item.WriteSliceRotating",
758        WorkItemKind::WriteSliceDoff { .. } => "item.WriteSliceDoff",
759        WorkItemKind::Copy { .. } => "item.Copy",
760        WorkItemKind::Move { .. } => "item.Move",
761        WorkItemKind::Alloc { .. } => "item.Alloc",
762        WorkItemKind::ZeroFill => "item.ZeroFill",
763        WorkItemKind::InplaceKernel { .. } => "item.InplaceKernel",
764        WorkItemKind::SlotView { .. } => "item.SlotView",
765        WorkItemKind::SlotOwn { .. } => "item.SlotOwn",
766    }
767}
768
769/// Work items that choose no backend of their own: adopting an input-cache entry
770/// (`Op::Const`), the metadata-only view items, and `ContiguizeOf` (it runs on its
771/// input's backend; its `target_backend` is a `Cpu` placeholder, which made every
772/// Qwen3 decode step look like ~900 Vulkan -> Cpu -> Vulkan switches and forced a
773/// batch submit at each one). Their `target_backend` is a placeholder
774/// (a `Const` is always stamped `Cpu`; a view inherits its producer's or
775/// defaults to `Cpu`), so letting them take part in the chunk-boundary logic made
776/// every weight `Const` that sits between two Vulkan kernels look like a
777/// Vulkan -> Cpu -> Vulkan backend switch: the executor armed `multi_backend`,
778/// submitted the open Vulkan batch at each "switch", and then waited for it
779/// before the next Vulkan op. In Qwen3-0.6B decode that was about 400 forced
780/// submit-and-wait round trips per step (`docs/research/qwen3-vulkan-decode-profile.md`).
781fn is_backend_neutral(kind: &WorkItemKind) -> bool {
782    matches!(
783        kind,
784        WorkItemKind::ConstAdopt
785            | WorkItemKind::ViewOf { .. }
786            | WorkItemKind::SlotView { .. }
787            | WorkItemKind::ContiguizeOf { .. }
788    )
789}
790
791struct WorkItem {
792    node_id: NodeId,
793    inputs: Vec<NodeId>,
794    /// Number of elements in the output (for output Storage
795    /// allocation; multiplied by dtype size at allocation time).
796    elem_count: usize,
797    dtype: DType,
798    target_backend: BackendId,
799    /// What kind of work this represents (kernel vs adopt vs view).
800    kind: WorkItemKind,
801    /// `Some` for [`WorkItemKind::Kernel`]; `None` for the other
802    /// two. Carries the resolved kernel ref + op_params.
803    compiled: Option<CompiledNode>,
804    /// The output's [`Layout`]. For kernels: always
805    /// `Layout::contiguous(node.shape)`. For metadata-only view
806    /// ops: a strided/broadcast Layout pointing at the input's
807    /// Storage. Carried so the executor can publish the right
808    /// Layout into its layout cache and ultimately return it from
809    /// [`PipelinedExecutor::realize`].
810    output_layout: Layout,
811    /// Index into `inputs` whose storage gets destroyed by this op
812    /// (`Op::Release` / `Op::Move` → `Some(0)`; non-destructive ops
813    /// → `None`). The executor evicts the destroyed input from the
814    /// cache after the op runs, unless it's also in the realize
815    /// target set. Snapshot of `node.op.destructive_input()` at
816    /// compile time.
817    destructive_input: Option<usize>,
818    /// Multi-output bundle metadata (Option C, item 3). `Some(_)`
819    /// when the node was declared multi-output via
820    /// `Graph::set_output_views`; the Kernel arm allocates one
821    /// contiguous output Storage sized to fit every slot's bytes,
822    /// then attaches the bundle via `Storage::with_bundle` so
823    /// downstream `Op::View`/`Op::ViewOwned` nodes resolve
824    /// correctly.
825    output_bundle: Option<Arc<[fuel_ir::storage::OutputView]>>,
826}
827
828/// Merge the graph's side-effect roots into the caller's requested
829/// roots. Preserves caller order (user roots come first), dedupes,
830/// and appends side-effect-bearing nodes (`Op::Print`, `Op::Save`,
831/// etc.) so their effects fire even when not reachable from the
832/// caller's roots. Mirrors `fuel-graph-executor::extend_with_side_effect_roots`.
833///
834/// Short-circuits to a borrow-equivalent `Vec<NodeId>` when the graph
835/// has no side-effect roots — the common case during inference.
836fn extend_with_side_effect_roots(graph: &Graph, user_roots: &[NodeId]) -> Vec<NodeId> {
837    let side = graph.side_effect_roots();
838    if side.is_empty() {
839        return user_roots.to_vec();
840    }
841    let mut out = Vec::with_capacity(user_roots.len() + side.len());
842    out.extend_from_slice(user_roots);
843    for &s in side {
844        if !out.contains(&s) {
845            out.push(s);
846        }
847    }
848    out
849}
850
851/// Pipelined executor: walks a graph, compiles each node in a
852/// dedicated thread, executes the compiled stream on the calling
853/// thread.
854///
855/// # Architectural commitments (Phase 7.6 step 9c)
856///
857/// ## Fail-fast dispatch — no runtime CPU fallback
858///
859/// The binding-table lookup is fail-fast. If
860/// `global_bindings().lookup(op_kind, dtypes, backend)` returns
861/// `None`, `realize` / `realize_many` surface a typed `Error::Msg`
862/// at compile time. There is **no runtime fallback** to a CPU
863/// sibling when a registered kernel returns `Err`; we commit to the
864/// backend contract that registered kernels must succeed for shapes
865/// matching their declared coverage.
866///
867/// Rationale: per-decision-point alternatives (architecture v1.0
868/// §04) already let multiple backends register at the same key. If
869/// a backend's coverage is partial, the right answer is to register
870/// only the shapes it actually handles — not to silently fall back
871/// at runtime, which masks bugs and slows the hot path. The
872/// long-term home for "this op on this device" is graph-level
873/// dispatch insertion (Op::Copy edges to a backend that does
874/// support the shape), which makes the routing decision visible in
875/// the IR rather than hidden in the executor. Picker-arc step 4b
876/// landed exactly that: `compile_plan`'s off-device fallback
877/// (`PlanOptions::fallback_placements_for`) admits a candidate on
878/// another device when the pinned device lacks the implementation,
879/// and the bridge's cross-device-copy pass stitches residency
880/// around the off-device winner. There is exactly ONE fallback
881/// owner — the plan-time picker; this executor still dispatches
882/// fail-fast, and ops with no implementation anywhere surface the
883/// plan-time `NoBackendForOp` error.
884///
885/// This is a deliberate departure from the legacy executor's
886/// `cpu_fallback(op, inputs, shape, dtype, cache)` semantics.
887///
888/// ## Optimizer separation — callers compose
889///
890/// The pipelined executor does **not** run `fuel_graph::opt` or any
891/// `RuleRegistry` pass itself. Callers that want graph-level
892/// optimization compose it at the call site:
893///
894/// ```ignore
895/// let optimized_targets = registry.optimize_to_fixpoint(&graph, &targets);
896/// PipelinedExecutor::realize_many(graph, &optimized_targets, inputs)?;
897/// ```
898///
899/// Rationale: the legacy `GraphExecutor<B>::with_optimization(bool)`
900/// coupling reflected its per-typed-entry API surface
901/// (`realize_f32`, etc.) where the convenience of a single
902/// optimize+realize call was load-bearing. The pipelined path has
903/// a uniform `realize_many` that composes trivially — no need to
904/// re-couple them at the executor layer. This keeps the executor
905/// focused on execution and lets the optimizer evolve
906/// independently (different rule registries per call site, mid-
907/// pipeline opt+realize+opt+realize patterns, etc.).
908pub struct PipelinedExecutor;
909
910impl PipelinedExecutor {
911    /// Realize `target` and every transitive dependency. Compilation
912    /// runs in a worker thread; execution runs on the calling
913    /// thread.
914    ///
915    /// Pre-conditions:
916    ///
917    /// - Every reachable `Op::Const` node must have a corresponding
918    ///   entry in `inputs` (pre-realized Storage Arc).
919    /// - Every reachable non-`Const` node must have its
920    ///   `target_backend` set in the graph
921    ///   (`Graph::set_target_backend`).
922    /// - The op + dtype must be registered in `global_bindings()`.
923    ///
924    /// Returns the realized `Storage` Arc for `target` plus its
925    /// resolved [`Layout`]. The Layout is contiguous for kernel
926    /// outputs; for graphs whose target is a metadata-only view
927    /// op (`Op::Transpose`, `Op::Permute`, `Op::BroadcastTo`),
928    /// the returned Storage shares its bytes with an upstream
929    /// node and the Layout encodes the view's strides + offset.
930    ///
931    /// Production-correct: errors on any unmet precondition rather
932    /// than panicking.
933    pub fn realize(
934        graph: Arc<RwLock<Graph>>,
935        target: NodeId,
936        inputs: StorageCache,
937    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
938        Self::realize_inner(
939            graph,
940            target,
941            inputs,
942            OrderSource::Default,
943            SymEnv::default(),
944        )
945        .map(|(s, l, _produced)| (s, l))
946    }
947
948    /// Env-carrying sibling of [`Self::realize`]: realize `target` with a
949    /// per-pass [`SymEnv`] supplying the runtime bindings for any
950    /// `DynScalar` op params (today: `Op::WriteSlice`'s dynamic start
951    /// offset — Phase D symbolic extents). An **empty** env is
952    /// byte-identical to [`Self::realize`]; the env is consulted only by ops
953    /// that carry a `DynScalar`, so a graph with none ignores it. Uses
954    /// the default (`execution_plan`) dispatch order.
955    ///
956    /// This is the input-determined path for persistent decode (the
957    /// per-token `cached_len` write offset). The `OptimizedGraph`/route
958    /// entry points keep an empty env until the realize bridge threads
959    /// the session env through them (Phase D step 1, fuel-core).
960    pub fn realize_with_env(
961        graph: Arc<RwLock<Graph>>,
962        target: NodeId,
963        inputs: StorageCache,
964        sym_env: SymEnv,
965    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
966        Self::realize_inner(graph, target, inputs, OrderSource::Default, sym_env)
967            .map(|(s, l, _produced)| (s, l))
968    }
969
970    /// Producing sibling of [`Self::realize_with_env`]: realize `target` and
971    /// ALSO return the [`SymEnv`] of symbols BOUND BY PRODUCERS during the
972    /// pass — data-determined dynamic shapes (`Op::NonZeroIndices`'s
973    /// runtime count, etc.). The returned env is disjoint from the input
974    /// `sym_env` (which is input-determined). Empty when the graph has no
975    /// data-determined producer. This is the observation point for the
976    /// increment-2a bind seam; a downstream pass consumes these bindings
977    /// as dynamic extents.
978    pub fn realize_with_env_producing(
979        graph: Arc<RwLock<Graph>>,
980        target: NodeId,
981        inputs: StorageCache,
982        sym_env: SymEnv,
983    ) -> Result<(Arc<RwLock<Storage>>, Layout, SymEnv)> {
984        Self::realize_inner(graph, target, inputs, OrderSource::Default, sym_env)
985    }
986
987    /// PR-A3b-1 entry: realize `target` driven from `optimized`'s
988    /// in-place "plan IS the graph" form. The dispatch order is the
989    /// `OptimizedGraph`'s `extract_runs`/`lower_run` lowering (computed
990    /// after safety-copy insertion); per-node kernel resolution uses
991    /// the binding-table-lookup path (no `ExecutionPlan`, so no
992    /// route-picking — A3b-1 is branchless). The optimize-time
993    /// `generation` drives the `TopologyChanged` chunk-boundary check.
994    ///
995    /// Pre-conditions match [`Self::realize`]: every reachable kernel-bearing
996    /// node must have `target_backend` set (the bridge's
997    /// `stamp_plan_backends` does this) and a registered binding.
998    pub fn realize_with_optimized(
999        graph: Arc<RwLock<Graph>>,
1000        target: NodeId,
1001        inputs: StorageCache,
1002        optimized: &OptimizedGraph,
1003    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1004        Self::realize_inner(
1005            graph,
1006            target,
1007            inputs,
1008            OrderSource::Optimized {
1009                optimized,
1010                route: None,
1011            },
1012            SymEnv::default(),
1013        )
1014        .map(|(s, l, _produced)| (s, l))
1015    }
1016
1017    /// Env-carrying sibling of [`Self::realize_with_optimized`]: same
1018    /// optimized-graph dispatch, but with a per-pass [`SymEnv`] supplying
1019    /// the runtime bindings for `DynScalar` op params (Phase D symbolic
1020    /// extents). An empty env is byte-identical to
1021    /// [`Self::realize_with_optimized`]. The realize bridge threads its session
1022    /// env through here for persistent decode.
1023    pub fn realize_with_optimized_env(
1024        graph: Arc<RwLock<Graph>>,
1025        target: NodeId,
1026        inputs: StorageCache,
1027        optimized: &OptimizedGraph,
1028        sym_env: SymEnv,
1029    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1030        Self::realize_inner(
1031            graph,
1032            target,
1033            inputs,
1034            OrderSource::Optimized {
1035                optimized,
1036                route: None,
1037            },
1038            sym_env,
1039        )
1040        .map(|(s, l, _produced)| (s, l))
1041    }
1042
1043    /// PR-C1 entry: realize `target` driven from `optimized`'s in-place
1044    /// form **following the runtime route picker's chosen arms**. The
1045    /// dispatch order is the route-aware lowering
1046    /// ([`fuel_graph::lower_picked_route`]) over `route` — the per-branch
1047    /// arm the picker (Picker 2) selected by live telemetry. A branch
1048    /// absent from `route` defaults to arm 0, so an **empty** route is
1049    /// byte-identical to [`Self::realize_with_optimized`] (the no-pressure /
1050    /// no-telemetry contract). A branchless graph has no branches ⇒ the
1051    /// route is empty ⇒ this is exactly the arm-0 path.
1052    pub fn realize_with_optimized_route(
1053        graph: Arc<RwLock<Graph>>,
1054        target: NodeId,
1055        inputs: StorageCache,
1056        optimized: &OptimizedGraph,
1057        route: &PickedRoute,
1058    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1059        Self::realize_inner(
1060            graph,
1061            target,
1062            inputs,
1063            OrderSource::Optimized {
1064                optimized,
1065                route: Some(route),
1066            },
1067            SymEnv::default(),
1068        )
1069        .map(|(s, l, _produced)| (s, l))
1070    }
1071
1072    /// Env-carrying sibling of [`Self::realize_with_optimized_route`] — the
1073    /// route-aware lowering with a per-pass [`SymEnv`]. An empty env is
1074    /// byte-identical to [`Self::realize_with_optimized_route`].
1075    pub fn realize_with_optimized_route_env(
1076        graph: Arc<RwLock<Graph>>,
1077        target: NodeId,
1078        inputs: StorageCache,
1079        optimized: &OptimizedGraph,
1080        route: &PickedRoute,
1081        sym_env: SymEnv,
1082    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1083        Self::realize_inner(
1084            graph,
1085            target,
1086            inputs,
1087            OrderSource::Optimized {
1088                optimized,
1089                route: Some(route),
1090            },
1091            sym_env,
1092        )
1093        .map(|(s, l, _produced)| (s, l))
1094    }
1095
1096    /// Cleanup Step C/D entry: the executor OWNS `Op::Branch` arm-selection.
1097    /// Given the runtime `selector` + the live device `lookup` (built
1098    /// bridge-side from the realize `Device` + Judge oracle and passed in,
1099    /// exactly like the residency `input_residency` provider), pick one arm per
1100    /// branch HERE — at dispatch — then lower the chosen route. The per-arm
1101    /// candidates are re-enumerated from the runtime binding registry + the
1102    /// graph (Step D: no threaded `ExecutionPlan`).
1103    ///
1104    /// No `selector` (the `runtime_selector_disabled()` opt-out) or a
1105    /// branchless graph yields the arm-0 lowering, byte-identical to Phase B.
1106    ///
1107    /// **Step E Phase C, PR C1 — STREAMING.** A branched graph WITH a
1108    /// selector no longer resolves the whole route up front: it routes to the
1109    /// `OrderSource::Streaming` walk, where the compiler thread resolves
1110    /// each branch lazily as the frontier reaches it (via
1111    /// [`resolve_branch`]). C1 keeps the SAME VRAM-only selector chain — so
1112    /// the streamed route equals the one-shot `pick_route` route byte-for-byte
1113    /// — and only changes *when* a branch resolves; C2 makes that moment read
1114    /// live device load.
1115    pub fn realize_with_optimized_picking_env(
1116        graph: Arc<RwLock<Graph>>,
1117        target: NodeId,
1118        inputs: StorageCache,
1119        optimized: &OptimizedGraph,
1120        selector: Option<Arc<dyn RuntimeSelector>>,
1121        lookup: Option<BackendRuntimeLookup>,
1122        sym_env: SymEnv,
1123    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1124        match Self::streaming_pick_for(&graph, selector, lookup)? {
1125            Some(pick) => Self::realize_inner(
1126                graph,
1127                target,
1128                inputs,
1129                OrderSource::Streaming {
1130                    optimized,
1131                    pick: &pick,
1132                },
1133                sym_env,
1134            )
1135            .map(|(s, l, _produced)| (s, l)),
1136            None => Self::realize_with_optimized_env(graph, target, inputs, optimized, sym_env),
1137        }
1138    }
1139
1140    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
1141    /// §5) — cached sibling of [`Self::realize_with_optimized_picking_env`]
1142    /// for the plan-once persistent-decode caller, which holds `order_cache`
1143    /// across repeated calls over the SAME graph/roots/`optimized` (one per
1144    /// `DecodeSession`, initially empty). On a branchless graph with no
1145    /// selector pressure (the decode shape this is for), dispatches via
1146    /// [`OrderSource::Cached`] — computed once, reused thereafter, see that
1147    /// variant's doc for the safety argument. A branched graph WITH a
1148    /// resolved selector pick falls back to the uncached
1149    /// [`OrderSource::Streaming`] path unchanged (caching doesn't apply
1150    /// there; this entry point exists for the decode case, not to cover
1151    /// every caller).
1152    pub fn realize_with_optimized_picking_cached_env(
1153        graph: Arc<RwLock<Graph>>,
1154        target: NodeId,
1155        inputs: StorageCache,
1156        optimized: &OptimizedGraph,
1157        order_cache: &std::sync::OnceLock<Vec<NodeId>>,
1158        selector: Option<Arc<dyn RuntimeSelector>>,
1159        lookup: Option<BackendRuntimeLookup>,
1160        sym_env: SymEnv,
1161    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1162        match Self::streaming_pick_for(&graph, selector, lookup)? {
1163            Some(pick) => Self::realize_inner(
1164                graph,
1165                target,
1166                inputs,
1167                OrderSource::Streaming {
1168                    optimized,
1169                    pick: &pick,
1170                },
1171                sym_env,
1172            )
1173            .map(|(s, l, _produced)| (s, l)),
1174            None => Self::realize_inner(
1175                graph,
1176                target,
1177                inputs,
1178                OrderSource::Cached {
1179                    optimized,
1180                    order_cache,
1181                },
1182                sym_env,
1183            )
1184            .map(|(s, l, _produced)| (s, l)),
1185        }
1186    }
1187
1188    /// Build the [`StreamingPick`] for the executor's picking entry points —
1189    /// the streaming successor of the one-shot `pick_route_for` (which was the
1190    /// relocated body of the bridge's old `resolve_runtime_route`). Returns
1191    /// `None` (⇒ arm-0 lowering, the untouched `route: None` /
1192    /// `dispatch_order` path) when there is no `selector` (the disabled
1193    /// opt-out) or the graph has no `Op::Branch` (the branchless fast-path:
1194    /// skip the streaming machinery entirely so the common case is unchanged
1195    /// and byte-identical). Otherwise it carries the selector + lookup into
1196    /// the [`OrderSource::Streaming`] walk, which resolves each branch at the
1197    /// frontier (PR C1). The per-arm candidates are re-enumerated from the
1198    /// runtime binding registry inside the compiler thread (Step D — was the
1199    /// threaded `ExecutionPlan`).
1200    fn streaming_pick_for(
1201        graph: &Arc<RwLock<Graph>>,
1202        selector: Option<Arc<dyn RuntimeSelector>>,
1203        // Accepted for call-site parity with `pick_route` but not stored: the
1204        // streaming walk reads VRAM + load through the selector, which holds its
1205        // own `BackendRuntimeLookup`.
1206        _lookup: Option<BackendRuntimeLookup>,
1207    ) -> Result<Option<StreamingPick>> {
1208        let Some(selector) = selector else {
1209            return Ok(None);
1210        };
1211        let g = graph
1212            .read()
1213            .map_err(|_| Error::Msg("graph lock poisoned".into()).bt())?;
1214        let has_branch = (0..g.len()).any(|i| matches!(g.node(NodeId(i)).op, Op::Branch { .. }));
1215        if !has_branch {
1216            return Ok(None);
1217        }
1218        Ok(Some(StreamingPick { selector }))
1219    }
1220
1221    /// Capture a single-device CUDA decode step's kernel launches into a
1222    /// replayable [`CapturedRun`] (the CapturedRun executor build-out).
1223    ///
1224    /// Runs the graph TWICE against fixed-address buffers:
1225    ///   1. **Warm (record)**: realize normally into a fresh cache cloned
1226    ///      from `inputs`, recording every compute node's output Arc as its
1227    ///      fixed capture buffer, and synchronizing so the result is stable.
1228    ///   2. **Capture (reuse)**: re-issue the same launch sequence — each
1229    ///      node writing INTO its recorded buffer via the write-into kernel
1230    ///      path (no allocation) — inside [`CudaDevice::capture_run`],
1231    ///      producing an instantiated [`CapturedRun`].
1232    ///
1233    /// Both passes share the SAME input Arcs (cloned map, shared buffers)
1234    /// and the SAME recorded output buffers, so every device address the
1235    /// captured graph bakes in is stable for replay. To replay a later
1236    /// token: overwrite the fixed input buffers in place (H2D), call
1237    /// `run.replay(dev)`, then read `output`.
1238    ///
1239    /// Contract (surfaced as `Err`, never a panic or a mid-capture alloc):
1240    ///   - CUDA-only, single device: every compute node targets `Cuda`;
1241    ///     no cross-device `Op::Copy`/`Move` in the graph.
1242    ///   - Every compute node's op must have a write-into CUDA wrapper
1243    ///     (`op_kind_is_capture_writeinto`); an unsupported op surfaces a
1244    ///     clear capability gap rather than silently breaking the capture.
1245    ///   - Inputs must be contiguous (no auto-Contiguize alloc in capture).
1246    #[cfg(feature = "cuda")]
1247    pub fn capture_decode(
1248        graph: Arc<RwLock<Graph>>,
1249        target: NodeId,
1250        inputs: StorageCache,
1251        sym_env: SymEnv,
1252    ) -> Result<CapturedDecode> {
1253        use fuel_memory::BackendStorage;
1254
1255        // Front matter mirrors realize_inner: safety copies + frozen order.
1256        {
1257            let mut g = graph.write().map_err(|_| poisoned("graph lock"))?;
1258            let effective_roots = extend_with_side_effect_roots(&g, &[target]);
1259            insert_safety_copies(&mut g, &effective_roots);
1260        }
1261        let (compiler_work, _wait_set, seed_layouts) = {
1262            let g = graph.read().map_err(|_| poisoned("graph lock"))?;
1263            let effective_roots = extend_with_side_effect_roots(&g, &[target]);
1264            let (work, wait_set) =
1265                compiler_work_and_wait_set_for(&g, &effective_roots, &OrderSource::Default);
1266            let mut layouts: HashMap<NodeId, Layout> = HashMap::with_capacity(inputs.len());
1267            for &id in inputs.keys() {
1268                layouts.insert(id, g.layout(id));
1269            }
1270            (work, wait_set, layouts)
1271        };
1272
1273        // Compile every WorkItem once (one compiler thread) and collect them
1274        // so both passes replay the identical sequence.
1275        let (tx, rx) = channel::<Result<WorkItem>>();
1276        let graph_for_compiler = Arc::clone(&graph);
1277        let compiler = thread::spawn(move || {
1278            compiler_thread_body(graph_for_compiler, compiler_work, sym_env, tx);
1279        });
1280        let mut items: Vec<WorkItem> = Vec::new();
1281        for item in rx {
1282            items.push(item?);
1283        }
1284        compiler
1285            .join()
1286            .map_err(|_| Error::Msg("compiler thread panicked".to_string()).bt())?;
1287
1288        // CapturedRun 4b Step-4 diagnostic: name every kernel placed OFF Cuda
1289        // (an unseeded / audited-loser op that forces a cross-device copy and
1290        // blocks capture), so verification-ledger seeding can target it
1291        // precisely. Fires only when a capture is attempted AND something is
1292        // mis-placed — otherwise silent.
1293        {
1294            let off: Vec<String> = items
1295                .iter()
1296                .filter_map(|it| match &it.kind {
1297                    WorkItemKind::Kernel if it.target_backend != BackendId::Cuda => {
1298                        let desc = it
1299                            .compiled
1300                            .as_ref()
1301                            .map(|c| format!("{:?} dtypes={:?}", c.op, c.dtypes))
1302                            .unwrap_or_else(|| "?".to_string());
1303                        Some(format!(
1304                            "node {:?}: {desc} on {:?}",
1305                            it.node_id, it.target_backend
1306                        ))
1307                    }
1308                    _ => None,
1309                })
1310                .collect();
1311            if !off.is_empty() {
1312                eprintln!(
1313                    "[capture-diag] {} kernel(s) placed OFF Cuda (these block capture): {}",
1314                    off.len(),
1315                    off.join("; "),
1316                );
1317            }
1318        }
1319
1320        // Capture-safety validation — surface every gap up front, before any
1321        // launch, so a capture scope is never entered on an unsupported graph.
1322        for item in &items {
1323            match &item.kind {
1324                // Op::Move: the destructive half (releasing the source) is
1325                // driven by the realize loop's `destructive_input` cleanup,
1326                // which runs once per REALIZE call — not once per `replay()`.
1327                // A captured graph's `replay()` re-executes the same baked
1328                // launches repeatedly without re-running that surrounding
1329                // cleanup between replays, so whether a repeat-replayed Move
1330                // is even meaningful is unclear; out of scope here (4b-ζ) —
1331                // keep rejecting every Move unconditionally.
1332                WorkItemKind::Move { .. } => {
1333                    return Err(Error::Msg(format!(
1334                        "capture_decode: graph has an Op::Move at node {:?}; \
1335                         Move's destructive source-release half is driven by \
1336                         per-realize cleanup, not per-replay, so capture is \
1337                         not supported for Move (out of scope — see the \
1338                         `capture_decode` validation loop's Move arm).",
1339                        item.node_id,
1340                    ))
1341                    .bt());
1342                }
1343                // Op::Copy: a same-device CUDA→CUDA copy (e.g. an
1344                // `insert_safety_copies` snapshot) has a write-into wrapper
1345                // (`copy_from_cuda_wrapper`'s `BackendStorage::Cuda` branch,
1346                // via `CudaStorageBytes::copy_from_device`) and is
1347                // capture-safe. A copy whose `target_location` is `Cpu` or
1348                // `Vulkan` is a genuine host round-trip / cross-backend
1349                // transfer and can never be part of a CUDA graph capture —
1350                // keep rejecting those. (`gpu_id` is not cross-checked
1351                // against the capture device, matching the `Kernel` arm's
1352                // `target_backend` check just above: today's decode graphs
1353                // are single-GPU only.)
1354                WorkItemKind::Copy { target_location } => {
1355                    if !matches!(target_location, DeviceLocation::Cuda { .. }) {
1356                        return Err(Error::Msg(format!(
1357                            "capture_decode: graph has a cross-device Op::Copy at \
1358                             node {:?} (target {:?}); capture requires a \
1359                             single-device CUDA decode step — only same-device \
1360                             CUDA→CUDA copies are capture-safe.",
1361                            item.node_id, target_location,
1362                        ))
1363                        .bt());
1364                    }
1365                }
1366                WorkItemKind::Kernel => {
1367                    if item.target_backend != BackendId::Cuda {
1368                        return Err(Error::Msg(format!(
1369                            "capture_decode: kernel node {:?} targets {:?}, not Cuda",
1370                            item.node_id, item.target_backend,
1371                        ))
1372                        .bt());
1373                    }
1374                    let compiled = item.compiled.as_ref().ok_or_else(|| {
1375                        Error::Msg(format!(
1376                            "capture_decode: kernel node {:?} has no compiled op",
1377                            item.node_id,
1378                        ))
1379                        .bt()
1380                    })?;
1381                    let op = compiled.op;
1382                    if !op_kind_is_capture_writeinto(op) {
1383                        return Err(Error::Msg(format!(
1384                            "capture_decode: op {:?} (node {:?}) has no write-into CUDA \
1385                             wrapper yet — capture unsupported for this op. Extend \
1386                             op_kind_is_capture_writeinto once its write-into variant lands.",
1387                            op, item.node_id,
1388                        ))
1389                        .bt());
1390                    }
1391                    // Concat's capture-safety is conditional on arity — N==2
1392                    // has a write-into path (concat2_into), N>2 does not (its
1393                    // wrapper falls back to an allocating N-1 chain). This
1394                    // can't be expressed by op_kind_is_capture_writeinto (a
1395                    // pure OpKind -> bool predicate with no OpParams access),
1396                    // so reject N>2 explicitly here, BEFORE the warm pass —
1397                    // see op_kind_is_capture_writeinto's doc comment.
1398                    if op == OpKind::Concat {
1399                        if let OpParams::Concat {
1400                            input_dim_sizes, ..
1401                        } = &compiled.op_params
1402                        {
1403                            if input_dim_sizes.len() != 2 {
1404                                return Err(Error::Msg(format!(
1405                                    "capture_decode: Concat node {:?} has {} inputs; only \
1406                                     2-input concat (the rope rotate-half shape) has a \
1407                                     write-into CUDA path today — N-ary (N>2) concat would \
1408                                     allocate mid-capture.",
1409                                    item.node_id,
1410                                    input_dim_sizes.len(),
1411                                ))
1412                                .bt());
1413                            }
1414                        }
1415                    }
1416                }
1417                // View / adopt / slot kinds: no alloc, no launch — capture-safe.
1418                _ => {}
1419            }
1420        }
1421
1422        // ---- Pass 1: warm (record) — fixed buffers + a synchronized result --
1423        let mut persistent = PersistentOutputs::recording();
1424        let mut warm_cache: StorageCache = inputs.clone();
1425        let mut warm_layouts = seed_layouts.clone();
1426        let mut warm_syms = SymEnv::new();
1427        for item in &items {
1428            let _handle = execute_work_item(
1429                item,
1430                &mut warm_cache,
1431                &mut warm_layouts,
1432                &mut warm_syms,
1433                false,
1434                Some(&mut persistent),
1435            )
1436            .map_err(|e| with_node_location(&graph, item.node_id, e))?;
1437        }
1438        // Flush all warm launches before capture (device idle; result stable).
1439        sync_active_cuda_devices(&warm_cache)?;
1440
1441        let output = warm_cache.get(&target).cloned().ok_or_else(|| {
1442            Error::Msg(format!(
1443                "capture_decode: target {:?} not realized in warm run",
1444                target,
1445            ))
1446            .bt()
1447        })?;
1448        let output_layout = warm_layouts.get(&target).cloned().ok_or_else(|| {
1449            Error::Msg(format!("capture_decode: target {:?} has no layout", target)).bt()
1450        })?;
1451
1452        // Derive the CUDA device from the target's storage for capture_run.
1453        let device = {
1454            let guard = output.read().map_err(|_| poisoned("output storage"))?;
1455            match &guard.inner {
1456                BackendStorage::Cuda(c) => c.device().clone(),
1457                other => {
1458                    return Err(Error::Msg(format!(
1459                        "capture_decode: target {:?} is BackendStorage::{:?}, not Cuda",
1460                        target,
1461                        other.backend_id(),
1462                    ))
1463                    .bt());
1464                }
1465            }
1466        };
1467
1468        // ---- Pass 2: capture (reuse) — record the launch sequence ----------
1469        let mut reuse = PersistentOutputs::reuse(persistent.into_map());
1470        // Retain EVERY input buffer before `inputs` is consumed: the captured
1471        // graph bakes their device addresses, so they must outlive it even if
1472        // the caller doesn't independently hold them.
1473        let retained_inputs: Vec<Arc<RwLock<Storage>>> = inputs.values().cloned().collect();
1474        let mut cap_cache: StorageCache = inputs;
1475        let mut cap_layouts = seed_layouts;
1476        let mut cap_syms = SymEnv::new();
1477        let mut inner_err: Option<Error> = None;
1478        let items_ref = &items;
1479        let graph_ref = &graph;
1480        let run = device.capture_run(|_stream| {
1481            // Inside the capture scope: NO device alloc, NO host sync. Each
1482            // kernel launches on device.stream() (now capturing) and writes
1483            // into its reused fixed buffer.
1484            for item in items_ref {
1485                match execute_work_item(
1486                    item,
1487                    &mut cap_cache,
1488                    &mut cap_layouts,
1489                    &mut cap_syms,
1490                    false,
1491                    Some(&mut reuse),
1492                ) {
1493                    Ok(_handle) => {}
1494                    Err(e) => {
1495                        inner_err = Some(with_node_location(graph_ref, item.node_id, e));
1496                        break;
1497                    }
1498                }
1499            }
1500            Ok(())
1501        })?;
1502        if let Some(e) = inner_err {
1503            return Err(e);
1504        }
1505
1506        Ok(CapturedDecode {
1507            run,
1508            output,
1509            output_layout,
1510            retained_inputs,
1511            persistent: reuse.into_map(),
1512        })
1513    }
1514
1515    fn realize_inner(
1516        graph: Arc<RwLock<Graph>>,
1517        target: NodeId,
1518        inputs: StorageCache,
1519        order_source: OrderSource<'_>,
1520        sym_env: SymEnv,
1521    ) -> Result<(Arc<RwLock<Storage>>, Layout, SymEnv)> {
1522        // Auto-insert safety copies for in-place ops whose target
1523        // has additional readers in this realize set (residual-
1524        // connection cycle break). No-op when no destructive ops
1525        // are present.
1526        {
1527            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.safety_copies");
1528            let mut g = graph.write().map_err(|_| poisoned("graph lock"))?;
1529            let effective_roots = extend_with_side_effect_roots(&g, &[target]);
1530            insert_safety_copies(&mut g, &effective_roots);
1531        }
1532
1533        // Execution plan + initial layouts for the input cache
1534        // entries, computed on the calling thread to keep the
1535        // compiler thread free of graph-locking responsibilities.
1536        // Side-effect roots (Op::Print, Op::Save, etc.) are merged
1537        // into the walk so their effects fire even when not
1538        // reachable from the user's `target`. `execution_plan`
1539        // integrates `derive_ordering`'s view-aware pinning so
1540        // destructive ops run AFTER non-destructive readers of
1541        // their targets.
1542        let (compiler_work, wait_set, mut layout_cache): (
1543            CompilerWork,
1544            WaitSet,
1545            HashMap<NodeId, Layout>,
1546        ) = {
1547            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.plan_order");
1548            let g = graph.read().map_err(|_| poisoned("graph lock"))?;
1549            let effective_roots = extend_with_side_effect_roots(&g, &[target]);
1550            // PR-A3b-1: the OptimizedGraph path lowers via
1551            // `extract_runs`/`lower_run` (computed here, AFTER
1552            // `insert_safety_copies`, so the order covers freshly
1553            // inserted safety-copy nodes). The default path keeps the
1554            // pre-A3b-1 `execution_plan` walk. On a branchless graph the
1555            // two sequences are identical (A3a equivalence gate).
1556            //
1557            // PR-C1: a `Streaming` source is NOT flattened here — it is
1558            // handed to the compiler thread as a `CompilerWork::Streaming`
1559            // spec so the thread resolves each branch lazily at the
1560            // frontier (see `compiler_thread_body`).
1561            //
1562            // Step E A4b open question #4: the SAME pass also derives the
1563            // `WaitSet` from the materialized order ("event only where
1564            // waited" — see `compiler_work_and_wait_set_for`).
1565            let (work, wait_set) =
1566                compiler_work_and_wait_set_for(&g, &effective_roots, &order_source);
1567            let mut layouts = HashMap::with_capacity(inputs.len());
1568            for &id in inputs.keys() {
1569                layouts.insert(id, g.layout(id));
1570            }
1571            (work, wait_set, layouts)
1572        };
1573
1574        let (tx, rx) = channel::<Result<WorkItem>>();
1575        let graph_for_compiler = Arc::clone(&graph);
1576
1577        // Compiler thread: read graph nodes, resolve kernels,
1578        // push WorkItems. On error, push the error and bail. PR-C1: for a
1579        // `Streaming` work spec the thread also resolves each branch's arm
1580        // at the frontier (the SAME VRAM-only selector the one-shot picker
1581        // uses) before compiling that arm's runs.
1582        let compiler = {
1583            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.spawn_compiler");
1584            thread::spawn(move || {
1585                let _t = crate::compiled::op_profile::PhaseTimer::start(
1586                    "compiler_thread (runs concurrently)",
1587                );
1588                compiler_thread_body(graph_for_compiler, compiler_work, sym_env, tx);
1589            })
1590        };
1591
1592        // Executor on this thread: consume WorkItems, gather
1593        // inputs from the cache, allocate outputs, call kernels,
1594        // populate the cache. After each destructive op
1595        // (Op::Release / Op::Move) evict the destroyed input from
1596        // the cache, unless it's the realize target.
1597        //
1598        // Phase 4.3: at each dispatch-chunk boundary (target_backend
1599        // change), check the live SystemTopology generation against
1600        // the plan's stamped generation. Mismatch surfaces
1601        // `Error::TopologyChanged`; the realize layer
1602        // (`pipelined_bridge`) catches it, rebuilds the plan against
1603        // the fresh topology, and retries.
1604        let plan_generation: Option<u64> = generation_for(&order_source);
1605        let mut current_chunk_backend: Option<BackendId> = None;
1606        let mut cache: StorageCache = inputs;
1607        // Data-dependent dynamic-shapes: symbols BOUND BY PRODUCERS during
1608        // this pass (e.g. `Op::NonZeroIndices`'s runtime count). Distinct
1609        // from the compile-time `sym_env` (input-determined, moved into the
1610        // compiler thread): these become known only as ops execute. Returned
1611        // to the caller so a downstream pass can consume them.
1612        let mut produced_syms = SymEnv::new();
1613        // Step E A4b-1: per-node async-completion handles. Each producing node's
1614        // `execute_compiled` returns a `CompletionHandle` (CUDA → a recorded
1615        // `Event`; CPU/Vulkan → `Ready`) instead of being `wait`ed inline. We
1616        // store them here, wait the SOURCE producer's handle before a
1617        // cross-device copy (A4b-3, below), and drain whatever remains at
1618        // realize-end.
1619        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
1620        // Step E A4b-4: eagerly-submitted-but-not-yet-waited Vulkan batches. The
1621        // OVERLAP enabler — when we LEAVE a Vulkan chunk (or are about to block on
1622        // a CUDA copy) we `submit_pending` the open Vulkan batch so the iGPU runs
1623        // it while the executor records/dispatches the next (CUDA) chunk, instead
1624        // of letting it sit merely-recorded until realize-end (the A4b-2 behavior,
1625        // which never overlapped). Each submitted batch is tracked here and waited
1626        // at the in-flight-lifetime guard (before a Vulkan read / Vulkan-referenced
1627        // eviction / realize-end). `multi_backend` gates ALL eager submits so a
1628        // single-device realize never touches this path (byte-identical to A4b-2).
1629        let mut inflight_vulkan: Vec<InflightVulkan> = Vec::new();
1630        // Step E A4b-4: set true the first time the dispatch order transitions
1631        // between two DIFFERENT non-CPU... actually any two distinct backends — a
1632        // genuine backend switch. On a pure-CUDA or pure-Vulkan graph there is no
1633        // switch, so this stays false and the eager-submit / in-flight machinery is
1634        // unreachable (single-device byte-identical + throughput-neutral, §5).
1635        let mut multi_backend = false;
1636        let loop_total = crate::compiled::op_profile::PhaseTimer::start("realize.loop_total");
1637        loop {
1638            let t_wait =
1639                crate::compiled::op_profile::PhaseTimer::start("realize.wait_for_compiler");
1640            let Ok(item) = rx.recv() else {
1641                break;
1642            };
1643            drop(t_wait);
1644            let item = item?;
1645            // Chunk-boundary hook (target_backend change). Existing duty: the
1646            // `TopologyChanged` generation check. Step E A4b-4 adds two duties:
1647            // (1) detect a genuine backend switch → arm `multi_backend`; (2) when
1648            // LEAVING a Vulkan chunk on a multi-backend graph, eager-submit the
1649            // open Vulkan batch so the iGPU starts it concurrently with the chunk
1650            // we are about to dispatch (the overlap win).
1651            if !is_backend_neutral(&item.kind) && current_chunk_backend != Some(item.target_backend)
1652            {
1653                if let Some(plan_gen) = plan_generation {
1654                    let live = crate::dispatch::topology_generation();
1655                    if live != plan_gen {
1656                        return Err(Error::TopologyChanged {
1657                            plan_generation: plan_gen,
1658                            current_generation: live,
1659                        }
1660                        .bt());
1661                    }
1662                }
1663                let leaving = current_chunk_backend;
1664                if let Some(prev) = leaving
1665                    && prev != item.target_backend
1666                {
1667                    // A real backend switch occurred — this realize is
1668                    // genuinely multi-backend.
1669                    multi_backend = true;
1670                    // Leaving a Vulkan chunk → submit it NOW so it runs on the
1671                    // iGPU while we record/dispatch the next chunk. Whole-chunk
1672                    // granularity (the open batch IS the just-finished Vulkan
1673                    // chunk with all its intra-CB barriers) — UAF/race-safe per
1674                    // `eager_submit_all_vulkan`'s contract.
1675                    if prev == BackendId::Vulkan {
1676                        {
1677                            let _pt = crate::compiled::op_profile::PhaseTimer::start(
1678                                "realize.eager_submit_vulkan",
1679                            );
1680                            eager_submit_all_vulkan(&cache, &mut inflight_vulkan)?;
1681                        }
1682                    }
1683                }
1684                current_chunk_backend = Some(item.target_backend);
1685            }
1686            // Vulkan realizes run the async path (deferred eviction, size-based eager
1687            // submit) even on a single device: ordering between batches is structural
1688            // (inter-batch barrier + epoch-gated buffer reuse), not a host wait.
1689            if item.target_backend == BackendId::Vulkan && matches!(item.kind, WorkItemKind::Kernel)
1690            {
1691                multi_backend = true;
1692            }
1693            // Same-device cross-chunk RAW/WAR safety between Vulkan batches (the old
1694            // "Invariant E": wait every in-flight Vulkan batch on the HOST before
1695            // recording a new Vulkan op) is now structural: the Vulkan recorder
1696            // starts every batch with a memory barrier whose first scope covers all
1697            // earlier submissions on the queue (`Recorder::record_inter_batch_barrier`),
1698            // so a later batch cannot read or overwrite what an earlier in-flight
1699            // one is still using. The host therefore keeps recording while the
1700            // GPU runs the batches already submitted; waits remain only where the
1701            // host needs a result (D2H reads), before freeing a buffer, and at
1702            // realize-end.
1703            // Step E A4b-3 + A4b-4: the cross-device residency boundary.
1704            if matches!(
1705                item.kind,
1706                WorkItemKind::Copy { .. } | WorkItemKind::Move { .. }
1707            ) {
1708                // A4b-4: before we (possibly) block the host on the CUDA producer,
1709                // eager-submit any open Vulkan chunk so the iGPU runs it WHILE we
1710                // wait on CUDA (the §5.1 ordering — submit Vulkan *before* draining
1711                // CUDA). Cheap + safe; gated to multi-backend (no-op single-device).
1712                if multi_backend {
1713                    {
1714                        let _pt = crate::compiled::op_profile::PhaseTimer::start(
1715                            "realize.eager_submit_vulkan",
1716                        );
1717                        eager_submit_all_vulkan(&cache, &mut inflight_vulkan)?;
1718                    }
1719                }
1720                if let Some(&producer) = item.inputs.first() {
1721                    // A4b-4: a VULKAN-source D2H must read COMPLETED data, and the
1722                    // Vulkan download path only flushes the OPEN batch (not our
1723                    // in-flight ones) — so wait the in-flight Vulkan batches here.
1724                    // For a CUDA/CPU source we do NOT wait Vulkan (the copy reads no
1725                    // Vulkan buffer); waiting it would needlessly serialize the
1726                    // independent Vulkan sub-DAG and kill the overlap. The Vulkan
1727                    // work that was eager-submitted at the chunk boundary keeps
1728                    // running concurrently until ITS result is the one being copied.
1729                    if multi_backend && copy_source_is_vulkan(&cache, producer)? {
1730                        {
1731                            let _pt = crate::compiled::op_profile::PhaseTimer::start(
1732                                "realize.drain_inflight_vulkan",
1733                            );
1734                            drain_inflight_vulkan(&mut inflight_vulkan)?;
1735                        }
1736                    }
1737                    // Step E A4b-3: FINER CUDA source-drain — wait ONLY the source
1738                    // producer's recorded event (not the whole source device), so
1739                    // the OTHER sub-DAG's independent in-flight CUDA work keeps
1740                    // running. No-op for a Vulkan/CPU producer (no CUDA handle).
1741                    wait_producer_handle(&mut handles, producer)?;
1742                }
1743            }
1744            let t_exec =
1745                crate::compiled::op_profile::PhaseTimer::start(work_item_kind_name(&item.kind));
1746            let handle = execute_work_item(
1747                &item,
1748                &mut cache,
1749                &mut layout_cache,
1750                &mut produced_syms,
1751                will_be_waited(&wait_set, item.node_id),
1752                // No persistent-output mode on the standard realize paths —
1753                // fresh alloc per node, byte-identical to pre-CapturedRun.
1754                None,
1755            )
1756            .map_err(|e| with_node_location(&graph, item.node_id, e))?;
1757            drop(t_exec);
1758            store_handle(&mut handles, item.node_id, handle);
1759            if let Some(d_idx) = item.destructive_input
1760                && let Some(&destroyed) = item.inputs.get(d_idx)
1761                && destroyed != target
1762            {
1763                // Step E A2.1 (in-flight-batch DATA-BUFFER lifetime — the
1764                // UAF guard, now DEFERRED-DELETION instead of a drain). A
1765                // `SubmittedBatch` owns its CB/descriptors/transients but
1766                // NOT the DATA buffers it reads (those live here in the
1767                // cache); recycling a data buffer an in-flight/open CB still
1768                // reads is a use-after-free. PRE-A2.1 we host-blocked here —
1769                // `drain_inflight_vulkan` (wait every in-flight batch) +
1770                // `force_flush` (submit+wait the open batch) — which stalled
1771                // the iGPU work we were overlapping with CUDA at EVERY such
1772                // eviction. A2.1 instead RETAINS the evicted buffer until the
1773                // reader fences signal: it eager-submits the open batch (no
1774                // wait → it becomes a fenced in-flight batch) and moves a
1775                // refcount clone of the buffer into every in-flight batch, so
1776                // the buffer frees POST-fence on each batch's `Drop`
1777                // (follow-on #2) with NO host block. Conservative over all
1778                // batches (no cheap buffer→batch map — the same reason the old
1779                // drain waited all of them). CUDA eviction is stream-ordered-
1780                // safe via A3. Single-device (multi_backend == false) keeps the
1781                // pre-A2.1 blocking force_flush of the OPEN batch (the else
1782                // branch) — byte-identical + UAF-safe there; the deferred path is
1783                // unsafe single-device (no eager-submit/in-flight tracking, and the
1784                // cross-batch RAW guard at :832 doesn't run — see
1785                // force_flush_vulkan's doc).
1786                let _t =
1787                    crate::compiled::op_profile::PhaseTimer::start("realize.evict_destroyed_input");
1788                if multi_backend {
1789                    defer_evicted_vulkan_buffer(&cache, destroyed, &mut inflight_vulkan)?;
1790                } else if let Some(d_arc) = cache.get(&destroyed) {
1791                    let _f = crate::compiled::op_profile::PhaseTimer::start(
1792                        "realize.evict_force_flush_vulkan",
1793                    );
1794                    force_flush_vulkan(d_arc)?;
1795                }
1796                cache.remove(&destroyed);
1797                layout_cache.remove(&destroyed);
1798                // Drop the evicted node's CUDA handle (if still present)
1799                // so the realize-end drain's empty-map assert stays
1800                // meaningful. The free itself is stream-ordered-safe (A3).
1801                handles.remove(&destroyed);
1802            }
1803        }
1804
1805        drop(loop_total);
1806        {
1807            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.join_compiler");
1808            compiler
1809                .join()
1810                .map_err(|_| Error::Msg("compiler thread panicked".to_string()).bt())?;
1811        }
1812
1813        // Step E A4b-1: drain every outstanding async handle before the result is
1814        // read / the cache drops (freeing intermediates). For CUDA this waits the
1815        // recorded events (one stream/device ⇒ waiting the latest drains all prior
1816        // stream work too; see `drain_handles`).
1817        let post_loop = crate::compiled::op_profile::PhaseTimer::start("realize.post_loop_drains");
1818        drain_handles(&mut handles)?;
1819        // Step E A4b open question #4 — "event only where waited": most CUDA
1820        // nodes in this realize never got an Event (elided per the `WaitSet`),
1821        // so `drain_handles` above only retired the (typically few) tracked
1822        // handles. This blanket per-device `cuStreamSynchronize` flushes the
1823        // elided work too — safe + sufficient because of single-stream-per-
1824        // device ordering (see `sync_active_cuda_devices`'s doc).
1825        sync_active_cuda_devices(&cache)?;
1826        // Step E A4b-4: wait every eagerly-submitted (in-flight) Vulkan batch
1827        // before the cache drops, freeing the data buffers their CBs read. Empty
1828        // on a single-device realize (nothing was eager-submitted).
1829        {
1830            let _pt =
1831                crate::compiled::op_profile::PhaseTimer::start("realize.drain_inflight_vulkan");
1832            drain_inflight_vulkan(&mut inflight_vulkan)?;
1833        }
1834        // Step E A4b-2: drain all deferred Vulkan work before reading/returning
1835        // the result (and before the cache drops, freeing buffers). The A2
1836        // submit+wait is now SPLIT — `drain_vulkan_pending` submits the open
1837        // batch then waits it via a `VulkanCompletion` handle. Byte-identical to
1838        // A2 for pure-Vulkan (one submission at realize-end, just split).
1839        drain_vulkan_pending(&cache)?;
1840        debug_assert!(
1841            inflight_vulkan.is_empty(),
1842            "A4b-4: in-flight Vulkan batch list must be empty after realize-end drain",
1843        );
1844
1845        drop(post_loop);
1846        let storage = cache.remove(&target).ok_or_else(|| {
1847            Error::Msg(format!(
1848                "PipelinedExecutor::realize: target slot {:?} not populated after execution",
1849                target
1850            ))
1851            .bt()
1852        })?;
1853        let layout = layout_cache.remove(&target).ok_or_else(|| {
1854            Error::Msg(format!(
1855                "PipelinedExecutor::realize: target layout {:?} not populated after execution",
1856                target
1857            ))
1858            .bt()
1859        })?;
1860        {
1861            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.drop_cache");
1862            drop(cache);
1863            drop(handles);
1864            drop(layout_cache);
1865        }
1866        Ok((storage, layout, produced_syms))
1867    }
1868
1869    /// Realize multiple targets in one walk. Each target's transitive
1870    /// dependency set is collapsed into a single execution plan
1871    /// (via [`execution_plan`]); shared subgraphs are evaluated
1872    /// once. Returns a `Vec<(Storage, Layout)>` whose order matches
1873    /// `targets`.
1874    ///
1875    /// This is Phase A of Phase 7.6 step 9c — feature-parity with the
1876    /// legacy `GraphExecutor::realize_many_f32`. Multi-session
1877    /// migration target ([memory: project_phase_7_6_step_9c_parity_audit.md]).
1878    ///
1879    /// Pre-conditions: every reachable `Op::Const` must be in
1880    /// `inputs`; every reachable non-`Const` must have its
1881    /// `target_backend` set; the op + dtype must be registered in
1882    /// `global_bindings()`. Same as single-target [`Self::realize`].
1883    pub fn realize_many(
1884        graph: Arc<RwLock<Graph>>,
1885        targets: &[NodeId],
1886        inputs: StorageCache,
1887    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
1888        Self::realize_many_inner(
1889            graph,
1890            targets,
1891            inputs,
1892            OrderSource::Default,
1893            SymEnv::default(),
1894        )
1895    }
1896
1897    /// Multi-target PR-A3b-1 entry — the `realize_many` sibling of
1898    /// [`Self::realize_with_optimized`]. Drives the executor from the
1899    /// `OptimizedGraph`'s run lowering via the binding-table-lookup
1900    /// path, with the optimize-time `generation` keying the
1901    /// `TopologyChanged` chunk-boundary check.
1902    pub fn realize_many_with_optimized(
1903        graph: Arc<RwLock<Graph>>,
1904        targets: &[NodeId],
1905        inputs: StorageCache,
1906        optimized: &OptimizedGraph,
1907    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
1908        Self::realize_many_inner(
1909            graph,
1910            targets,
1911            inputs,
1912            OrderSource::Optimized {
1913                optimized,
1914                route: None,
1915            },
1916            SymEnv::default(),
1917        )
1918    }
1919
1920    /// Env-carrying sibling of [`Self::realize_many_with_optimized`] (Phase D
1921    /// symbolic extents). An empty env is byte-identical to it.
1922    pub fn realize_many_with_optimized_env(
1923        graph: Arc<RwLock<Graph>>,
1924        targets: &[NodeId],
1925        inputs: StorageCache,
1926        optimized: &OptimizedGraph,
1927        sym_env: SymEnv,
1928    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
1929        Self::realize_many_inner(
1930            graph,
1931            targets,
1932            inputs,
1933            OrderSource::Optimized {
1934                optimized,
1935                route: None,
1936            },
1937            sym_env,
1938        )
1939    }
1940
1941    /// Multi-target PR-C1 entry — the `realize_many` sibling of
1942    /// [`Self::realize_with_optimized_route`]. Lowers each target's runs
1943    /// following the picker's chosen arms via
1944    /// [`fuel_graph::lower_picked_route`].
1945    pub fn realize_many_with_optimized_route(
1946        graph: Arc<RwLock<Graph>>,
1947        targets: &[NodeId],
1948        inputs: StorageCache,
1949        optimized: &OptimizedGraph,
1950        route: &PickedRoute,
1951    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
1952        Self::realize_many_inner(
1953            graph,
1954            targets,
1955            inputs,
1956            OrderSource::Optimized {
1957                optimized,
1958                route: Some(route),
1959            },
1960            SymEnv::default(),
1961        )
1962    }
1963
1964    /// Env-carrying sibling of [`Self::realize_many_with_optimized_route`]
1965    /// (Phase D symbolic extents). An empty env is byte-identical to it.
1966    pub fn realize_many_with_optimized_route_env(
1967        graph: Arc<RwLock<Graph>>,
1968        targets: &[NodeId],
1969        inputs: StorageCache,
1970        optimized: &OptimizedGraph,
1971        route: &PickedRoute,
1972        sym_env: SymEnv,
1973    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
1974        Self::realize_many_inner(
1975            graph,
1976            targets,
1977            inputs,
1978            OrderSource::Optimized {
1979                optimized,
1980                route: Some(route),
1981            },
1982            sym_env,
1983        )
1984    }
1985
1986    /// Multi-target sibling of [`Self::realize_with_optimized_picking_env`] —
1987    /// the executor resolves one arm per `Op::Branch` (cleanup Step C/D) over
1988    /// the effective targets. PR C1: a branched graph routes to the
1989    /// `OrderSource::Streaming` walk (lazy per-branch resolution at the
1990    /// frontier); branchless / no-selector falls to the untouched arm-0 path.
1991    pub fn realize_many_with_optimized_picking_env(
1992        graph: Arc<RwLock<Graph>>,
1993        targets: &[NodeId],
1994        inputs: StorageCache,
1995        optimized: &OptimizedGraph,
1996        selector: Option<Arc<dyn RuntimeSelector>>,
1997        lookup: Option<BackendRuntimeLookup>,
1998        sym_env: SymEnv,
1999    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2000        match Self::streaming_pick_for(&graph, selector, lookup)? {
2001            Some(pick) => Self::realize_many_inner(
2002                graph,
2003                targets,
2004                inputs,
2005                OrderSource::Streaming {
2006                    optimized,
2007                    pick: &pick,
2008                },
2009                sym_env,
2010            ),
2011            None => {
2012                Self::realize_many_with_optimized_env(graph, targets, inputs, optimized, sym_env)
2013            }
2014        }
2015    }
2016
2017    fn realize_many_inner(
2018        graph: Arc<RwLock<Graph>>,
2019        targets: &[NodeId],
2020        inputs: StorageCache,
2021        order_source: OrderSource<'_>,
2022        sym_env: SymEnv,
2023    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2024        if targets.is_empty() {
2025            return Ok(Vec::new());
2026        }
2027
2028        // Auto-insert safety copies for in-place ops whose target
2029        // has additional readers in this realize set (residual-
2030        // connection cycle break). No-op when no destructive ops
2031        // are present.
2032        {
2033            let mut g = graph.write().map_err(|_| poisoned("graph lock"))?;
2034            let effective_roots = extend_with_side_effect_roots(&g, targets);
2035            insert_safety_copies(&mut g, &effective_roots);
2036        }
2037
2038        // Execution plan covering every target's dependency set +
2039        // initial layouts for the input cache entries. Side-effect
2040        // roots merge in so their effects fire even when not
2041        // reachable from any target. `execution_plan` integrates
2042        // `derive_ordering`'s view-aware pinning so destructive ops
2043        // run AFTER non-destructive readers of their targets.
2044        let (compiler_work, wait_set, mut layout_cache): (
2045            CompilerWork,
2046            WaitSet,
2047            HashMap<NodeId, Layout>,
2048        ) = {
2049            let g = graph.read().map_err(|_| poisoned("graph lock"))?;
2050            let effective_roots = extend_with_side_effect_roots(&g, targets);
2051            // PR-A3b-1: derive from the OptimizedGraph's run lowering
2052            // when present (post-safety-copies); else the legacy
2053            // `execution_plan` walk. Identical on branchless graphs.
2054            //
2055            // PR-C1: a `Streaming` source is handed to the compiler thread
2056            // unflattened (resolves branches at the frontier).
2057            //
2058            // Step E A4b open question #4: also derives the `WaitSet`
2059            // ("event only where waited") from the same materialized order.
2060            let (work, wait_set) =
2061                compiler_work_and_wait_set_for(&g, &effective_roots, &order_source);
2062            let mut layouts = HashMap::with_capacity(inputs.len());
2063            for &id in inputs.keys() {
2064                layouts.insert(id, g.layout(id));
2065            }
2066            (work, wait_set, layouts)
2067        };
2068
2069        // Caller's target set — used to gate destructive-input
2070        // eviction so we don't drop a tensor the caller asked for.
2071        let target_set: std::collections::HashSet<NodeId> = targets.iter().copied().collect();
2072
2073        let (tx, rx) = channel::<Result<WorkItem>>();
2074        let graph_for_compiler = Arc::clone(&graph);
2075
2076        let compiler = thread::spawn(move || {
2077            compiler_thread_body(graph_for_compiler, compiler_work, sym_env, tx);
2078        });
2079
2080        // Phase 4.3: per-chunk SystemTopology generation check (see
2081        // realize_inner for the rationale). PR-A3b-1: the OptimizedGraph
2082        // path supplies its own optimize-time generation.
2083        let plan_generation: Option<u64> = generation_for(&order_source);
2084        let mut current_chunk_backend: Option<BackendId> = None;
2085        let mut cache: StorageCache = inputs;
2086        // Data-dependent dynamic-shapes producer-bound symbols (see
2087        // `realize_inner`). `realize_many` does not expose them today; the
2088        // env is dropped at pass end (producers still publish, keeping the
2089        // seam uniform across both realize loops).
2090        let mut produced_syms = SymEnv::new();
2091        // Step E A4b-1/A4b-3: per-node async-completion handles (see realize_inner
2092        // for the full rationale). Map drained at realize-end; the cross-device
2093        // copy waits the SOURCE producer's handle (A4b-3).
2094        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
2095        // Step E A4b-4: eagerly-submitted in-flight Vulkan batches + the
2096        // multi-backend gate. See realize_inner for the full rationale — this is
2097        // the identical eager-submit / in-flight-lifetime machinery applied to the
2098        // multi-target walk. `multi_backend` arms on a genuine backend switch and
2099        // gates every eager submit, so a single-device realize_many is
2100        // byte-identical to A4b-2.
2101        let mut inflight_vulkan: Vec<InflightVulkan> = Vec::new();
2102        let mut multi_backend = false;
2103        for item in rx {
2104            let item = item?;
2105            // Chunk-boundary hook: TopologyChanged check + (A4b-4) backend-switch
2106            // detection + eager-submit-on-leaving-a-Vulkan-chunk.
2107            if !is_backend_neutral(&item.kind) && current_chunk_backend != Some(item.target_backend)
2108            {
2109                if let Some(plan_gen) = plan_generation {
2110                    let live = crate::dispatch::topology_generation();
2111                    if live != plan_gen {
2112                        return Err(Error::TopologyChanged {
2113                            plan_generation: plan_gen,
2114                            current_generation: live,
2115                        }
2116                        .bt());
2117                    }
2118                }
2119                let leaving = current_chunk_backend;
2120                if let Some(prev) = leaving
2121                    && prev != item.target_backend
2122                {
2123                    multi_backend = true;
2124                    if prev == BackendId::Vulkan {
2125                        eager_submit_all_vulkan(&cache, &mut inflight_vulkan)?;
2126                    }
2127                }
2128                current_chunk_backend = Some(item.target_backend);
2129            }
2130            // Vulkan realizes run the async path (deferred eviction, size-based eager
2131            // submit) even on a single device: ordering between batches is structural
2132            // (inter-batch barrier + epoch-gated buffer reuse), not a host wait.
2133            if item.target_backend == BackendId::Vulkan && matches!(item.kind, WorkItemKind::Kernel)
2134            {
2135                multi_backend = true;
2136            }
2137            // Inter-batch Vulkan ordering is structural (see realize_inner): no host
2138            // wait before recording a new Vulkan op.
2139            // Step E A4b-3 + A4b-4: cross-device residency boundary. See
2140            // realize_inner for the full rationale.
2141            if matches!(
2142                item.kind,
2143                WorkItemKind::Copy { .. } | WorkItemKind::Move { .. }
2144            ) {
2145                // A4b-4: submit any open Vulkan chunk so the iGPU runs while the
2146                // host (possibly) waits on the CUDA producer.
2147                if multi_backend {
2148                    eager_submit_all_vulkan(&cache, &mut inflight_vulkan)?;
2149                }
2150                if let Some(&producer) = item.inputs.first() {
2151                    // A4b-4: wait in-flight Vulkan ONLY for a Vulkan-source D2H
2152                    // (reads completed data; download flushes only the OPEN batch).
2153                    // A CUDA/CPU source does NOT wait Vulkan (preserves overlap).
2154                    if multi_backend && copy_source_is_vulkan(&cache, producer)? {
2155                        drain_inflight_vulkan(&mut inflight_vulkan)?;
2156                    }
2157                    // Step E A4b-3: finer CUDA source-drain — wait ONLY the producer.
2158                    wait_producer_handle(&mut handles, producer)?;
2159                }
2160            }
2161            let handle = execute_work_item(
2162                &item,
2163                &mut cache,
2164                &mut layout_cache,
2165                &mut produced_syms,
2166                will_be_waited(&wait_set, item.node_id),
2167                // No persistent-output mode on the standard realize paths —
2168                // fresh alloc per node, byte-identical to pre-CapturedRun.
2169                None,
2170            )
2171            .map_err(|e| with_node_location(&graph, item.node_id, e))?;
2172            store_handle(&mut handles, item.node_id, handle);
2173            if let Some(d_idx) = item.destructive_input
2174                && let Some(&destroyed) = item.inputs.get(d_idx)
2175                && !target_set.contains(&destroyed)
2176            {
2177                // Step E A2.1 (in-flight DATA-BUFFER lifetime — UAF guard,
2178                // now DEFERRED-DELETION instead of a drain): retain the
2179                // evicted buffer until the reader fences signal — eager-
2180                // submit the open batch (no wait) + move a refcount clone of
2181                // the buffer into every in-flight batch, freeing it post-
2182                // fence on each batch's `Drop` with NO host block. Replaces
2183                // the pre-A2.1 `drain_inflight_vulkan` + open-batch
2184                // `force_flush` (two host-blocking fence waits). See
2185                // `defer_evicted_vulkan_buffer` / realize_inner for the
2186                // UAF/leak argument. CUDA eviction is A3 stream-safe.
2187                // Single-device (multi_backend == false) keeps the pre-A2.1
2188                // blocking force_flush of the OPEN batch (the else branch) —
2189                // byte-identical + UAF-safe; the deferred path is unsafe there
2190                // (see force_flush_vulkan's doc).
2191                if multi_backend {
2192                    defer_evicted_vulkan_buffer(&cache, destroyed, &mut inflight_vulkan)?;
2193                } else if let Some(d_arc) = cache.get(&destroyed) {
2194                    force_flush_vulkan(d_arc)?;
2195                }
2196                cache.remove(&destroyed);
2197                layout_cache.remove(&destroyed);
2198                // CUDA eviction is stream-ordered-safe (A3); drop the
2199                // handle so the realize-end empty-map assert stays valid.
2200                handles.remove(&destroyed);
2201            }
2202        }
2203
2204        compiler
2205            .join()
2206            .map_err(|_| Error::Msg("compiler thread panicked".to_string()).bt())?;
2207
2208        // Step E A4b-1: drain every outstanding async handle (CUDA events) before
2209        // results are read / the cache drops.
2210        drain_handles(&mut handles)?;
2211        // Step E A4b open question #4: blanket per-device stream sync for the
2212        // elided nodes `drain_handles` never tracked — see `realize_inner`'s
2213        // identical comment / `sync_active_cuda_devices`'s doc for the argument.
2214        sync_active_cuda_devices(&cache)?;
2215        // Step E A4b-4: wait every eagerly-submitted in-flight Vulkan batch before
2216        // the cache drops. Empty on a single-device realize.
2217        drain_inflight_vulkan(&mut inflight_vulkan)?;
2218        // Step E A4b-2: drain all deferred Vulkan work — submit the open batch
2219        // then wait it via a `VulkanCompletion` handle (the A2 submit+wait, split;
2220        // byte-identical for pure-Vulkan — one submission at realize-end).
2221        drain_vulkan_pending(&cache)?;
2222        debug_assert!(
2223            inflight_vulkan.is_empty(),
2224            "A4b-4: in-flight Vulkan batch list must be empty after realize-end drain",
2225        );
2226
2227        // Verify every target was realized + collect outputs in
2228        // target order. We don't `remove` from the cache because the
2229        // same NodeId can appear twice in `targets` (caller wants the
2230        // same storage twice) — clone the Arc instead.
2231        let mut out = Vec::with_capacity(targets.len());
2232        for &target in targets {
2233            let storage = cache.get(&target).cloned().ok_or_else(|| {
2234                Error::Msg(format!(
2235                    "PipelinedExecutor::realize_many: target {:?} not populated after execution",
2236                    target
2237                ))
2238                .bt()
2239            })?;
2240            let layout = layout_cache.get(&target).cloned().ok_or_else(|| {
2241                Error::Msg(format!(
2242                    "PipelinedExecutor::realize_many: target layout {:?} not populated after execution",
2243                    target
2244                ))
2245                .bt()
2246            })?;
2247            out.push((storage, layout));
2248        }
2249        Ok(out)
2250    }
2251}
2252
2253/// Resolve the executor's dispatch order from the configured
2254/// [`OrderSource`]. PR-A3b-1: `Optimized` lowers the in-place
2255/// "plan IS the graph" form via `extract_runs`/`lower_run`; `Default`
2256/// keeps the pre-A3b-1 `execution_plan` walk. Both produce the same
2257/// `NodeId` sequence on a branchless graph (A3a equivalence gate),
2258/// computed here AFTER safety-copy insertion so either path covers
2259/// any freshly inserted copies.
2260fn order_for(
2261    graph: &Graph,
2262    effective_roots: &[NodeId],
2263    order_source: &OrderSource<'_>,
2264) -> Vec<NodeId> {
2265    match order_source {
2266        OrderSource::Default => execution_plan(graph, effective_roots),
2267        // The streaming walk is driven in the compiler thread (it
2268        // interleaves arm resolution with compilation), so `order_for`
2269        // never flattens it on the production path. This arm exists only
2270        // for match totality / non-pipelined callers: it collects the SAME
2271        // lazily-resolved order eagerly (the streaming walk with the same
2272        // `resolve_branch` over the threaded selector), which equals the
2273        // one-shot `lower_picked_route(pick_route(..))` order.
2274        OrderSource::Streaming {
2275            optimized: _optimized,
2276            pick,
2277        } => {
2278            let bindings = global_bindings();
2279            fuel_graph::lower_picked_route_streaming(graph, effective_roots, |branch| {
2280                resolve_branch(graph, branch, &bindings, pick.selector.as_ref())
2281            })
2282        }
2283        OrderSource::Optimized { optimized, route } => {
2284            // Lower the runs over the *effective* roots (user targets +
2285            // any spliced/side-effect roots) so the order matches the
2286            // walk's reachable set rather than only the optimize-time
2287            // roots. On a branchless graph this is the same concatenated
2288            // `lower_run` sequence the OptimizedGraph reports.
2289            //
2290            // PR-C1: when the picker supplied a route, follow the chosen
2291            // arms (`lower_picked_route`); otherwise the arm-0 lowering
2292            // (`OptimizedGraph::dispatch_order`). An empty route is
2293            // byte-identical to arm-0, so the two paths agree whenever
2294            // the picker chose arm-0 everywhere (the no-pressure case).
2295            match route {
2296                Some(route) => fuel_graph::lower_picked_route(graph, effective_roots, route),
2297                None => {
2298                    // A transient view built solely to call `dispatch_order`;
2299                    // it does no planning, so it carries no placements. The
2300                    // real optimization's map lives on `optimized`.
2301                    let view = OptimizedGraph {
2302                        roots: effective_roots.to_vec(),
2303                        generation: optimized.generation,
2304                        placements: None,
2305                        eviction: None,
2306                    };
2307                    view.dispatch_order(graph)
2308                }
2309            }
2310        }
2311        // Resolved by `compiler_work_and_wait_set_for` before delegating
2312        // here (the whole point of `Cached` is to skip this computation
2313        // on a hit) — never reached. Kept exhaustive rather than wildcarded
2314        // so a future `OrderSource` variant can't silently fall through.
2315        OrderSource::Cached { .. } => {
2316            unreachable!("OrderSource::Cached is resolved before order_for is called")
2317        }
2318    }
2319}
2320
2321/// Step E A4b open question #4 — "event only where waited". The producer
2322/// [`NodeId`]s that some later `Op::Copy`/`Op::Move` node in `order` will
2323/// `wait_producer_handle` on (the executor's cross-device residency
2324/// boundary — see `wait_producer_handle`, whose `item.inputs.first()` read
2325/// this mirrors exactly). A CUDA node whose id is absent from the returned
2326/// set has NO mid-walk reader: same-device consumers are correct via stream
2327/// ordering alone (they never `wait`), and nothing touches its handle before
2328/// the realize-end drain, so [`crate::compiled::execute_compiled_with_wait_hint`]
2329/// can skip recording an `Event` for it entirely.
2330///
2331/// Requires a materialized `order` (works for [`OrderSource::Default`] /
2332/// [`OrderSource::Optimized`], whose [`CompilerWork::Order`] is a frozen
2333/// `Vec<NodeId>` computed up front) — see
2334/// [`compiler_work_and_wait_set_for`] for the [`OrderSource::Streaming`]
2335/// fallback.
2336fn build_wait_set(graph: &Graph, order: &[NodeId]) -> HashSet<NodeId> {
2337    let mut set = HashSet::new();
2338    for &id in order {
2339        let node = graph.node(id);
2340        if matches!(node.op, Op::Copy { .. } | Op::Move { .. })
2341            && let Some(&producer) = node.inputs.first()
2342        {
2343            set.insert(producer);
2344        }
2345    }
2346    set
2347}
2348
2349/// Step E A4b open question #4: the executor's per-realize wait-set.
2350/// `None` is the CONSERVATIVE fallback — every CUDA node still gets an Event
2351/// (today's pre-elision behavior, byte-identical). `Some(set)` restricts
2352/// event production to `set`'s members ([`build_wait_set`]'s output);
2353/// everything else gets `CompletionHandle::Ready` with no Event recorded.
2354type WaitSet = Option<HashSet<NodeId>>;
2355
2356/// Whether `node_id`'s completion handle must be individually observable
2357/// (i.e. `execute_compiled_with_wait_hint`'s `will_be_waited`). `None` (the
2358/// [`OrderSource::Streaming`] fallback — never elides) is always `true`.
2359#[inline]
2360fn will_be_waited(wait_set: &WaitSet, node_id: NodeId) -> bool {
2361    match wait_set {
2362        None => true,
2363        Some(set) => set.contains(&node_id),
2364    }
2365}
2366
2367/// Build the [`CompilerWork`] the compiler thread walks for the configured
2368/// [`OrderSource`], plus the [`WaitSet`] "event only where waited" (open
2369/// question #4) consults. The non-streaming sources flatten up front via
2370/// [`order_for`] (unchanged) and the SAME materialized order feeds
2371/// [`build_wait_set`], so the pre-scan and the dispatch order never
2372/// disagree. [`OrderSource::Streaming`] is handed to the compiler thread as
2373/// a [`CompilerWork::Streaming`] spec — NOT flattened here — so the thread
2374/// resolves branches lazily at the frontier (Step E Phase C, PR C1); the lazy
2375/// order can't be pre-scanned without eagerly resolving it (which would
2376/// defeat the point of streaming), so it falls back to the conservative
2377/// `WaitSet::None` — event every node, unchanged behavior. Holds the graph
2378/// read-lock only for the flattening branches; the streaming branch defers
2379/// the lock to the compiler thread.
2380fn compiler_work_and_wait_set_for(
2381    graph: &Graph,
2382    effective_roots: &[NodeId],
2383    order_source: &OrderSource<'_>,
2384) -> (CompilerWork, WaitSet) {
2385    match order_source {
2386        OrderSource::Streaming { pick, .. } => (
2387            CompilerWork::Streaming {
2388                roots: effective_roots.to_vec(),
2389                pick: (*pick).clone(),
2390            },
2391            None,
2392        ),
2393        OrderSource::Cached {
2394            optimized,
2395            order_cache,
2396        } => {
2397            let order = order_cache.get_or_init(|| {
2398                order_for(
2399                    graph,
2400                    effective_roots,
2401                    &OrderSource::Optimized {
2402                        optimized,
2403                        route: None,
2404                    },
2405                )
2406            });
2407            let wait_set = build_wait_set(graph, order);
2408            (CompilerWork::Order(order.clone()), Some(wait_set))
2409        }
2410        other => {
2411            let order = order_for(graph, effective_roots, other);
2412            let wait_set = build_wait_set(graph, &order);
2413            (CompilerWork::Order(order), Some(wait_set))
2414        }
2415    }
2416}
2417
2418/// The topology generation that keys the executor's `TopologyChanged`
2419/// chunk-boundary check. Uses the `OptimizedGraph`'s optimize-time
2420/// generation (PR-A3b-1 path). `None` ⇒ no check (the plain
2421/// `realize`/`realize_many` entries).
2422fn generation_for(order_source: &OrderSource<'_>) -> Option<u64> {
2423    match order_source {
2424        OrderSource::Optimized { optimized, .. } => Some(optimized.generation),
2425        OrderSource::Streaming { optimized, .. } => Some(optimized.generation),
2426        OrderSource::Cached { optimized, .. } => Some(optimized.generation),
2427        OrderSource::Default => None,
2428    }
2429}
2430
2431/// What the compiler thread walks: either a pre-flattened dispatch
2432/// `Order` (the `Default` / `Optimized` paths — unchanged), or a
2433/// `Streaming` spec the thread resolves branch-by-branch at the frontier
2434/// (Step E Phase C, PR C1).
2435enum CompilerWork {
2436    /// A frozen topological order (computed up front by `order_for`). The
2437    /// compiler thread compiles each node and sends it in turn.
2438    Order(Vec<NodeId>),
2439    /// The streaming run-walk: the compiler thread drives
2440    /// [`fuel_graph::walk_picked_route_streaming`] over `roots`, resolving
2441    /// each `Op::Branch` lazily via [`resolve_branch`] as the frontier
2442    /// reaches its arm-entry, and compiling + sending only the chosen
2443    /// arm's runs. `roots` are the effective roots (same set `order_for`
2444    /// lowers over). Byte-identical to `Order(lower_picked_route(
2445    /// pick_route(..)))` in C1 (same VRAM-only selector).
2446    Streaming {
2447        roots: Vec<NodeId>,
2448        pick: StreamingPick,
2449    },
2450}
2451
2452/// Compiler thread body. Holds the graph read-lock + a thread-local
2453/// layout cache and emits `WorkItem`s in topological order. For
2454/// [`CompilerWork::Order`] it walks the frozen order; for
2455/// [`CompilerWork::Streaming`] it resolves each branch at the frontier and
2456/// emits only the chosen arm's runs (Step E Phase C, PR C1). Sends
2457/// `Err(...)` and stops on the first failure.
2458fn compiler_thread_body(
2459    graph: Arc<RwLock<Graph>>,
2460    work: CompilerWork,
2461    sym_env: SymEnv,
2462    tx: Sender<Result<WorkItem>>,
2463) {
2464    let bindings = global_bindings();
2465
2466    let g = match graph.read() {
2467        Ok(g) => g,
2468        Err(_) => {
2469            let _ = tx.send(Err(poisoned("graph lock in compiler")));
2470            return;
2471        }
2472    };
2473
2474    // Compiler-thread-local layout cache. Populated as compile_one
2475    // walks topologically; downstream nodes look up their inputs'
2476    // layouts here (rather than from the graph side-table) to honor
2477    // the strided layouts emitted by metadata-only view ops earlier
2478    // in the same realize call.
2479    let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
2480    // `compile_one` for one node + send; returns `false` to stop the walk
2481    // (channel closed or compile error). Shared by both work modes so the
2482    // streamed and frozen-order paths compile identically.
2483    let compile_and_send = |id: NodeId, layout_cache: &mut HashMap<NodeId, Layout>| -> bool {
2484        let item = compile_one(&g, id, layout_cache, &bindings, &sym_env);
2485        let stop_on_err = item.is_err();
2486        if tx.send(item).is_err() {
2487            return false;
2488        }
2489        !stop_on_err
2490    };
2491
2492    match work {
2493        CompilerWork::Order(order) => {
2494            for id in order {
2495                if !compile_and_send(id, &mut layout_cache) {
2496                    return;
2497                }
2498            }
2499        }
2500        CompilerWork::Streaming { roots, pick } => {
2501            // Resolve each branch lazily at its arm-entry. C1 built the
2502            // streaming frontier; C2 made `pick.selector` load-aware (the
2503            // production `ChainedSelector` now reads each arm's live device
2504            // load — `pending_work_count / slot_capacity` via the
2505            // `BackendStreams` seam — as a key leg under the VRAM guard),
2506            // so this resolution reads live device load at THIS moment: the
2507            // executor has been submitting/draining (and updating the B1
2508            // counter) while the compiler ran ahead. Emit only the chosen
2509            // arm's runs, compiling + sending each node as the walk reaches
2510            // it — genuine streaming (resolution interleaved with
2511            // dispatch), not a pre-flattened order.
2512            let mut stopped = false;
2513            fuel_graph::walk_picked_route_streaming(
2514                &g,
2515                &roots,
2516                |branch| resolve_branch(&g, branch, &bindings, pick.selector.as_ref()),
2517                |members| {
2518                    if stopped {
2519                        return;
2520                    }
2521                    for &id in members {
2522                        if !compile_and_send(id, &mut layout_cache) {
2523                            stopped = true;
2524                            return;
2525                        }
2526                    }
2527                },
2528            );
2529        }
2530    }
2531}
2532
2533/// Resolve the [`CompiledNode`] for a kernel-bearing graph node via
2534/// the first-registered [`compile_node`] binding-table lookup.
2535///
2536/// `op_params` always comes from the executor's
2537/// `op_to_op_params(graph, node, id, layout_cache, sym_env)` — the live
2538/// OpParams shape (reduce dims, conv geometry, the per-pass
2539/// `SymEnv`-resolved `WriteSlice` offset, etc.) derives from the graph
2540/// node + its resolved input layouts at execute time.
2541fn resolve_compiled(
2542    op_kind: OpKind,
2543    dtypes: &[DType],
2544    target_backend: BackendId,
2545    op_params: OpParams,
2546    bindings: &KernelBindingTable,
2547) -> Result<CompiledNode> {
2548    compile_node(op_kind, dtypes, target_backend, op_params, bindings)
2549}
2550
2551/// Resolve one node into a `WorkItem` and update `layout_cache`
2552/// with the node's output layout. Three op shapes:
2553///
2554/// - `Op::Const` — adopts the entry from the input cache; layout is
2555///   read from the graph's side-table (or its contiguous fallback).
2556///
2557/// - Metadata-only view op — output layout is read from the graph's
2558///   side-table (populated by `Graph::push` at construction time);
2559///   the executor adopts the input's Storage Arc (no allocation, no
2560///   kernel).
2561///
2562/// - Computational op — output layout is `Layout::contiguous(node.shape)`
2563///   because today's kernels write contiguous output. The compiler
2564///   resolves the kernel ref and emits a Kernel work item.
2565fn compile_one(
2566    graph: &Graph,
2567    id: NodeId,
2568    layout_cache: &mut HashMap<NodeId, Layout>,
2569    bindings: &KernelBindingTable,
2570    sym_env: &SymEnv,
2571) -> Result<WorkItem> {
2572    let node = graph.node(id);
2573    let elem_count = node.shape.elem_count();
2574    let inputs = node.inputs.clone();
2575    // Snapshot destructive-input metadata from the graph at compile
2576    // time so the executor can evict the destroyed input from its
2577    // cache after the op runs (Op::Release / Op::Move semantics).
2578    let destructive_input = node.op.destructive_input();
2579
2580    if matches!(node.op, Op::Const) {
2581        let output_layout = graph.layout(id);
2582        layout_cache.insert(id, output_layout.clone());
2583        return Ok(WorkItem {
2584            node_id: id,
2585            inputs,
2586            elem_count,
2587            dtype: node.dtype,
2588            target_backend: BackendId::Cpu,
2589            kind: WorkItemKind::ConstAdopt,
2590            compiled: None,
2591            output_layout,
2592            destructive_input,
2593            output_bundle: None,
2594        });
2595    }
2596
2597    if node.op.is_view_op() {
2598        if inputs.len() != 1 {
2599            return Err(Error::Msg(format!(
2600                "view op {:?} expects 1 input, got {}",
2601                node.op,
2602                inputs.len(),
2603            ))
2604            .bt());
2605        }
2606        // Layout is read from the graph's side-table — populated by
2607        // `Graph::push` at construction time for view ops, and by
2608        // graph-rewriting opt passes that emit view nodes. The
2609        // compiler does not re-derive: graph.layout(id) is the single
2610        // source of truth.
2611        let output_layout = graph.layout(id);
2612        layout_cache.insert(id, output_layout.clone());
2613        // Inherit the upstream's target_backend (or default CPU) —
2614        // metadata-only adoption doesn't actually run on a backend,
2615        // but downstream consumers look at target_backend so it
2616        // needs to be set sensibly. Any device works.
2617        let target_backend = graph
2618            .target_backend(id)
2619            .or_else(|| graph.target_backend(inputs[0]))
2620            .unwrap_or(BackendId::Cpu);
2621        return Ok(WorkItem {
2622            node_id: id,
2623            inputs,
2624            elem_count,
2625            dtype: node.dtype,
2626            target_backend,
2627            kind: WorkItemKind::ViewOf {
2628                input: node.inputs[0],
2629            },
2630            compiled: None,
2631            output_layout,
2632            destructive_input,
2633            output_bundle: None,
2634        });
2635    }
2636
2637    // Op::View — multi-output projection (Option C, Session 4).
2638    // Structurally identical to a metadata-only view op at realize
2639    // time: clone the producer's Storage Arc into the View's cache
2640    // slot. The graph's layout side-table, populated by
2641    // `Tensor::view`, already carries the slot's effective layout
2642    // (slot.byte_offset baked into start_offset in slot-dtype-element
2643    // units).
2644    if let Op::View { .. } = node.op {
2645        if inputs.len() != 1 {
2646            return Err(Error::Msg(format!(
2647                "Op::View expects 1 input (the producer), got {}",
2648                inputs.len(),
2649            ))
2650            .bt());
2651        }
2652        let output_layout = graph.layout(id);
2653        layout_cache.insert(id, output_layout.clone());
2654        let target_backend = graph
2655            .target_backend(id)
2656            .or_else(|| graph.target_backend(inputs[0]))
2657            .unwrap_or(BackendId::Cpu);
2658        return Ok(WorkItem {
2659            node_id: id,
2660            inputs: inputs.clone(),
2661            elem_count,
2662            dtype: node.dtype,
2663            target_backend,
2664            kind: WorkItemKind::SlotView {
2665                producer: inputs[0],
2666            },
2667            compiled: None,
2668            output_layout,
2669            destructive_input,
2670            output_bundle: None,
2671        });
2672    }
2673
2674    // Op::ViewOwned — copies the slot's bytes into a fresh
2675    // contiguous Storage at realize time. Output layout is
2676    // contiguous starting at offset 0 (the memcpy produced an
2677    // independent buffer).
2678    if let Op::ViewOwned { slot } = node.op {
2679        if inputs.len() != 1 {
2680            return Err(Error::Msg(format!(
2681                "Op::ViewOwned expects 1 input (the producer), got {}",
2682                inputs.len(),
2683            ))
2684            .bt());
2685        }
2686        let output_layout = Layout::contiguous(node.shape.clone());
2687        layout_cache.insert(id, output_layout.clone());
2688        let target_backend = graph
2689            .target_backend(id)
2690            .or_else(|| graph.target_backend(inputs[0]))
2691            .unwrap_or(BackendId::Cpu);
2692        return Ok(WorkItem {
2693            node_id: id,
2694            inputs: inputs.clone(),
2695            elem_count,
2696            dtype: node.dtype,
2697            target_backend,
2698            kind: WorkItemKind::SlotOwn {
2699                producer: inputs[0],
2700                slot,
2701            },
2702            compiled: None,
2703            output_layout,
2704            destructive_input,
2705            output_bundle: None,
2706        });
2707    }
2708
2709    if matches!(node.op, Op::Release) {
2710        // Op::Release produces a zero-element marker output. The
2711        // marker storage is CPU + 0 bytes — nothing reads it; it
2712        // exists so cache lookups on the Release NodeId resolve.
2713        // The actual deallocation of `inputs[0]` happens in the
2714        // realize loop via `destructive_input` cleanup.
2715        if inputs.len() != 1 {
2716            return Err(
2717                Error::Msg(format!("Op::Release expects 1 input, got {}", inputs.len(),)).bt(),
2718            );
2719        }
2720        let output_layout = Layout::contiguous(node.shape.clone());
2721        layout_cache.insert(id, output_layout.clone());
2722        // Inherit the source's target_backend so any downstream
2723        // backend-aware logic (telemetry, scheduling) sees a sensible
2724        // value. The marker doesn't actually run on any backend.
2725        let target_backend = graph
2726            .target_backend(id)
2727            .or_else(|| graph.target_backend(inputs[0]))
2728            .unwrap_or(BackendId::Cpu);
2729        return Ok(WorkItem {
2730            node_id: id,
2731            inputs,
2732            elem_count,
2733            dtype: node.dtype,
2734            target_backend,
2735            kind: WorkItemKind::ReleaseMarker,
2736            compiled: None,
2737            output_layout,
2738            destructive_input,
2739            output_bundle: None,
2740        });
2741    }
2742
2743    // In-place ops (Phase 3 of in-place ops infrastructure): kernel
2744    // lookup goes through the standard binding-table path, but the
2745    // executor adopts the target's Arc as the output instead of
2746    // allocating fresh bytes. The compile-time predicate is exactly
2747    // `op.destructive_input().is_some()` AND NOT one of the
2748    // structural ops (WriteSlice / ZeroFill / Release / Move) which
2749    // have their own dedicated WorkItemKind arms in this function.
2750    if !matches!(
2751        node.op,
2752        Op::WriteSlice { .. }
2753            | Op::WriteSliceRotating { .. }
2754            | Op::WriteSliceDoff { .. }
2755            | Op::ZeroFill
2756            | Op::Release
2757            | Op::Move { .. },
2758    ) && let Some(target_idx) = node.op.destructive_input()
2759    {
2760        if inputs.len() <= target_idx {
2761            return Err(Error::Msg(format!(
2762                "in-place op {:?} declares destructive_input={target_idx} \
2763                     but has only {} input(s)",
2764                node.op,
2765                inputs.len(),
2766            ))
2767            .bt());
2768        }
2769        let target_backend = graph.target_backend(id).ok_or_else(|| {
2770            Error::Msg(format!(
2771                "PipelinedExecutor: in-place op node {id:?} has no target_backend set",
2772            ))
2773            .bt()
2774        })?;
2775        let op_kind = op_to_op_kind(&node.op).ok_or_else(|| {
2776            Error::Msg(format!(
2777                "PipelinedExecutor: in-place op {:?} has no op_to_op_kind mapping",
2778                node.op,
2779            ))
2780            .bt()
2781        })?;
2782        let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
2783        let dtypes = build_lookup_dtypes(graph, node);
2784        let compiled = resolve_compiled(op_kind, &dtypes, target_backend, op_params, bindings)?;
2785        // Output adopts target's Layout (same Storage Arc, same shape).
2786        let output_layout = graph.layout(inputs[target_idx]);
2787        layout_cache.insert(id, output_layout.clone());
2788        return Ok(WorkItem {
2789            node_id: id,
2790            inputs: inputs.clone(),
2791            elem_count,
2792            dtype: node.dtype,
2793            target_backend,
2794            kind: WorkItemKind::InplaceKernel { target_idx },
2795            compiled: Some(compiled),
2796            output_layout,
2797            destructive_input,
2798            output_bundle: None,
2799        });
2800    }
2801
2802    if matches!(node.op, Op::WriteSlice { .. }) {
2803        // WriteSlice: kernel lookup happens like a normal kernel, but
2804        // the work item carries a dedicated kind so the executor
2805        // knows to adopt the destination's Arc as the output rather
2806        // than allocating a fresh buffer. The destination's NodeId is
2807        // captured here so the executor doesn't have to re-derive it.
2808        if inputs.len() != 2 {
2809            return Err(Error::Msg(format!(
2810                "Op::WriteSlice expects 2 inputs (destination, source), got {}",
2811                inputs.len(),
2812            ))
2813            .bt());
2814        }
2815        let target_backend = graph.target_backend(id).ok_or_else(|| {
2816            Error::Msg(format!(
2817                "PipelinedExecutor: WriteSlice node {:?} has no target_backend set",
2818                id
2819            ))
2820            .bt()
2821        })?;
2822        let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
2823        let dtypes = build_lookup_dtypes(graph, node);
2824        let compiled = resolve_compiled(
2825            OpKind::WriteSlice,
2826            &dtypes,
2827            target_backend,
2828            op_params,
2829            bindings,
2830        )?;
2831        // Output adopts the destination's Layout — same Storage Arc,
2832        // same shape. Downstream consumers that want a post-write
2833        // sub-extent compose an explicit Op::Slice (WriteSlice does
2834        // not encode partial extents).
2835        let output_layout = graph.layout(inputs[0]);
2836        layout_cache.insert(id, output_layout.clone());
2837        return Ok(WorkItem {
2838            node_id: id,
2839            inputs: inputs.clone(),
2840            elem_count,
2841            dtype: node.dtype,
2842            target_backend,
2843            kind: WorkItemKind::WriteSlice {
2844                dest: inputs[0],
2845                source: inputs[1],
2846            },
2847            compiled: Some(compiled),
2848            output_layout,
2849            destructive_input,
2850            output_bundle: None,
2851        });
2852    }
2853
2854    if matches!(node.op, Op::WriteSliceRotating { .. }) {
2855        // WriteSliceRotating: same shape as WriteSlice but with a
2856        // third input (position scalar). Dispatch through the
2857        // binding table at `OpKind::WriteSliceRotating`; the
2858        // executor's arm reads the position from `position`'s
2859        // storage and the kernel splits across the ring boundary.
2860        if inputs.len() != 3 {
2861            return Err(Error::Msg(format!(
2862                "Op::WriteSliceRotating expects 3 inputs (destination, source, position), got {}",
2863                inputs.len(),
2864            ))
2865            .bt());
2866        }
2867        let target_backend = graph.target_backend(id).ok_or_else(|| {
2868            Error::Msg(format!(
2869                "PipelinedExecutor: WriteSliceRotating node {:?} has no target_backend set",
2870                id
2871            ))
2872            .bt()
2873        })?;
2874        let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
2875        let dtypes = build_lookup_dtypes(graph, node);
2876        let compiled = resolve_compiled(
2877            OpKind::WriteSliceRotating,
2878            &dtypes,
2879            target_backend,
2880            op_params,
2881            bindings,
2882        )?;
2883        let output_layout = graph.layout(inputs[0]);
2884        layout_cache.insert(id, output_layout.clone());
2885        return Ok(WorkItem {
2886            node_id: id,
2887            inputs: inputs.clone(),
2888            elem_count,
2889            dtype: node.dtype,
2890            target_backend,
2891            kind: WorkItemKind::WriteSliceRotating {
2892                dest: inputs[0],
2893                source: inputs[1],
2894                position: inputs[2],
2895            },
2896            compiled: Some(compiled),
2897            output_layout,
2898            destructive_input,
2899            output_bundle: None,
2900        });
2901    }
2902
2903    if matches!(node.op, Op::WriteSliceDoff { .. }) {
2904        // WriteSliceDoff: same shape as WriteSlice but with a third
2905        // input (device-resident I64 offset). Dispatch through the
2906        // binding table at `OpKind::WriteSliceDoff`; the executor's arm
2907        // threads the offset's device pointer straight to the kernel
2908        // (no D2H, capture-safe).
2909        if inputs.len() != 3 {
2910            return Err(Error::Msg(format!(
2911                "Op::WriteSliceDoff expects 3 inputs (destination, source, offset), got {}",
2912                inputs.len(),
2913            ))
2914            .bt());
2915        }
2916        let target_backend = graph.target_backend(id).ok_or_else(|| {
2917            Error::Msg(format!(
2918                "PipelinedExecutor: WriteSliceDoff node {:?} has no target_backend set",
2919                id
2920            ))
2921            .bt()
2922        })?;
2923        let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
2924        let dtypes = build_lookup_dtypes(graph, node);
2925        let compiled = resolve_compiled(
2926            OpKind::WriteSliceDoff,
2927            &dtypes,
2928            target_backend,
2929            op_params,
2930            bindings,
2931        )?;
2932        let output_layout = graph.layout(inputs[0]);
2933        layout_cache.insert(id, output_layout.clone());
2934        return Ok(WorkItem {
2935            node_id: id,
2936            inputs: inputs.clone(),
2937            elem_count,
2938            dtype: node.dtype,
2939            target_backend,
2940            kind: WorkItemKind::WriteSliceDoff {
2941                dest: inputs[0],
2942                source: inputs[1],
2943                offset: inputs[2],
2944            },
2945            compiled: Some(compiled),
2946            output_layout,
2947            destructive_input,
2948            output_bundle: None,
2949        });
2950    }
2951
2952    if let Op::Alloc { target } = node.op {
2953        // Op::Alloc { target }: produce a fresh zero-init Storage on
2954        // `target` with node.shape * node.dtype. Zero inputs.
2955        // Direct executor dispatch via WorkItemKind::Alloc — no
2956        // binding-table lookup (the device handle threading isn't
2957        // expressible through the binding table's current key shape).
2958        if !inputs.is_empty() {
2959            return Err(
2960                Error::Msg(format!("Op::Alloc expects 0 inputs, got {}", inputs.len(),)).bt(),
2961            );
2962        }
2963        let output_layout = Layout::contiguous(node.shape.clone());
2964        layout_cache.insert(id, output_layout.clone());
2965        // target_backend is informational here (the executor's Alloc
2966        // arm consults target_location for allocation routing); set
2967        // it to target's backend for consistency with how downstream
2968        // nodes inherit/read it.
2969        let target_backend = target.backend();
2970        return Ok(WorkItem {
2971            node_id: id,
2972            inputs,
2973            elem_count,
2974            dtype: node.dtype,
2975            target_backend,
2976            kind: WorkItemKind::Alloc {
2977                target_location: target,
2978            },
2979            compiled: None,
2980            output_layout,
2981            destructive_input,
2982            output_bundle: None,
2983        });
2984    }
2985
2986    if let Op::Iota { len } = node.op {
2987        // Op::Iota { len }: 0-input F32 position generator
2988        // [0.0, 1.0, …, (len-1)]. Direct executor dispatch via
2989        // WorkItemKind::Iota — no binding-table lookup (a leaf has no
2990        // inputs[0] to inherit a backend from). Modeled on Op::Alloc.
2991        if !inputs.is_empty() {
2992            return Err(
2993                Error::Msg(format!("Op::Iota expects 0 inputs, got {}", inputs.len(),)).bt(),
2994            );
2995        }
2996        let output_layout = Layout::contiguous(node.shape.clone());
2997        layout_cache.insert(id, output_layout.clone());
2998        // Leaf: the planner may not place a 0-input node, so fall back to
2999        // CPU. Iota is a tiny host-side generator; its only consumer today
3000        // is the CPU flash-attn decomposition's alibi bias.
3001        let target_backend = graph.target_backend(id).unwrap_or(BackendId::Cpu);
3002        return Ok(WorkItem {
3003            node_id: id,
3004            inputs,
3005            elem_count,
3006            dtype: node.dtype,
3007            target_backend,
3008            kind: WorkItemKind::Iota { len },
3009            compiled: None,
3010            output_layout,
3011            destructive_input,
3012            output_bundle: None,
3013        });
3014    }
3015
3016    if matches!(node.op, Op::ZeroFill) {
3017        // Op::ZeroFill: 1 input (the buffer to zero); output aliases
3018        // input's Storage Arc (destructive in-place). No binding-
3019        // table lookup — per-backend dispatch in execute_work_item.
3020        if inputs.len() != 1 {
3021            return Err(Error::Msg(format!(
3022                "Op::ZeroFill expects 1 input, got {}",
3023                inputs.len(),
3024            ))
3025            .bt());
3026        }
3027        // Output layout: contiguous in the node's shape. We don't
3028        // require the input to be contiguous (auto_contiguize in the
3029        // executor handles strided inputs), but the destructive
3030        // semantic means callers should only ZeroFill an Op::Alloc
3031        // output today.
3032        let output_layout = Layout::contiguous(node.shape.clone());
3033        layout_cache.insert(id, output_layout.clone());
3034        let target_backend = graph
3035            .target_backend(id)
3036            .or_else(|| graph.target_backend(inputs[0]))
3037            .unwrap_or(BackendId::Cpu);
3038        return Ok(WorkItem {
3039            node_id: id,
3040            inputs,
3041            elem_count,
3042            dtype: node.dtype,
3043            target_backend,
3044            kind: WorkItemKind::ZeroFill,
3045            compiled: None,
3046            output_layout,
3047            destructive_input,
3048            output_bundle: None,
3049        });
3050    }
3051
3052    if let Op::Copy { target } = node.op {
3053        // Op::Copy { target }: download bytes from the source residency
3054        // to a fresh Storage allocated on `target`. Kernel lookup uses
3055        // `target_backend` = source backend (set by `prepare()` on the
3056        // realize device the source is on); the wrapper does the actual
3057        // transfer (e.g. Vulkan::download_bytes → memcpy into a CPU
3058        // CpuStorageBytes). The output Storage's variant is determined
3059        // by `target_location` and allocated in `execute_work_item`'s
3060        // WorkItemKind::Copy arm.
3061        if inputs.len() != 1 {
3062            return Err(
3063                Error::Msg(format!("Op::Copy expects 1 input, got {}", inputs.len(),)).bt(),
3064            );
3065        }
3066        let target_backend = graph.target_backend(id).ok_or_else(|| {
3067            Error::Msg(format!(
3068                "PipelinedExecutor: Op::Copy node {:?} has no target_backend \
3069                 set (= source backend, the one whose kernel runs the \
3070                 download)",
3071                id
3072            ))
3073            .bt()
3074        })?;
3075        let op_params = OpParams::None;
3076        let dtypes = build_lookup_dtypes(graph, node);
3077        let compiled =
3078            resolve_compiled(OpKind::Copy, &dtypes, target_backend, op_params, bindings)?;
3079        // Output layout: contiguous in the node's shape (mirrors the
3080        // source's logical shape). Auto-contiguize on the input side
3081        // (in execute_work_item) handles strided source views by
3082        // materializing them into a contiguous source buffer before
3083        // the kernel runs.
3084        let output_layout = Layout::contiguous(node.shape.clone());
3085        layout_cache.insert(id, output_layout.clone());
3086        return Ok(WorkItem {
3087            node_id: id,
3088            inputs,
3089            elem_count,
3090            dtype: node.dtype,
3091            target_backend,
3092            kind: WorkItemKind::Copy {
3093                target_location: target,
3094            },
3095            compiled: Some(compiled),
3096            output_layout,
3097            destructive_input,
3098            output_bundle: None,
3099        });
3100    }
3101
3102    if let Op::Move { target } = node.op {
3103        // Op::Move { target }: identical data-movement half to
3104        // Op::Copy — kernel lookup at (OpKind::Copy, [dt, dt],
3105        // source_backend); output allocated on `target` by the
3106        // executor's Copy/Move arm. The destructive half (release
3107        // the source) rides the realize loop's `destructive_input`
3108        // cleanup via the snapshot taken at the top of this function
3109        // (`Op::Move::destructive_input() == Some(0)`). Ordering
3110        // safety (a Move must not strand a sibling consumer of its
3111        // source) is `execution_plan`/`derive_ordering`'s job — the
3112        // Move is pinned after every non-destructive reader of the
3113        // source's alias set before any work item is emitted.
3114        if inputs.len() != 1 {
3115            return Err(
3116                Error::Msg(format!("Op::Move expects 1 input, got {}", inputs.len(),)).bt(),
3117            );
3118        }
3119        let target_backend = graph.target_backend(id).ok_or_else(|| {
3120            Error::Msg(format!(
3121                "PipelinedExecutor: Op::Move node {:?} has no target_backend \
3122                 set (= source backend, the one whose kernel runs the \
3123                 transfer)",
3124                id
3125            ))
3126            .bt()
3127        })?;
3128        let op_params = OpParams::None;
3129        let dtypes = build_lookup_dtypes(graph, node);
3130        let compiled =
3131            resolve_compiled(OpKind::Copy, &dtypes, target_backend, op_params, bindings)?;
3132        // Output layout: contiguous in the node's shape, same as
3133        // Op::Copy (the transfer materializes strided sources via
3134        // auto-contiguize on the input side).
3135        let output_layout = Layout::contiguous(node.shape.clone());
3136        layout_cache.insert(id, output_layout.clone());
3137        return Ok(WorkItem {
3138            node_id: id,
3139            inputs,
3140            elem_count,
3141            dtype: node.dtype,
3142            target_backend,
3143            kind: WorkItemKind::Move {
3144                target_location: target,
3145            },
3146            compiled: Some(compiled),
3147            output_layout,
3148            destructive_input,
3149            output_bundle: None,
3150        });
3151    }
3152
3153    if matches!(node.op, Op::Reshape(_)) {
3154        if inputs.len() != 1 {
3155            return Err(
3156                Error::Msg(format!("Op::Reshape expects 1 input, got {}", inputs.len(),)).bt(),
3157            );
3158        }
3159        let input_layout = graph.layout(inputs[0]);
3160        // Output is contiguous in the new shape — bytes per element
3161        // are unchanged, so a contiguous input flows through with
3162        // zero copy. A non-contiguous input is auto-contiguized at
3163        // execute time and the result is naturally contiguous.
3164        let output_layout = Layout::contiguous(node.shape.clone());
3165        layout_cache.insert(id, output_layout.clone());
3166        let target_backend = graph
3167            .target_backend(id)
3168            .or_else(|| graph.target_backend(inputs[0]))
3169            .unwrap_or(BackendId::Cpu);
3170        // Sanity: same total element count.
3171        let in_elem_count = input_layout.shape().elem_count();
3172        if in_elem_count != elem_count {
3173            return Err(Error::Msg(format!(
3174                "Op::Reshape changes element count: input {} → output {}",
3175                in_elem_count, elem_count,
3176            ))
3177            .bt());
3178        }
3179        return Ok(WorkItem {
3180            node_id: id,
3181            inputs,
3182            elem_count,
3183            dtype: node.dtype,
3184            target_backend,
3185            kind: WorkItemKind::ContiguizeOf {
3186                input: node.inputs[0],
3187            },
3188            compiled: None,
3189            output_layout,
3190            destructive_input,
3191            output_bundle: None,
3192        });
3193    }
3194
3195    if matches!(node.op, Op::Contiguize) {
3196        // Op::Contiguize: same execute-time path as Reshape, but
3197        // output shape == input shape so there's no element-count
3198        // check. Zero-copy when input is already contiguous +
3199        // zero-offset (the ContiguizeOf arm in execute_work_item
3200        // adopts the input Arc); otherwise auto_contiguize allocates
3201        // a fresh contiguous Storage on the input's backend.
3202        if inputs.len() != 1 {
3203            return Err(Error::Msg(format!(
3204                "Op::Contiguize expects 1 input, got {}",
3205                inputs.len(),
3206            ))
3207            .bt());
3208        }
3209        let output_layout = Layout::contiguous(node.shape.clone());
3210        layout_cache.insert(id, output_layout.clone());
3211        let target_backend = graph
3212            .target_backend(id)
3213            .or_else(|| graph.target_backend(inputs[0]))
3214            .unwrap_or(BackendId::Cpu);
3215        return Ok(WorkItem {
3216            node_id: id,
3217            inputs,
3218            elem_count,
3219            dtype: node.dtype,
3220            target_backend,
3221            kind: WorkItemKind::ContiguizeOf {
3222                input: node.inputs[0],
3223            },
3224            compiled: None,
3225            output_layout,
3226            destructive_input,
3227            output_bundle: None,
3228        });
3229    }
3230
3231    // Runtime fused op — a JIT-adopted (Tier-2) kernel. `Op::Fused(fid, _)`
3232    // with `fid.is_runtime()` has no `OpKind` (the op was synthesized after
3233    // startup): its kernel resolves from the SAME binding table as every
3234    // static kernel, under `BindingKey::RuntimeFused(fid)` — the dtype tuple
3235    // is the key, so an absent kernel AND a dtype mismatch are one honest
3236    // `NoBackendForOp` miss. A deterministic *lookup*, not a decision: the
3237    // optimizer's gate emitted the arm only when this kernel was bound, and
3238    // pinned `target_backend` (`runtime-fused-op-registration.md` §6). The
3239    // guards are invariant checks, never live fallbacks.
3240    if let Op::Fused(fid, _) = &node.op
3241        && fid.is_runtime()
3242    {
3243        let target_backend = graph.target_backend(id).ok_or_else(|| {
3244            Error::Msg(format!(
3245                "PipelinedExecutor: runtime fused op {:?} (node {:?}) has no \
3246                     target_backend — the arm emitter pins it at emission",
3247                fid, id,
3248            ))
3249            .bt()
3250        })?;
3251        // v1: single-output only. Reject a multi-output bundle explicitly
3252        // rather than silently dropping it.
3253        if graph.output_views_arc(id).is_some() {
3254            return Err(Error::Msg(format!(
3255                "PipelinedExecutor: runtime fused op {:?} (node {:?}) carries a \
3256                     multi-output bundle — synthesized kernels are single-output in v1",
3257                fid, id,
3258            ))
3259            .bt());
3260        }
3261        let dtypes = build_lookup_dtypes(graph, node);
3262        let (kernel, caps) = bindings.lookup_with_caps(
3263            crate::kernel::BindingKey::RuntimeFused(*fid),
3264            &dtypes,
3265            target_backend,
3266        )?;
3267        let output_layout = Layout::contiguous(node.shape.clone());
3268        layout_cache.insert(id, output_layout.clone());
3269        // Deliberate, not a fallthrough to `op_to_op_params` (which doesn't
3270        // know runtime ops): the node's `Runtime { scalars }` — the live
3271        // `extract:` values, pattern pre-order — becomes `JitScalars` (the
3272        // launch appends them as the kernel's trailing `p{i}` args); a
3273        // param-free op carries `None` (its launch is layout-driven:
3274        // pointers + element count).
3275        let op_params = match &node.op {
3276            Op::Fused(_, FusedOpParams::Runtime { scalars }) if !scalars.is_empty() => {
3277                OpParams::JitScalars {
3278                    scalars: scalars.clone(),
3279                }
3280            }
3281            _ => OpParams::None,
3282        };
3283        let compiled = CompiledNode {
3284            op: OpKind::RuntimeFused,
3285            dtypes: KernelDTypes::from_slice(&dtypes),
3286            backend: target_backend,
3287            kernel,
3288            caps,
3289            op_params,
3290        };
3291        return Ok(WorkItem {
3292            node_id: id,
3293            inputs,
3294            elem_count,
3295            dtype: node.dtype,
3296            target_backend,
3297            kind: WorkItemKind::Kernel,
3298            compiled: Some(compiled),
3299            output_layout,
3300            destructive_input,
3301            output_bundle: None,
3302        });
3303    }
3304
3305    let target_backend = graph.target_backend(id).ok_or_else(|| {
3306        Error::Msg(format!(
3307            "PipelinedExecutor: node {:?} ({:?}) has no target_backend set",
3308            id, node.op
3309        ))
3310        .bt()
3311    })?;
3312
3313    let op_kind = op_to_op_kind(&node.op).ok_or_else(|| {
3314        Error::Msg(format!(
3315            "PipelinedExecutor: op {:?} not yet mapped to an OpKind \
3316             (Phase C migrates more ops as they're registered)",
3317            node.op,
3318        ))
3319        .bt()
3320    })?;
3321
3322    let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3323    // Build the per-operand dtype list for the binding-table lookup —
3324    // inputs in order, then outputs. Variadic uniform-dtype ops
3325    // (Concat) collapse to the canonical `[T_in, T_out]` shorthand to
3326    // match how registrations index them.
3327    let dtypes = build_lookup_dtypes(graph, node);
3328    let compiled = resolve_compiled(op_kind, &dtypes, target_backend, op_params, bindings)?;
3329    let output_layout = Layout::contiguous(node.shape.clone());
3330    layout_cache.insert(id, output_layout.clone());
3331    // Multi-output: snapshot the producer's bundle metadata. When
3332    // `Some(_)`, the Kernel arm allocates a single Storage sized to
3333    // fit every slot and attaches the bundle via
3334    // `Storage::with_bundle` so downstream Op::View/Op::ViewOwned
3335    // resolve correctly.
3336    let output_bundle = graph.output_views_arc(id);
3337    Ok(WorkItem {
3338        node_id: id,
3339        inputs,
3340        elem_count,
3341        dtype: node.dtype,
3342        target_backend,
3343        kind: WorkItemKind::Kernel,
3344        compiled: Some(compiled),
3345        output_layout,
3346        destructive_input,
3347        output_bundle,
3348    })
3349}
3350
3351/// Build the per-operand dtype list used as the binding-table lookup
3352/// key. Inputs in order, then the output. Variadic-uniform ops
3353/// (Concat) collapse to the canonical `[T_in, T_out]` shorthand to
3354/// match how those wrappers are registered (otherwise an N-way concat
3355/// would need N+1 distinct registrations per dtype).
3356///
3357/// `pub(crate)` — `crate::plan::compile_plan` (step 9b) reuses this
3358/// to key the route picker's binding-table lookup the same way the
3359/// pipelined path does.
3360pub(crate) fn build_lookup_dtypes(graph: &Graph, node: &Node) -> Vec<DType> {
3361    if matches!(node.op, Op::Concat { .. }) {
3362        // Concat: all inputs share node.dtype by construction.
3363        let in_dt = node
3364            .inputs
3365            .first()
3366            .map(|&id| graph.node(id).dtype)
3367            .unwrap_or(node.dtype);
3368        return vec![in_dt, node.dtype];
3369    }
3370    if matches!(node.op, Op::WriteSlice { .. }) {
3371        // WriteSlice: the destination (inputs[0]) is exposed to the
3372        // executor as the OUTPUT slot (in-place adoption), not as an
3373        // input the kernel reads. Canonicalize the binding-table key
3374        // to `[T_source, T_out]` so registrations match the kernel's
3375        // actual surface (one input slab + one output buffer).
3376        let src_dt = node
3377            .inputs
3378            .get(1)
3379            .map(|&id| graph.node(id).dtype)
3380            .unwrap_or(node.dtype);
3381        return vec![src_dt, node.dtype];
3382    }
3383    if matches!(node.op, Op::WriteSliceRotating { .. }) {
3384        // Same canonicalization as WriteSlice: dest = output slot;
3385        // position (inputs[2]) is read by the kernel via the
3386        // position-input parameter, not the binding-table key.
3387        let src_dt = node
3388            .inputs
3389            .get(1)
3390            .map(|&id| graph.node(id).dtype)
3391            .unwrap_or(node.dtype);
3392        return vec![src_dt, node.dtype];
3393    }
3394    if matches!(node.op, Op::WriteSliceDoff { .. }) {
3395        // Same canonicalization as WriteSlice: dest = output slot;
3396        // offset (inputs[2], I64) is a non-key runtime operand read by
3397        // the kernel via its device pointer, not the binding-table key.
3398        let src_dt = node
3399            .inputs
3400            .get(1)
3401            .map(|&id| graph.node(id).dtype)
3402            .unwrap_or(node.dtype);
3403        return vec![src_dt, node.dtype];
3404    }
3405    let mut dts: Vec<DType> = node.inputs.iter().map(|&id| graph.node(id).dtype).collect();
3406    dts.push(node.dtype);
3407    dts
3408}
3409
3410/// SoftmaxLastDim is reachable only through `Op::Fused(FusedOps::
3411/// SOFTMAX_LAST_DIM, _)` post-step-5 (the legacy `Op::SoftmaxLastDim`
3412/// primitive variant was retired). This helper collapses the
3413/// op-to-OpKind/OpParams shapes for callers that want a single-arm
3414/// match.
3415fn op_is_softmax_last_dim(op: &Op) -> bool {
3416    matches!(op, Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM)
3417}
3418
3419/// FusedLinear is reachable only through `Op::Fused(FusedOps::
3420/// FUSED_LINEAR, _)` post-step-5.
3421fn op_is_fused_linear(op: &Op) -> bool {
3422    matches!(op, Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::FUSED_LINEAR)
3423}
3424
3425/// Map a `fuel_graph::Op` to a `fuel_ir::dispatch::OpKind`.
3426/// Returns `None` for ops that haven't been wired into the new
3427/// dispatch path yet — Phase C extends this as op families migrate.
3428///
3429/// `pub(crate)` — `crate::plan::compile_plan` (step 9b) reuses this
3430/// to skip nodes the binding-table doesn't index (view ops,
3431/// `Op::Const`, not-yet-migrated ops) when building bindings.
3432pub(crate) fn op_to_op_kind(op: &Op) -> Option<OpKind> {
3433    match op {
3434        Op::Add => Some(OpKind::AddElementwise),
3435        Op::Sub => Some(OpKind::SubElementwise),
3436        Op::Mul => Some(OpKind::MulElementwise),
3437        Op::Div => Some(OpKind::DivElementwise),
3438        Op::Relu => Some(OpKind::ReluElementwise),
3439        Op::Neg => Some(OpKind::NegElementwise),
3440        Op::Sqr => Some(OpKind::SqrElementwise),
3441        Op::Sqrt => Some(OpKind::SqrtElementwise),
3442        Op::Tanh => Some(OpKind::TanhElementwise),
3443        Op::Exp => Some(OpKind::ExpElementwise),
3444        Op::Log => Some(OpKind::LogElementwise),
3445        Op::Sin => Some(OpKind::SinElementwise),
3446        Op::Cos => Some(OpKind::CosElementwise),
3447        Op::Sigmoid => Some(OpKind::SigmoidElementwise),
3448        Op::Silu => Some(OpKind::SiluElementwise),
3449        Op::GeluTanh => Some(OpKind::GeluTanhElementwise),
3450        Op::Step => Some(OpKind::StepElementwise),
3451        Op::Recip => Some(OpKind::RecipElementwise),
3452        Op::Abs => Some(OpKind::AbsElementwise),
3453        Op::Equal => Some(OpKind::EqualElementwise),
3454        Op::Ne => Some(OpKind::NotEqualElementwise),
3455        Op::Lt => Some(OpKind::LessElementwise),
3456        Op::Le => Some(OpKind::LessEqualElementwise),
3457        Op::Gt => Some(OpKind::GreaterElementwise),
3458        Op::Ge => Some(OpKind::GreaterEqualElementwise),
3459        Op::Where => Some(OpKind::Where),
3460        Op::Floor => Some(OpKind::FloorElementwise),
3461        Op::Ceil => Some(OpKind::CeilElementwise),
3462        Op::Round => Some(OpKind::RoundElementwise),
3463        Op::Sign => Some(OpKind::SignElementwise),
3464        Op::Erf => Some(OpKind::ErfElementwise),
3465        Op::Gelu => Some(OpKind::GeluElementwise),
3466        Op::Pow => Some(OpKind::PowElementwise),
3467        Op::Rsqrt => Some(OpKind::RsqrtElementwise),
3468        Op::Rem => Some(OpKind::RemElementwise),
3469        Op::Flip { .. } => Some(OpKind::Flip),
3470        Op::Roll { .. } => Some(OpKind::Roll),
3471        Op::CumSum { .. } => Some(OpKind::CumSum),
3472        Op::Triu { .. } => Some(OpKind::Triu),
3473        Op::Tril { .. } => Some(OpKind::Tril),
3474        Op::LogSoftmaxLastDim => Some(OpKind::LogSoftmaxLastDim),
3475        Op::LogSoftmaxLastDimBackward => Some(OpKind::LogSoftmaxLastDimBackward),
3476        Op::MaskedFill { .. } => Some(OpKind::MaskedFill),
3477        Op::Pad { .. } => Some(OpKind::Pad),
3478        Op::PadBackward { .. } => Some(OpKind::PadBackward),
3479        Op::SumDim(_) => Some(OpKind::SumReduce),
3480        Op::MaxDim(_) => Some(OpKind::MaxReduce),
3481        Op::MinDim(_) => Some(OpKind::MinReduce),
3482        Op::MeanDim(_) => Some(OpKind::MeanReduce),
3483        Op::SumAll => Some(OpKind::SumReduce),
3484        Op::MaxAll => Some(OpKind::MaxReduce),
3485        Op::MinAll => Some(OpKind::MinReduce),
3486        Op::MeanAll => Some(OpKind::MeanReduce),
3487        Op::MatMul => Some(OpKind::MatMul),
3488        Op::Cast(_) => Some(OpKind::Cast),
3489        // Phase 7.6 step 5: fused-op dispatch routes through
3490        // `Op::Fused(fid, _)`; the legacy `Op::Conv2D` /
3491        // `Op::FusedLinear` / `Op::SoftmaxLastDim` /
3492        // `Op::RmsNormLastDim` / `Op::LayerNormLastDim` / `Op::Rope`
3493        // arms were dropped together with the variants.
3494        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::CONV2D => Some(OpKind::Conv2D),
3495        // Phase 7.6 step 5 (final): legacy `Op::ConvTranspose2D` /
3496        // `Op::FlashAttn` / `Op::PagedAttn` arms dropped with the
3497        // variants; dispatch flows only through `Op::Fused`.
3498        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D => {
3499            Some(OpKind::ConvTranspose2D)
3500        }
3501        Op::ReduceSumTo(_) => Some(OpKind::ReduceSumTo),
3502        Op::ReduceMaxTo(_) => Some(OpKind::ReduceMaxTo),
3503        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::FLASH_ATTN => {
3504            Some(OpKind::FlashAttn)
3505        }
3506        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::PAGED_ATTN => {
3507            Some(OpKind::PagedAttn)
3508        }
3509        Op::AddScalar(_) => Some(OpKind::Affine),
3510        Op::MulScalar(_) => Some(OpKind::Affine),
3511        Op::Clamp { .. } => Some(OpKind::ClampElementwise),
3512        Op::PowI(_) => Some(OpKind::PowIElementwise),
3513        Op::Maximum => Some(OpKind::MaximumElementwise),
3514        Op::Minimum => Some(OpKind::MinimumElementwise),
3515        Op::Concat { .. } => Some(OpKind::Concat),
3516        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM => {
3517            Some(OpKind::SoftmaxLastDim)
3518        }
3519        // Phase 7.6 step 6 follow-up: backward helpers now route
3520        // through the byte-level binding table too.
3521        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM_BACKWARD => {
3522            Some(OpKind::SoftmaxLastDimBackward)
3523        }
3524        Op::Fused(fid, _)
3525            if *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM_BACKWARD =>
3526        {
3527            Some(OpKind::LayerNormLastDimBackward)
3528        }
3529        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM_BACKWARD => {
3530            Some(OpKind::RmsNormLastDimBackward)
3531        }
3532        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::REDUCE_MAX_TO_BACKWARD => {
3533            Some(OpKind::ReduceMaxToBackward)
3534        }
3535        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::POWI_BACKWARD => {
3536            Some(OpKind::PowIElementwiseBackward)
3537        }
3538        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::FUSED_LINEAR => {
3539            Some(OpKind::FusedLinear)
3540        }
3541        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM => {
3542            Some(OpKind::RmsNormLastDim)
3543        }
3544        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM => {
3545            Some(OpKind::LayerNormLastDim)
3546        }
3547        Op::IndexSelect { .. } => Some(OpKind::IndexSelect),
3548        Op::Gather { .. } => Some(OpKind::Gather),
3549        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::ROPE => Some(OpKind::Rope),
3550        Op::IndexAdd { .. } => Some(OpKind::IndexAdd),
3551        Op::ScatterAdd { .. } => Some(OpKind::ScatterAdd),
3552        Op::NonZeroIndices { .. } => Some(OpKind::NonZeroIndices),
3553        Op::ArgMaxDim(_) => Some(OpKind::ArgMaxDim),
3554        Op::ArgMinDim(_) => Some(OpKind::ArgMinDim),
3555        // Phase 7.6 step 5 (final): legacy `Op::QMatMul` arm dropped.
3556        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::QMATMUL => {
3557            Some(OpKind::QMatMul)
3558        }
3559        Op::WriteSlice { .. } => Some(OpKind::WriteSlice),
3560        Op::WriteSliceRotating { .. } => Some(OpKind::WriteSliceRotating),
3561        Op::WriteSliceDoff { .. } => Some(OpKind::WriteSliceDoff),
3562        // Phase 2 of bridge-retirement (post-9c): Op::Copy dispatches
3563        // through the binding table at OpKind::Copy. The BackendId
3564        // axis encodes the source backend (the kernel runs there —
3565        // download from local memory). The executor handles output
3566        // allocation on the target via a dedicated WorkItemKind::Copy
3567        // arm, since target_location differs from target_backend for
3568        // this op (the only one with that property today).
3569        Op::Copy { .. } => Some(OpKind::Copy),
3570        // Op::Move dispatches the same data-movement kernel as
3571        // Op::Copy — the destructive release of the source is
3572        // realize-loop bookkeeping (`destructive_input` cleanup), not
3573        // a kernel. Same OpKind, same source-backend key convention.
3574        // `compile_plan` skips both (residency-determined, not a
3575        // picker decision).
3576        Op::Move { .. } => Some(OpKind::Copy),
3577        // Phase 3 of the in-place ops infrastructure: each in-place Op
3578        // variant maps to its OpKind so the binding-table dispatch can
3579        // resolve a kernel. The executor's dedicated WorkItemKind
3580        // arms (added alongside) handle the storage-Arc adoption.
3581        Op::ReluInplace => Some(OpKind::ReluInplace),
3582        Op::SiluInplace => Some(OpKind::SiluInplace),
3583        Op::GeluTanhInplace => Some(OpKind::GeluTanhInplace),
3584        Op::TanhInplace => Some(OpKind::TanhInplace),
3585        Op::SigmoidInplace => Some(OpKind::SigmoidInplace),
3586        Op::NegInplace => Some(OpKind::NegInplace),
3587        Op::AbsInplace => Some(OpKind::AbsInplace),
3588        Op::SqrInplace => Some(OpKind::SqrInplace),
3589        Op::SqrtInplace => Some(OpKind::SqrtInplace),
3590        Op::RsqrtInplace => Some(OpKind::RsqrtInplace),
3591        Op::RecipInplace => Some(OpKind::RecipInplace),
3592        Op::ExpInplace => Some(OpKind::ExpInplace),
3593        Op::LogInplace => Some(OpKind::LogInplace),
3594        Op::SinInplace => Some(OpKind::SinInplace),
3595        Op::CosInplace => Some(OpKind::CosInplace),
3596        Op::SignInplace => Some(OpKind::SignInplace),
3597        Op::FloorInplace => Some(OpKind::FloorInplace),
3598        Op::CeilInplace => Some(OpKind::CeilInplace),
3599        Op::RoundInplace => Some(OpKind::RoundInplace),
3600        Op::ErfInplace => Some(OpKind::ErfInplace),
3601        Op::GeluInplace => Some(OpKind::GeluInplace),
3602        Op::ClampInplace { .. } => Some(OpKind::ClampInplace),
3603        Op::PowIInplace(_) => Some(OpKind::PowIInplace),
3604        // In-place binary variants (Add/Sub/Mul/Div/MaskedFill) and
3605        // their OpKind siblings are tracked by a parallel session and
3606        // toggle in and out of the Op enum as that work progresses.
3607        // No multi-output arm references them; nothing to map here in
3608        // the current HEAD.
3609        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::INPLACE_AFFINE => {
3610            Some(OpKind::InplaceAffine)
3611        }
3612        Op::Fused(fid, _)
3613            if *fid == fuel_graph::registry::FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY =>
3614        {
3615            Some(OpKind::FusedSoftmaxCrossEntropy)
3616        }
3617        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::CAUSAL_CONV1D => {
3618            Some(OpKind::CausalConv1d)
3619        }
3620        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SELECTIVE_SCAN => {
3621            Some(OpKind::SelectiveScan)
3622        }
3623        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SSD_CHUNK_SCAN => {
3624            Some(OpKind::SsdChunkScan)
3625        }
3626        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::NF4_MATMUL => {
3627            Some(OpKind::Nf4Matmul)
3628        }
3629        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::AWQ_MATMUL => {
3630            Some(OpKind::AwqMatmul)
3631        }
3632        // Phase 3a (post-9c): Op::Alloc + Op::ZeroFill are structural
3633        // ops dispatched directly via `WorkItemKind::Alloc` /
3634        // `WorkItemKind::ZeroFill` (no binding-table lookup).
3635        // `compile_plan` skips these.
3636        Op::Alloc { .. } | Op::ZeroFill => None,
3637        _ => None,
3638    }
3639}
3640
3641/// Build the [`OpParams`] for `node`'s op. Most ops use
3642/// `OpParams::None`; reductions / matmul / conv / slice carry their
3643/// op-specific extras here. The graph is consulted to read input
3644/// shapes (e.g. reductions need the input shape to walk the
3645/// multi-index — Storage only carries bytes + dtype).
3646///
3647/// Phase C — extends as op families migrate. Returns Err if a
3648/// graph-shape lookup fails (currently can't, but the signature is
3649/// `Result` so future cases needing validation slot in cleanly).
3650/// Encode an `f64` value into the byte pattern of `dtype`. Used by
3651/// `Op::Pad` (Constant mode) to pre-convert the fill value once at
3652/// op_params time, so the kernel itself stays dtype-agnostic.
3653fn encode_value_to_bytes(dtype: DType, value: f64) -> Result<Vec<u8>> {
3654    match dtype {
3655        DType::F32 => Ok((value as f32).to_le_bytes().to_vec()),
3656        DType::F64 => Ok(value.to_le_bytes().to_vec()),
3657        DType::BF16 => Ok(half::bf16::from_f32(value as f32).to_le_bytes().to_vec()),
3658        DType::F16 => Ok(half::f16::from_f32(value as f32).to_le_bytes().to_vec()),
3659        DType::U8 => Ok(vec![value as u8]),
3660        DType::U32 => Ok((value as u32).to_le_bytes().to_vec()),
3661        other => Err(Error::Msg(format!(
3662            "encode_value_to_bytes: dtype {other:?} not yet supported for Pad fill",
3663        ))
3664        .bt()),
3665    }
3666}
3667
3668/// Encode a typed `Scalar` to its little-endian byte representation.
3669/// Used by Op::MaskedFill so the kernel only sees bytes — never has
3670/// to know the value's dtype.
3671fn scalar_to_bytes(s: fuel_ir::Scalar) -> Vec<u8> {
3672    use fuel_ir::Scalar;
3673    match s {
3674        Scalar::U8(v) => vec![v],
3675        Scalar::I8(v) => vec![v as u8],
3676        Scalar::U32(v) => v.to_le_bytes().to_vec(),
3677        Scalar::I16(v) => v.to_le_bytes().to_vec(),
3678        Scalar::I32(v) => v.to_le_bytes().to_vec(),
3679        Scalar::I64(v) => v.to_le_bytes().to_vec(),
3680        Scalar::BF16(v) => v.to_le_bytes().to_vec(),
3681        Scalar::F16(v) => v.to_le_bytes().to_vec(),
3682        Scalar::F32(v) => v.to_le_bytes().to_vec(),
3683        Scalar::F64(v) => v.to_le_bytes().to_vec(),
3684        Scalar::Bool(b) => vec![b as u8],
3685        Scalar::F8E4M3(v) => vec![v.to_bits()],
3686        Scalar::F8E5M2(v) => vec![v.to_bits()],
3687        // OCP-MX E8M0 block scale is a raw byte on the wire (`2^(X-127)`,
3688        // decoded kernel-side); a single byte is its own LE encoding.
3689        Scalar::F8E8M0(v) => vec![v],
3690    }
3691}
3692
3693fn op_to_op_params(
3694    graph: &Graph,
3695    node: &Node,
3696    node_id: NodeId,
3697    layout_cache: &HashMap<NodeId, Layout>,
3698    sym_env: &SymEnv,
3699) -> Result<OpParams> {
3700    // Helper: read an input's layout from the compiler-thread-local
3701    // cache (which is current within the realize call), falling back
3702    // to the graph's side-table if the input wasn't visited (which
3703    // shouldn't happen in topo order, but the fallback keeps the
3704    // path safe).
3705    let input_layout = |input_id: NodeId| -> Layout {
3706        layout_cache
3707            .get(&input_id)
3708            .cloned()
3709            .unwrap_or_else(|| graph.layout(input_id))
3710    };
3711    Ok(match &node.op {
3712        // Phase 7.6 step 5 (final): legacy `Op::QMatMul` arm dropped.
3713        Op::Fused(_, fuel_graph::registry::FusedOpParams::QMatMul { quant_type, k, n }) => {
3714            // Inputs: (activations f32 [..., m, k], weight_bytes
3715            // u32-typed). Output shape (this Node's shape) is
3716            // [..., m, n]. Flatten leading dims into batch_count.
3717            if node.inputs.len() != 2 {
3718                return Err(Error::Msg(format!(
3719                    "Op::QMatMul expects 2 inputs (activations, weight_bytes), got {}",
3720                    node.inputs.len(),
3721                ))
3722                .bt());
3723            }
3724            let act_layout = input_layout(node.inputs[0]);
3725            let act_dims = act_layout.shape().dims();
3726            if act_dims.len() < 2 {
3727                return Err(Error::Msg(format!(
3728                    "Op::QMatMul: activations must be rank ≥ 2, got {act_dims:?}",
3729                ))
3730                .bt());
3731            }
3732            let m = act_dims[act_dims.len() - 2];
3733            let k_act = act_dims[act_dims.len() - 1];
3734            if k_act != *k {
3735                return Err(Error::Msg(format!(
3736                    "Op::QMatMul: activation last dim ({k_act}) must equal Op's k ({k})",
3737                ))
3738                .bt());
3739            }
3740            let batch_count: usize = act_dims[..act_dims.len() - 2].iter().product();
3741            OpParams::QMatMul {
3742                quant_type: *quant_type,
3743                batch_count,
3744                m,
3745                n: *n,
3746                k: *k,
3747            }
3748        }
3749        Op::ArgMaxDim(d) | Op::ArgMinDim(d) => {
3750            // Reuse OpParams::Reduce — same shape contract; the
3751            // single reduce dim is the argmax/argmin axis. Input
3752            // layout flows through KernelRef's `layouts[0]`.
3753            OpParams::Reduce {
3754                dims: vec![*d],
3755                keepdim: false,
3756            }
3757        }
3758        Op::SumDim(d) | Op::MaxDim(d) | Op::MinDim(d) | Op::MeanDim(d) => OpParams::Reduce {
3759            dims: vec![*d],
3760            keepdim: false,
3761        },
3762        Op::SumAll | Op::MaxAll | Op::MinAll | Op::MeanAll => {
3763            let il = input_layout(node.inputs[0]);
3764            let rank = il.shape().rank();
3765            OpParams::Reduce {
3766                dims: (0..rank).collect(),
3767                keepdim: false,
3768            }
3769        }
3770        Op::MatMul => {
3771            // Batched matmul: lhs `[..lhs_batch.., m, k]` @
3772            // rhs `[..rhs_batch.., k, n]` → out `[..lhs_batch.., m, n]`.
3773            // Per-axis the batch dims either match or follow GQA-style
3774            // divisibility (lhs_dim > rhs_dim && lhs_dim % rhs_dim == 0);
3775            // the kernel honors the latter via `rhs_idx = lhs_idx / n_rep`.
3776            if node.inputs.len() != 2 {
3777                return Err(Error::Msg(format!(
3778                    "Op::MatMul expects 2 inputs, got {}",
3779                    node.inputs.len(),
3780                ))
3781                .bt());
3782            }
3783            let lhs = input_layout(node.inputs[0]);
3784            let rhs = input_layout(node.inputs[1]);
3785            let lhs_dims = lhs.shape().dims();
3786            let rhs_dims = rhs.shape().dims();
3787            if lhs_dims.len() < 2 || rhs_dims.len() < 2 {
3788                return Err(Error::Msg(format!(
3789                    "Op::MatMul requires both inputs rank ≥ 2; got lhs={:?} rhs={:?}",
3790                    lhs_dims, rhs_dims,
3791                ))
3792                .bt());
3793            }
3794            if lhs_dims.len() != rhs_dims.len() {
3795                return Err(Error::Msg(format!(
3796                    "Op::MatMul: ranks must match (auto-broadcast happens at \
3797                     graph construction time); got lhs rank {} vs rhs rank {}",
3798                    lhs_dims.len(),
3799                    rhs_dims.len(),
3800                ))
3801                .bt());
3802            }
3803            let rank = lhs_dims.len();
3804            let batch_rank = rank - 2;
3805            // Per-axis validation: equal or GQA-divisible.
3806            for i in 0..batch_rank {
3807                let la = lhs_dims[i];
3808                let ra = rhs_dims[i];
3809                let ok = la == ra || (ra > 0 && la > ra && la % ra == 0);
3810                if !ok {
3811                    return Err(Error::Msg(format!(
3812                        "Op::MatMul: batch dim {i} disallowed combination \
3813                         (lhs={la}, rhs={ra}); must be equal or \
3814                         GQA-divisible (lhs > rhs && lhs % rhs == 0)",
3815                    ))
3816                    .bt());
3817                }
3818            }
3819            let lhs_batch_dims: Vec<usize> = lhs_dims[..batch_rank].to_vec();
3820            let rhs_batch_dims: Vec<usize> = rhs_dims[..batch_rank].to_vec();
3821            let (m, k_lhs) = (lhs_dims[rank - 2], lhs_dims[rank - 1]);
3822            let (k_rhs, n) = (rhs_dims[rank - 2], rhs_dims[rank - 1]);
3823            if k_lhs != k_rhs {
3824                return Err(Error::Msg(format!(
3825                    "Op::MatMul: contracting dims disagree — lhs trailing is \
3826                     [{m}, {k_lhs}], rhs trailing is [{k_rhs}, {n}]",
3827                ))
3828                .bt());
3829            }
3830            // Data-determined-M (sparse-MoE): a side-table row count makes
3831            // `m` the capacity and this the compute count. Dual-path,
3832            // mirroring WriteSlice: resolve in the compile-time SymEnv
3833            // (static / input-determined) now; else DEFER a producer-bound
3834            // sym to execute; else it is a genuine caller error.
3835            let m_compute = match graph.matmul_row_count(node_id) {
3836                None => MatmulM::All,
3837                Some(dyn_m) => match dyn_m.resolve(sym_env) {
3838                    Some(c) => {
3839                        if c > m {
3840                            return Err(Error::Msg(format!(
3841                                "Op::MatMul: resolved row count {c} exceeds capacity {m}",
3842                            ))
3843                            .bt());
3844                        }
3845                        MatmulM::Rows(c)
3846                    }
3847                    None => match dyn_m {
3848                        fuel_ir::DynScalar::Sym(s) if graph.binds_data_determined_sym(s) => {
3849                            MatmulM::Deferred(dyn_m)
3850                        }
3851                        _ => {
3852                            return Err(Error::Msg(format!(
3853                                "Op::MatMul: dynamic row count {dyn_m:?} is unbound in the \
3854                                 SymEnv at compile and no producer binds it (not \
3855                                 data-determined)",
3856                            ))
3857                            .bt());
3858                        }
3859                    },
3860                },
3861            };
3862            OpParams::Matmul {
3863                lhs_batch_dims,
3864                rhs_batch_dims,
3865                m,
3866                n,
3867                k: k_lhs,
3868                m_compute,
3869            }
3870        }
3871        // Phase 7.6 step 4: legacy `Op::FusedLinear` and registry-extended
3872        // `Op::Fused(FUSED_LINEAR, _)` share the same shape contract and
3873        // params encoding (reuses OpParams::Matmul). One body covers both.
3874        op if op_is_fused_linear(op) => {
3875            // Inputs: [a, b, bias]. Same shape semantics as MatMul on
3876            // a/b; bias is rank-1 [N] and broadcasts along all leading
3877            // dims. We reuse OpParams::Matmul (kernel reads bias from
3878            // inputs[2] directly).
3879            if node.inputs.len() != 3 {
3880                return Err(Error::Msg(format!(
3881                    "Op::FusedLinear expects 3 inputs (a, b, bias), got {}",
3882                    node.inputs.len(),
3883                ))
3884                .bt());
3885            }
3886            let lhs = input_layout(node.inputs[0]);
3887            let rhs = input_layout(node.inputs[1]);
3888            let bias = input_layout(node.inputs[2]);
3889            let lhs_dims = lhs.shape().dims();
3890            let rhs_dims = rhs.shape().dims();
3891            let bias_dims = bias.shape().dims();
3892            if lhs_dims.len() < 2 || rhs_dims.len() < 2 {
3893                return Err(Error::Msg(format!(
3894                    "Op::FusedLinear requires both a, b rank ≥ 2; got a={:?} b={:?}",
3895                    lhs_dims, rhs_dims,
3896                ))
3897                .bt());
3898            }
3899            if lhs_dims.len() != rhs_dims.len() {
3900                return Err(Error::Msg(format!(
3901                    "Op::FusedLinear: ranks must match (auto-broadcast happens at \
3902                     graph construction time); got a rank {} vs b rank {}",
3903                    lhs_dims.len(),
3904                    rhs_dims.len(),
3905                ))
3906                .bt());
3907            }
3908            let rank = lhs_dims.len();
3909            let batch_rank = rank - 2;
3910            for i in 0..batch_rank {
3911                let la = lhs_dims[i];
3912                let ra = rhs_dims[i];
3913                let ok = la == ra || (ra > 0 && la > ra && la % ra == 0);
3914                if !ok {
3915                    return Err(Error::Msg(format!(
3916                        "Op::FusedLinear: batch dim {i} disallowed (a={la}, b={ra})",
3917                    ))
3918                    .bt());
3919                }
3920            }
3921            let lhs_batch_dims: Vec<usize> = lhs_dims[..batch_rank].to_vec();
3922            let rhs_batch_dims: Vec<usize> = rhs_dims[..batch_rank].to_vec();
3923            let (m, k_lhs) = (lhs_dims[rank - 2], lhs_dims[rank - 1]);
3924            let (k_rhs, n) = (rhs_dims[rank - 2], rhs_dims[rank - 1]);
3925            if k_lhs != k_rhs {
3926                return Err(Error::Msg(format!(
3927                    "Op::FusedLinear: contracting dims disagree — a trailing is \
3928                     [{m}, {k_lhs}], b trailing is [{k_rhs}, {n}]",
3929                ))
3930                .bt());
3931            }
3932            if bias_dims.len() != 1 || bias_dims[0] != n {
3933                return Err(Error::Msg(format!(
3934                    "Op::FusedLinear: bias must be rank-1 [{n}], got {bias_dims:?}",
3935                ))
3936                .bt());
3937            }
3938            OpParams::Matmul {
3939                lhs_batch_dims,
3940                rhs_batch_dims,
3941                m,
3942                n,
3943                k: k_lhs,
3944                // FusedLinear is always static-M (dense linear layer).
3945                m_compute: MatmulM::All,
3946            }
3947        }
3948        // FusedSoftmaxCrossEntropy: flatten logits `[..., V]` to
3949        // `[n_rows, V]` for the kernel. n_rows is the product of all
3950        // leading dims (≥1 even for rank-1 logits, where targets are
3951        // a scalar). The kernel walks rows internally.
3952        Op::Fused(
3953            _,
3954            fuel_graph::registry::FusedOpParams::FusedSoftmaxCrossEntropy {
3955                reduction,
3956                ignore_index,
3957            },
3958        ) => {
3959            if node.inputs.len() != 2 {
3960                return Err(Error::Msg(format!(
3961                    "FusedSoftmaxCrossEntropy expects 2 inputs (logits, targets), got {}",
3962                    node.inputs.len(),
3963                ))
3964                .bt());
3965            }
3966            let logits_layout = input_layout(node.inputs[0]);
3967            let logits_dims = logits_layout.shape().dims();
3968            if logits_dims.is_empty() {
3969                return Err(Error::Msg(
3970                    "FusedSoftmaxCrossEntropy: logits must have rank ≥ 1".to_string(),
3971                )
3972                .bt());
3973            }
3974            let vocab = *logits_dims.last().unwrap();
3975            let n_rows: usize = logits_dims[..logits_dims.len() - 1]
3976                .iter()
3977                .product::<usize>()
3978                .max(1);
3979            let targets_layout = input_layout(node.inputs[1]);
3980            let target_count: usize = targets_layout
3981                .shape()
3982                .dims()
3983                .iter()
3984                .product::<usize>()
3985                .max(1);
3986            if target_count != n_rows {
3987                return Err(Error::Msg(format!(
3988                    "FusedSoftmaxCrossEntropy: targets element count {target_count} must \
3989                     equal logits row count {n_rows} (logits {logits_dims:?}, targets {:?})",
3990                    targets_layout.shape().dims(),
3991                ))
3992                .bt());
3993            }
3994            OpParams::FusedSoftmaxCrossEntropy {
3995                n_rows,
3996                vocab,
3997                reduction: *reduction,
3998                ignore_index: *ignore_index,
3999            }
4000        }
4001        // CausalConv1d: derive (batch, channels, seq_in, seq_out, kernel)
4002        // from the input layouts. x is `[batch, channels, seq_in]`
4003        // (caller pre-pads with kernel-1 zeros), weight is
4004        // `[channels, 1, kernel]`. seq_out = seq_in - (kernel - 1).
4005        Op::Fused(_, fuel_graph::registry::FusedOpParams::CausalConv1d { use_silu }) => {
4006            if node.inputs.len() != 3 {
4007                return Err(Error::Msg(format!(
4008                    "CausalConv1d expects 3 inputs (x, weight, bias), got {}",
4009                    node.inputs.len(),
4010                ))
4011                .bt());
4012            }
4013            let x_layout = input_layout(node.inputs[0]);
4014            let w_layout = input_layout(node.inputs[1]);
4015            let x_dims = x_layout.shape().dims();
4016            let w_dims = w_layout.shape().dims();
4017            if x_dims.len() != 3 {
4018                return Err(Error::Msg(format!(
4019                    "CausalConv1d: x must be rank 3 [batch, channels, seq+pad], got {x_dims:?}",
4020                ))
4021                .bt());
4022            }
4023            if w_dims.len() != 3 {
4024                return Err(Error::Msg(format!(
4025                    "CausalConv1d: weight must be rank 3 [channels, 1, kernel], got {w_dims:?}",
4026                ))
4027                .bt());
4028            }
4029            let batch = x_dims[0];
4030            let channels = x_dims[1];
4031            let seq_in = x_dims[2];
4032            let kernel = w_dims[2];
4033            if seq_in < kernel - 1 {
4034                return Err(Error::Msg(format!(
4035                    "CausalConv1d: x time dim {seq_in} must be ≥ kernel-1 = {} \
4036                     (caller must pre-pad with kernel-1 zeros)",
4037                    kernel - 1,
4038                ))
4039                .bt());
4040            }
4041            let seq_out = seq_in - (kernel - 1);
4042            OpParams::CausalConv1d {
4043                batch,
4044                channels,
4045                seq_in,
4046                seq_out,
4047                kernel,
4048                use_silu: *use_silu,
4049            }
4050        }
4051        // SelectiveScan: derive (batch, seqlen, dim, dstate) from the
4052        // input layouts. u: [batch, seqlen, dim]; a: [dim, dstate].
4053        Op::Fused(_, fuel_graph::registry::FusedOpParams::SelectiveScan { delta_softplus }) => {
4054            if node.inputs.len() != 5 {
4055                return Err(Error::Msg(format!(
4056                    "SelectiveScan expects 5 inputs (u, delta, a, b, c), got {}",
4057                    node.inputs.len(),
4058                ))
4059                .bt());
4060            }
4061            let u_layout = input_layout(node.inputs[0]);
4062            let a_layout = input_layout(node.inputs[2]);
4063            let u_dims = u_layout.shape().dims();
4064            let a_dims = a_layout.shape().dims();
4065            if u_dims.len() != 3 {
4066                return Err(Error::Msg(format!(
4067                    "SelectiveScan: u must be rank 3 [batch, seqlen, dim], got {u_dims:?}",
4068                ))
4069                .bt());
4070            }
4071            if a_dims.len() != 2 {
4072                return Err(Error::Msg(format!(
4073                    "SelectiveScan: a must be rank 2 [dim, dstate], got {a_dims:?}",
4074                ))
4075                .bt());
4076            }
4077            let batch = u_dims[0];
4078            let seqlen = u_dims[1];
4079            let dim = u_dims[2];
4080            let dstate = a_dims[1];
4081            if a_dims[0] != dim {
4082                return Err(Error::Msg(format!(
4083                    "SelectiveScan: a's first dim {} must equal dim {dim}",
4084                    a_dims[0],
4085                ))
4086                .bt());
4087            }
4088            OpParams::SelectiveScan {
4089                batch,
4090                seqlen,
4091                dim,
4092                dstate,
4093                delta_softplus: *delta_softplus,
4094            }
4095        }
4096        // SsdChunkScan: derive (batch, seqlen, heads, head_dim,
4097        // state_dim) from x and b layouts. x: [batch, seqlen, heads,
4098        // head_dim]; b: [batch, seqlen, heads, state_dim].
4099        Op::Fused(_, fuel_graph::registry::FusedOpParams::SsdChunkScan { chunk_size }) => {
4100            if node.inputs.len() != 5 {
4101                return Err(Error::Msg(format!(
4102                    "SsdChunkScan expects 5 inputs (x, dt, a, b, c), got {}",
4103                    node.inputs.len(),
4104                ))
4105                .bt());
4106            }
4107            let x_layout = input_layout(node.inputs[0]);
4108            let b_layout = input_layout(node.inputs[3]);
4109            let x_dims = x_layout.shape().dims();
4110            let b_dims = b_layout.shape().dims();
4111            if x_dims.len() != 4 {
4112                return Err(Error::Msg(format!(
4113                    "SsdChunkScan: x must be rank 4 [batch, seqlen, heads, head_dim], got {x_dims:?}",
4114                ))
4115                .bt());
4116            }
4117            if b_dims.len() != 4 {
4118                return Err(Error::Msg(format!(
4119                    "SsdChunkScan: b must be rank 4 [batch, seqlen, heads, state_dim], got {b_dims:?}",
4120                ))
4121                .bt());
4122            }
4123            let batch = x_dims[0];
4124            let seqlen = x_dims[1];
4125            let heads = x_dims[2];
4126            let head_dim = x_dims[3];
4127            let state_dim = b_dims[3];
4128            OpParams::SsdChunkScan {
4129                batch,
4130                seqlen,
4131                heads,
4132                head_dim,
4133                state_dim,
4134                chunk_size: *chunk_size,
4135            }
4136        }
4137        // Nf4Matmul: derive (batch, m, n, k) from activations + w_packed
4138        // layouts. activations: [..., m, k] (leading dims flatten into
4139        // batch); w_packed: [n, k/2] U8.
4140        Op::Fused(_, fuel_graph::registry::FusedOpParams::Nf4Matmul { block_size }) => {
4141            if node.inputs.len() != 3 {
4142                return Err(Error::Msg(format!(
4143                    "Nf4Matmul expects 3 inputs (activations, w_packed, absmax), got {}",
4144                    node.inputs.len(),
4145                ))
4146                .bt());
4147            }
4148            let a_layout = input_layout(node.inputs[0]);
4149            let w_layout = input_layout(node.inputs[1]);
4150            let a_dims = a_layout.shape().dims();
4151            let w_dims = w_layout.shape().dims();
4152            if a_dims.len() < 2 {
4153                return Err(Error::Msg(format!(
4154                    "Nf4Matmul: activations must be rank ≥ 2, got {a_dims:?}",
4155                ))
4156                .bt());
4157            }
4158            if w_dims.len() != 2 {
4159                return Err(Error::Msg(format!(
4160                    "Nf4Matmul: w_packed must be rank 2 [n, k/2], got {w_dims:?}",
4161                ))
4162                .bt());
4163            }
4164            let m = a_dims[a_dims.len() - 2];
4165            let k = a_dims[a_dims.len() - 1];
4166            let n = w_dims[0];
4167            let batch: usize = a_dims[..a_dims.len() - 2].iter().product::<usize>().max(1);
4168            if k % 2 != 0 {
4169                return Err(Error::Msg(format!(
4170                    "Nf4Matmul: k={k} must be even (w_packed holds 2 nibbles per byte along k)",
4171                ))
4172                .bt());
4173            }
4174            if k % *block_size != 0 {
4175                return Err(Error::Msg(format!(
4176                    "Nf4Matmul: k={k} must be a multiple of block_size={block_size}",
4177                ))
4178                .bt());
4179            }
4180            if w_dims[1] != k / 2 {
4181                return Err(Error::Msg(format!(
4182                    "Nf4Matmul: w_packed second dim {} must equal k/2 = {}",
4183                    w_dims[1],
4184                    k / 2,
4185                ))
4186                .bt());
4187            }
4188            OpParams::Nf4Matmul {
4189                batch,
4190                m,
4191                n,
4192                k,
4193                block_size: *block_size,
4194            }
4195        }
4196        // AwqMatmul: (batch, m, n, k) from activations [..., m, k] and the
4197        // kernel-layout weight [n, k/8]; the padded zeros/scales widths are the
4198        // op's own build-time invariant (checked by `awq_matmul`).
4199        Op::Fused(
4200            _,
4201            fuel_graph::registry::FusedOpParams::AwqMatmul {
4202                group_size,
4203                split_k_iters,
4204            },
4205        ) => {
4206            if node.inputs.len() != 4 {
4207                return Err(Error::Msg(format!(
4208                    "AwqMatmul expects 4 inputs (activations, weight, zeros, scales), got {}",
4209                    node.inputs.len(),
4210                ))
4211                .bt());
4212            }
4213            let a_layout = input_layout(node.inputs[0]);
4214            let w_layout = input_layout(node.inputs[1]);
4215            let a_dims = a_layout.shape().dims();
4216            let w_dims = w_layout.shape().dims();
4217            if a_dims.len() < 2 {
4218                return Err(Error::Msg(format!(
4219                    "AwqMatmul: activations must be rank ≥ 2, got {a_dims:?}",
4220                ))
4221                .bt());
4222            }
4223            if w_dims.len() != 2 {
4224                return Err(Error::Msg(format!(
4225                    "AwqMatmul: weight must be rank 2 [n, k/8], got {w_dims:?}",
4226                ))
4227                .bt());
4228            }
4229            let m = a_dims[a_dims.len() - 2];
4230            let k = a_dims[a_dims.len() - 1];
4231            let n = w_dims[0];
4232            let batch: usize = a_dims[..a_dims.len() - 2].iter().product::<usize>().max(1);
4233            if k % 8 != 0 || w_dims[1] != k / 8 {
4234                return Err(Error::Msg(format!(
4235                    "AwqMatmul: weight second dim {} must equal k/8 for k={k} (a multiple of 8)",
4236                    w_dims[1],
4237                ))
4238                .bt());
4239            }
4240            OpParams::AwqMatmul {
4241                batch,
4242                m,
4243                n,
4244                k,
4245                group_size: *group_size,
4246                split_k_iters: *split_k_iters,
4247            }
4248        }
4249        // Phase 7.6 step 3: SoftmaxLastDim flows through
4250        // `Op::Fused(FusedOps::SOFTMAX_LAST_DIM, _)`. The
4251        // SOFTMAX_LAST_DIM_BACKWARD variant added in step 6
4252        // follow-up shares the same `outer × last_dim` shape
4253        // contract (input 0 is `y` for forward / forward-output
4254        // for backward; both rank-≥1 with last-dim as the
4255        // reduction axis).
4256        op if op_is_softmax_last_dim(op)
4257            || matches!(op, Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM_BACKWARD) =>
4258        {
4259            let il = input_layout(node.inputs[0]);
4260            let dims = il.shape().dims();
4261            if dims.is_empty() {
4262                return Err(Error::Msg("Op::SoftmaxLastDim requires rank ≥ 1".to_string()).bt());
4263            }
4264            let last_dim = *dims.last().unwrap();
4265            let outer_count: usize = dims[..dims.len() - 1].iter().product();
4266            OpParams::SoftmaxLastDim {
4267                outer_count,
4268                last_dim,
4269            }
4270        }
4271        Op::Flip { dim } => {
4272            // Single input. Precompute the flat-3-axis split
4273            // (outer × dim × inner) from the input shape.
4274            if node.inputs.len() != 1 {
4275                return Err(Error::Msg(format!(
4276                    "Op::Flip expects 1 input, got {}",
4277                    node.inputs.len(),
4278                ))
4279                .bt());
4280            }
4281            let in_layout = input_layout(node.inputs[0]);
4282            let in_dims = in_layout.shape().dims();
4283            if *dim >= in_dims.len() {
4284                return Err(Error::Msg(format!(
4285                    "Op::Flip: dim {dim} out of range for rank {}",
4286                    in_dims.len(),
4287                ))
4288                .bt());
4289            }
4290            let outer_count: usize = in_dims[..*dim].iter().product();
4291            let dim_size = in_dims[*dim];
4292            let inner_count: usize = in_dims[*dim + 1..].iter().product();
4293            OpParams::Flip {
4294                outer_count,
4295                dim_size,
4296                inner_count,
4297                axis: *dim,
4298            }
4299        }
4300        Op::Roll { dim, shift } => {
4301            if node.inputs.len() != 1 {
4302                return Err(Error::Msg(format!(
4303                    "Op::Roll expects 1 input, got {}",
4304                    node.inputs.len(),
4305                ))
4306                .bt());
4307            }
4308            let in_layout = input_layout(node.inputs[0]);
4309            let in_dims = in_layout.shape().dims();
4310            if *dim >= in_dims.len() {
4311                return Err(Error::Msg(format!(
4312                    "Op::Roll: dim {dim} out of range for rank {}",
4313                    in_dims.len(),
4314                ))
4315                .bt());
4316            }
4317            let outer_count: usize = in_dims[..*dim].iter().product();
4318            let dim_size = in_dims[*dim];
4319            let inner_count: usize = in_dims[*dim + 1..].iter().product();
4320            OpParams::Roll {
4321                outer_count,
4322                dim_size,
4323                inner_count,
4324                shift: *shift,
4325                axis: *dim,
4326            }
4327        }
4328        Op::CumSum { dim } => {
4329            if node.inputs.len() != 1 {
4330                return Err(Error::Msg(format!(
4331                    "Op::CumSum expects 1 input, got {}",
4332                    node.inputs.len(),
4333                ))
4334                .bt());
4335            }
4336            let in_layout = input_layout(node.inputs[0]);
4337            let in_dims = in_layout.shape().dims();
4338            if *dim >= in_dims.len() {
4339                return Err(Error::Msg(format!(
4340                    "Op::CumSum: dim {dim} out of range for rank {}",
4341                    in_dims.len(),
4342                ))
4343                .bt());
4344            }
4345            let outer_count: usize = in_dims[..*dim].iter().product();
4346            let dim_size = in_dims[*dim];
4347            let inner_count: usize = in_dims[*dim + 1..].iter().product();
4348            OpParams::CumSum {
4349                outer_count,
4350                dim_size,
4351                inner_count,
4352                axis: *dim,
4353            }
4354        }
4355        Op::Triu { diagonal } | Op::Tril { diagonal } => {
4356            if node.inputs.len() != 1 {
4357                return Err(Error::Msg(format!(
4358                    "Op::Triu/Tril expects 1 input, got {}",
4359                    node.inputs.len(),
4360                ))
4361                .bt());
4362            }
4363            let in_layout = input_layout(node.inputs[0]);
4364            let in_dims = in_layout.shape().dims();
4365            if in_dims.len() < 2 {
4366                return Err(Error::Msg(format!(
4367                    "Op::Triu/Tril requires rank >= 2, got {}",
4368                    in_dims.len(),
4369                ))
4370                .bt());
4371            }
4372            let rows = in_dims[in_dims.len() - 2];
4373            let cols = in_dims[in_dims.len() - 1];
4374            let batch_count: usize = in_dims[..in_dims.len() - 2]
4375                .iter()
4376                .product::<usize>()
4377                .max(1);
4378            OpParams::Triangular {
4379                batch_count,
4380                rows,
4381                cols,
4382                diagonal: *diagonal,
4383            }
4384        }
4385        Op::LogSoftmaxLastDim => {
4386            if node.inputs.len() != 1 {
4387                return Err(Error::Msg(format!(
4388                    "Op::LogSoftmaxLastDim expects 1 input, got {}",
4389                    node.inputs.len(),
4390                ))
4391                .bt());
4392            }
4393            let in_layout = input_layout(node.inputs[0]);
4394            let in_dims = in_layout.shape().dims();
4395            if in_dims.is_empty() {
4396                return Err(Error::Msg("Op::LogSoftmaxLastDim requires rank ≥ 1".to_string()).bt());
4397            }
4398            let last_dim = *in_dims.last().unwrap();
4399            let outer_count: usize = in_dims[..in_dims.len() - 1].iter().product();
4400            OpParams::LogSoftmaxLastDim {
4401                outer_count,
4402                last_dim,
4403            }
4404        }
4405        Op::LogSoftmaxLastDimBackward => {
4406            // Inputs: (forward_output_y, upstream_grad). Same shape contract
4407            // as SoftmaxLastDimBackward — last-dim row-wise dispatch.
4408            if node.inputs.len() != 2 {
4409                return Err(Error::Msg(format!(
4410                    "Op::LogSoftmaxLastDimBackward expects 2 inputs, got {}",
4411                    node.inputs.len(),
4412                ))
4413                .bt());
4414            }
4415            let in_layout = input_layout(node.inputs[0]);
4416            let in_dims = in_layout.shape().dims();
4417            if in_dims.is_empty() {
4418                return Err(Error::Msg(
4419                    "Op::LogSoftmaxLastDimBackward requires rank ≥ 1".to_string(),
4420                )
4421                .bt());
4422            }
4423            let last_dim = *in_dims.last().unwrap();
4424            let outer_count: usize = in_dims[..in_dims.len() - 1].iter().product();
4425            OpParams::LogSoftmaxLastDim {
4426                outer_count,
4427                last_dim,
4428            }
4429        }
4430        Op::MaskedFill { value } => {
4431            if node.inputs.len() != 2 {
4432                return Err(Error::Msg(format!(
4433                    "Op::MaskedFill expects 2 inputs (x, mask), got {}",
4434                    node.inputs.len(),
4435                ))
4436                .bt());
4437            }
4438            let fill_bytes = scalar_to_bytes(*value);
4439            OpParams::MaskedFill { fill_bytes }
4440        }
4441        // Op::MaskedFillInplace tracked by the parallel in-place
4442        // binary family session — not in HEAD's Op enum right now.
4443        Op::PadBackward {
4444            in_shape,
4445            padding,
4446            mode,
4447        } => {
4448            // Single input is the upstream gradient; output is the
4449            // input gradient (shape == `in_shape`).
4450            if node.inputs.len() != 1 {
4451                return Err(Error::Msg(format!(
4452                    "Op::PadBackward expects 1 input, got {}",
4453                    node.inputs.len(),
4454                ))
4455                .bt());
4456            }
4457            let in_dims: Vec<usize> = in_shape.dims().to_vec();
4458            // Output of the original forward Pad is the input shape
4459            // of the backward (== upstream's shape).
4460            let out_dims: Vec<usize> = in_dims
4461                .iter()
4462                .zip(padding.iter())
4463                .map(|(&d, &(b, a))| d + b + a)
4464                .collect();
4465            let mode_tag: u8 = match mode {
4466                fuel_graph::PadMode::Constant => 0,
4467                fuel_graph::PadMode::Reflect => 1,
4468                fuel_graph::PadMode::Replicate => 2,
4469            };
4470            OpParams::PadBackward {
4471                in_shape: in_dims,
4472                out_shape: out_dims,
4473                padding: padding.clone(),
4474                mode_tag,
4475            }
4476        }
4477        Op::Pad {
4478            padding,
4479            mode,
4480            value,
4481        } => {
4482            if node.inputs.len() != 1 {
4483                return Err(Error::Msg(format!(
4484                    "Op::Pad expects 1 input, got {}",
4485                    node.inputs.len(),
4486                ))
4487                .bt());
4488            }
4489            let in_layout = input_layout(node.inputs[0]);
4490            let in_dims: Vec<usize> = in_layout.shape().dims().to_vec();
4491            if padding.len() != in_dims.len() {
4492                return Err(Error::Msg(format!(
4493                    "Op::Pad: padding.len() ({}) != input rank ({})",
4494                    padding.len(),
4495                    in_dims.len(),
4496                ))
4497                .bt());
4498            }
4499            let out_dims: Vec<usize> = in_dims
4500                .iter()
4501                .zip(padding.iter())
4502                .map(|(&d, &(b, a))| d + b + a)
4503                .collect();
4504            let mode_tag: u8 = match mode {
4505                fuel_graph::PadMode::Constant => 0,
4506                fuel_graph::PadMode::Reflect => 1,
4507                fuel_graph::PadMode::Replicate => 2,
4508            };
4509            // Encode fill value as bytes for the output dtype. The
4510            // kernel is dtype-agnostic — it just memcopies the
4511            // pattern. Conversion happens once here per node, not
4512            // per element in the kernel.
4513            let fill_bytes = encode_value_to_bytes(node.dtype, *value)?;
4514            OpParams::Pad {
4515                in_shape: in_dims,
4516                out_shape: out_dims,
4517                padding: padding.clone(),
4518                mode_tag,
4519                fill_bytes,
4520            }
4521        }
4522        Op::IndexAdd { dim } => {
4523            // Inputs: (base, indices, src). All same dtype except
4524            // indices is U32. Output shape == base shape.
4525            if node.inputs.len() != 3 {
4526                return Err(Error::Msg(format!(
4527                    "Op::IndexAdd expects 3 inputs (base, indices, src), got {}",
4528                    node.inputs.len(),
4529                ))
4530                .bt());
4531            }
4532            let base_layout = input_layout(node.inputs[0]);
4533            let idx_layout = input_layout(node.inputs[1]);
4534            let src_layout = input_layout(node.inputs[2]);
4535            let base_dims = base_layout.shape().dims();
4536            let idx_dims = idx_layout.shape().dims();
4537            let src_dims = src_layout.shape().dims();
4538            if *dim >= base_dims.len() {
4539                return Err(Error::Msg(format!(
4540                    "Op::IndexAdd: dim {dim} out of range for base rank {}",
4541                    base_dims.len(),
4542                ))
4543                .bt());
4544            }
4545            if idx_dims.len() != 1 {
4546                return Err(Error::Msg(format!(
4547                    "Op::IndexAdd: indices must be rank 1, got {idx_dims:?}",
4548                ))
4549                .bt());
4550            }
4551            if base_dims.len() != src_dims.len() {
4552                return Err(Error::Msg(format!(
4553                    "Op::IndexAdd: base rank ({}) != src rank ({})",
4554                    base_dims.len(),
4555                    src_dims.len(),
4556                ))
4557                .bt());
4558            }
4559            let outer_count: usize = base_dims[..*dim].iter().product();
4560            let base_dim_size = base_dims[*dim];
4561            let inner_count: usize = base_dims[*dim + 1..].iter().product();
4562            let n_indices = idx_dims[0];
4563            OpParams::IndexAdd {
4564                outer_count,
4565                base_dim_size,
4566                n_indices,
4567                inner_count,
4568            }
4569        }
4570        Op::ScatterAdd { dim } => {
4571            if node.inputs.len() != 3 {
4572                return Err(Error::Msg(format!(
4573                    "Op::ScatterAdd expects 3 inputs (base, indices, src), got {}",
4574                    node.inputs.len(),
4575                ))
4576                .bt());
4577            }
4578            let base_layout = input_layout(node.inputs[0]);
4579            let src_layout = input_layout(node.inputs[2]);
4580            let base_shape: Vec<usize> = base_layout.shape().dims().to_vec();
4581            let src_shape: Vec<usize> = src_layout.shape().dims().to_vec();
4582            if base_shape.len() != src_shape.len() {
4583                return Err(Error::Msg(format!(
4584                    "Op::ScatterAdd: base rank ({}) != src rank ({})",
4585                    base_shape.len(),
4586                    src_shape.len(),
4587                ))
4588                .bt());
4589            }
4590            if *dim >= base_shape.len() {
4591                return Err(Error::Msg(format!(
4592                    "Op::ScatterAdd: dim {dim} out of range for rank {}",
4593                    base_shape.len(),
4594                ))
4595                .bt());
4596            }
4597            OpParams::ScatterAdd {
4598                base_shape,
4599                src_shape,
4600                dim: *dim,
4601            }
4602        }
4603        // Phase 7.6 step 5: Rope routes through the registry; the
4604        // legacy `Op::Rope` arm was retired with the variant.
4605        Op::Fused(_, fuel_graph::registry::FusedOpParams::Rope) => {
4606            // Inputs: (x, cos, sin). x is [..., seq, head_dim];
4607            // cos/sin are [seq, head_dim] (validated at graph build).
4608            if node.inputs.len() != 3 {
4609                return Err(Error::Msg(format!(
4610                    "Op::Rope expects 3 inputs (x, cos, sin), got {}",
4611                    node.inputs.len(),
4612                ))
4613                .bt());
4614            }
4615            let x_layout = input_layout(node.inputs[0]);
4616            let x_dims = x_layout.shape().dims();
4617            if x_dims.len() < 2 {
4618                return Err(
4619                    Error::Msg(format!("Op::Rope: x must have rank ≥ 2, got {x_dims:?}",)).bt(),
4620                );
4621            }
4622            let head_dim = *x_dims.last().unwrap();
4623            let seq = x_dims[x_dims.len() - 2];
4624            let outer_count: usize = x_dims[..x_dims.len() - 2].iter().product();
4625            OpParams::Rope {
4626                outer_count,
4627                seq,
4628                head_dim,
4629            }
4630        }
4631        Op::Gather { dim } => {
4632            // inputs[0] = source, inputs[1] = U32 indices (same rank).
4633            if node.inputs.len() != 2 {
4634                return Err(Error::Msg(format!(
4635                    "Op::Gather expects 2 inputs (source, indices), got {}",
4636                    node.inputs.len(),
4637                ))
4638                .bt());
4639            }
4640            let src_layout = input_layout(node.inputs[0]);
4641            let idx_layout = input_layout(node.inputs[1]);
4642            let source_shape: Vec<usize> = src_layout.shape().dims().to_vec();
4643            let output_shape: Vec<usize> = idx_layout.shape().dims().to_vec();
4644            if source_shape.len() != output_shape.len() {
4645                return Err(Error::Msg(format!(
4646                    "Op::Gather: source rank ({}) != indices rank ({})",
4647                    source_shape.len(),
4648                    output_shape.len(),
4649                ))
4650                .bt());
4651            }
4652            if *dim >= source_shape.len() {
4653                return Err(Error::Msg(format!(
4654                    "Op::Gather: dim {dim} out of range for rank {}",
4655                    source_shape.len(),
4656                ))
4657                .bt());
4658            }
4659            OpParams::Gather {
4660                source_shape,
4661                output_shape,
4662                dim: *dim,
4663            }
4664        }
4665        Op::NonZeroIndices { count_sym } => {
4666            // inputs[0] = x (the value tensor). capacity == x.elem_count();
4667            // the bundled output is [indices [capacity] U32 ; count [1] U32].
4668            if node.inputs.len() != 1 {
4669                return Err(Error::Msg(format!(
4670                    "Op::NonZeroIndices expects 1 input, got {}",
4671                    node.inputs.len(),
4672                ))
4673                .bt());
4674            }
4675            let x_layout = input_layout(node.inputs[0]);
4676            let capacity = x_layout.shape().elem_count();
4677            OpParams::NonZeroIndices {
4678                capacity,
4679                count_sym: *count_sym,
4680            }
4681        }
4682        Op::IndexSelect { dim } => {
4683            // inputs[0] = source, inputs[1] = U32 indices (rank 1).
4684            if node.inputs.len() != 2 {
4685                return Err(Error::Msg(format!(
4686                    "Op::IndexSelect expects 2 inputs (source, indices), got {}",
4687                    node.inputs.len(),
4688                ))
4689                .bt());
4690            }
4691            let src_layout = input_layout(node.inputs[0]);
4692            let idx_layout = input_layout(node.inputs[1]);
4693            let src_dims = src_layout.shape().dims();
4694            let idx_dims = idx_layout.shape().dims();
4695            if *dim >= src_dims.len() {
4696                return Err(Error::Msg(format!(
4697                    "Op::IndexSelect: dim {dim} out of range for source rank {}",
4698                    src_dims.len(),
4699                ))
4700                .bt());
4701            }
4702            if idx_dims.len() != 1 {
4703                return Err(Error::Msg(format!(
4704                    "Op::IndexSelect: indices must be rank 1, got shape {idx_dims:?}",
4705                ))
4706                .bt());
4707            }
4708            let outer_count: usize = src_dims[..*dim].iter().product();
4709            let source_dim_size = src_dims[*dim];
4710            let inner_count: usize = src_dims[*dim + 1..].iter().product();
4711            let n_indices = idx_dims[0];
4712            OpParams::IndexSelect {
4713                outer_count,
4714                source_dim_size,
4715                n_indices,
4716                inner_count,
4717            }
4718        }
4719        // Phase 7.6 step 5: legacy `Op::RmsNormLastDim` /
4720        // `Op::LayerNormLastDim` arms retired with the variants;
4721        // both now route through `Op::Fused(NORM_LAST_DIM, _)`.
4722        // Step 6 follow-up extends this arm to also cover the
4723        // backward variants (same outer × last_dim + eps geometry).
4724        Op::Fused(fid, params)
4725            if *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM
4726                || *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM
4727                || *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM_BACKWARD
4728                || *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM_BACKWARD =>
4729        {
4730            let eps = match params {
4731                fuel_graph::registry::FusedOpParams::RmsNormLastDim { eps } => *eps,
4732                fuel_graph::registry::FusedOpParams::LayerNormLastDim { eps } => *eps,
4733                fuel_graph::registry::FusedOpParams::RmsNormLastDimBackward { eps } => *eps,
4734                fuel_graph::registry::FusedOpParams::LayerNormLastDimBackward { eps } => *eps,
4735                _ => {
4736                    return Err(Error::Msg(format!(
4737                        "Op::Fused(NORM_LAST_DIM[_BACKWARD], _) expected \
4738                     RmsNormLastDim[Backward] or LayerNormLastDim[Backward] params, got {params:?}",
4739                    ))
4740                    .bt());
4741                }
4742            };
4743            let il = input_layout(node.inputs[0]);
4744            let dims = il.shape().dims();
4745            if dims.is_empty() {
4746                return Err(Error::Msg(
4747                    "Op::Fused(NORM_LAST_DIM[_BACKWARD], _) requires rank ≥ 1".to_string(),
4748                )
4749                .bt());
4750            }
4751            let last_dim = *dims.last().unwrap();
4752            let outer_count: usize = dims[..dims.len() - 1].iter().product();
4753            OpParams::NormLastDim {
4754                outer_count,
4755                last_dim,
4756                eps,
4757            }
4758        }
4759        // ReduceMaxToBackward: shape pair via the new
4760        // OpParams::ReduceMaxToBackward variant. x's shape is
4761        // `input_shape`; upstream's shape is `output_shape`.
4762        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::REDUCE_MAX_TO_BACKWARD => {
4763            if node.inputs.len() != 2 {
4764                return Err(Error::Msg(format!(
4765                    "Op::Fused(REDUCE_MAX_TO_BACKWARD) expects 2 inputs, got {}",
4766                    node.inputs.len(),
4767                ))
4768                .bt());
4769            }
4770            let x_layout = input_layout(node.inputs[0]);
4771            let up_layout = input_layout(node.inputs[1]);
4772            let input_shape: Vec<usize> = x_layout.shape().dims().to_vec();
4773            let output_shape: Vec<usize> = up_layout.shape().dims().to_vec();
4774            OpParams::ReduceMaxToBackward {
4775                input_shape,
4776                output_shape,
4777            }
4778        }
4779        Op::Concat { dim } => {
4780            // Output's shape: [..., total_dim, ...]. Compute outer
4781            // and inner counts from output_shape[..dim] and
4782            // [dim+1..]; per-input dim sizes from each input's
4783            // layout shape at index `dim`.
4784            if node.inputs.is_empty() {
4785                return Err(Error::Msg("Op::Concat requires at least 1 input".to_string()).bt());
4786            }
4787            let out_dims = node.shape.dims();
4788            if *dim >= out_dims.len() {
4789                return Err(Error::Msg(format!(
4790                    "Op::Concat: dim {dim} out of range for output rank {}",
4791                    out_dims.len(),
4792                ))
4793                .bt());
4794            }
4795            let outer_count: usize = out_dims[..*dim].iter().product();
4796            let inner_count: usize = out_dims[*dim + 1..].iter().product();
4797            let mut input_dim_sizes: Vec<usize> = Vec::with_capacity(node.inputs.len());
4798            for in_id in &node.inputs {
4799                let il = input_layout(*in_id);
4800                let il_dims = il.shape().dims();
4801                if *dim >= il_dims.len() {
4802                    return Err(Error::Msg(format!(
4803                        "Op::Concat: input {in_id:?} has rank {} but concat dim is {dim}",
4804                        il_dims.len(),
4805                    ))
4806                    .bt());
4807                }
4808                input_dim_sizes.push(il_dims[*dim]);
4809            }
4810            OpParams::Concat {
4811                outer_count,
4812                input_dim_sizes,
4813                inner_count,
4814                axis: *dim,
4815            }
4816        }
4817        Op::AddScalar(c) => OpParams::Affine { mul: 1.0, add: *c },
4818        Op::MulScalar(c) => OpParams::Affine { mul: *c, add: 0.0 },
4819        Op::Clamp { min, max } => OpParams::Clamp {
4820            min: *min,
4821            max: *max,
4822        },
4823        Op::PowI(exp) => OpParams::PowI { exp: *exp },
4824        Op::ClampInplace { min, max } => OpParams::Clamp {
4825            min: *min,
4826            max: *max,
4827        },
4828        Op::PowIInplace(exp) => OpParams::PowI { exp: *exp },
4829        // PowI backward — `(x, upstream) → grad_x = exp · x^(exp-1) ·
4830        // upstream`. Pulls the same `exp` as the forward through
4831        // FusedOpParams::PowIBackward (autograd carries it across).
4832        Op::Fused(_, fuel_graph::registry::FusedOpParams::PowIBackward { exp }) => {
4833            OpParams::PowI { exp: *exp }
4834        }
4835        // In-place affine (Phase 3 of the in-place ops infrastructure):
4836        // reuse the existing `OpParams::Affine` payload — the kernel
4837        // side doesn't care whether the destination is fresh or aliases
4838        // the input; the structural decision lives in the executor's
4839        // dedicated `WorkItemKind::InplaceKernel` arm.
4840        Op::Fused(_, fuel_graph::registry::FusedOpParams::InplaceAffine { mul, add }) => {
4841            OpParams::Affine {
4842                mul: *mul,
4843                add: *add,
4844            }
4845        }
4846        // Phase 7.6 step 5: legacy `Op::Conv2D` arm retired with the
4847        // variant; Conv2D routes through `Op::Fused(CONV2D, _)`.
4848        Op::Fused(
4849            _,
4850            fuel_graph::registry::FusedOpParams::Conv2D {
4851                stride,
4852                padding,
4853                groups,
4854            },
4855        ) => {
4856            // Inputs[0] = x [N, Cin, Hin, Win]; inputs[1] = weight
4857            // [Cout, Cin/groups, Kh, Kw]; inputs[2] (optional) = bias [Cout].
4858            // Output (this Node's shape) = [N, Cout, Hout, Wout].
4859            if node.inputs.len() != 2 && node.inputs.len() != 3 {
4860                return Err(Error::Msg(format!(
4861                    "Op::Conv2D expects 2 or 3 inputs, got {}",
4862                    node.inputs.len(),
4863                ))
4864                .bt());
4865            }
4866            let x_layout = input_layout(node.inputs[0]);
4867            let w_layout = input_layout(node.inputs[1]);
4868            let x_dims = x_layout.shape().dims();
4869            let w_dims = w_layout.shape().dims();
4870            if x_dims.len() != 4 || w_dims.len() != 4 {
4871                return Err(Error::Msg(format!(
4872                    "Op::Conv2D requires rank-4 x and weight; got x={x_dims:?} w={w_dims:?}",
4873                ))
4874                .bt());
4875            }
4876            let out_dims = node.shape.dims();
4877            if out_dims.len() != 4 {
4878                return Err(Error::Msg(format!(
4879                    "Op::Conv2D output must be rank 4, got {out_dims:?}",
4880                ))
4881                .bt());
4882            }
4883            let x_shape = [x_dims[0], x_dims[1], x_dims[2], x_dims[3]];
4884            let w_shape = [w_dims[0], w_dims[1], w_dims[2], w_dims[3]];
4885            let out_shape = [out_dims[0], out_dims[1], out_dims[2], out_dims[3]];
4886            OpParams::Conv2D {
4887                x_shape,
4888                w_shape,
4889                out_shape,
4890                stride: *stride,
4891                padding: *padding,
4892                dilation: (1, 1),
4893                groups: *groups,
4894            }
4895        }
4896        // Phase 7.6 step 5 (final): legacy `Op::PagedAttn` arm dropped.
4897        Op::Fused(
4898            _,
4899            fuel_graph::registry::FusedOpParams::PagedAttn {
4900                softmax_scale,
4901                block_size,
4902                softcap,
4903            },
4904        ) => {
4905            // Inputs[0]=q [B,Hq,Sq,D], inputs[1]=k_cache [num_blocks,
4906            // block_size, Hkv, D], inputs[2]=v_cache same shape,
4907            // inputs[3]=block_table [B, max_blocks_per_seq] U32,
4908            // inputs[4]=context_lens [B] U32, inputs[5]=alibi [Hq] (optional).
4909            if node.inputs.len() != 5 && node.inputs.len() != 6 {
4910                return Err(Error::Msg(format!(
4911                    "Op::PagedAttn expects 5 or 6 inputs, got {}",
4912                    node.inputs.len(),
4913                ))
4914                .bt());
4915            }
4916            let q_layout = input_layout(node.inputs[0]);
4917            let kc_layout = input_layout(node.inputs[1]);
4918            let vc_layout = input_layout(node.inputs[2]);
4919            let bt_layout = input_layout(node.inputs[3]);
4920            let q_dims = q_layout.shape().dims();
4921            let kc_dims = kc_layout.shape().dims();
4922            let vc_dims = vc_layout.shape().dims();
4923            let bt_dims = bt_layout.shape().dims();
4924            if q_dims.len() != 4 || kc_dims.len() != 4 || vc_dims.len() != 4 {
4925                return Err(Error::Msg(format!(
4926                    "Op::PagedAttn requires rank-4 q/k_cache/v_cache; \
4927                     got q={q_dims:?} k_cache={kc_dims:?} v_cache={vc_dims:?}",
4928                ))
4929                .bt());
4930            }
4931            if kc_dims != vc_dims {
4932                return Err(Error::Msg(format!(
4933                    "Op::PagedAttn: k_cache {kc_dims:?} and v_cache {vc_dims:?} must match",
4934                ))
4935                .bt());
4936            }
4937            if bt_dims.len() != 2 {
4938                return Err(Error::Msg(format!(
4939                    "Op::PagedAttn: block_table must be rank 2 [B, max_blocks_per_seq], got {bt_dims:?}",
4940                ))
4941                .bt());
4942            }
4943            if kc_dims[1] != *block_size {
4944                return Err(Error::Msg(format!(
4945                    "Op::PagedAttn: k_cache block_size dim ({}) must equal Op's block_size ({})",
4946                    kc_dims[1], block_size,
4947                ))
4948                .bt());
4949            }
4950            OpParams::PagedAttn {
4951                b: q_dims[0],
4952                hq: q_dims[1],
4953                hkv: kc_dims[2],
4954                sq: q_dims[2],
4955                d: q_dims[3],
4956                block_size: *block_size,
4957                max_blocks_per_seq: bt_dims[1],
4958                num_blocks: kc_dims[0],
4959                softmax_scale: *softmax_scale,
4960                softcap: *softcap,
4961            }
4962        }
4963        // Phase 7.6 step 5 (final): legacy `Op::FlashAttn` arm dropped.
4964        Op::Fused(
4965            _,
4966            fuel_graph::registry::FusedOpParams::FlashAttn {
4967                softmax_scale,
4968                causal,
4969                window_size_left,
4970                window_size_right,
4971                softcap,
4972                k_len,
4973            },
4974        ) => {
4975            // Inputs[0]=q [B,Hq,Sq,D], inputs[1]=k [B,Hkv,Sk,D],
4976            // inputs[2]=v [B,Hkv,Sk,D], inputs[3]=alibi_slopes [Hq] (optional).
4977            // `sk` is the PHYSICAL K extent (capacity, for strides/bytes);
4978            // `k_len` (resolved below) is the LOGICAL attended length.
4979            if node.inputs.len() != 3 && node.inputs.len() != 4 {
4980                return Err(Error::Msg(format!(
4981                    "Op::FlashAttn expects 3 or 4 inputs, got {}",
4982                    node.inputs.len(),
4983                ))
4984                .bt());
4985            }
4986            let q_layout = input_layout(node.inputs[0]);
4987            let k_layout = input_layout(node.inputs[1]);
4988            let v_layout = input_layout(node.inputs[2]);
4989            let q_dims = q_layout.shape().dims();
4990            let k_dims = k_layout.shape().dims();
4991            let v_dims = v_layout.shape().dims();
4992            if q_dims.len() != 4 || k_dims.len() != 4 || v_dims.len() != 4 {
4993                return Err(Error::Msg(format!(
4994                    "Op::FlashAttn requires rank-4 q/k/v; got q={q_dims:?} k={k_dims:?} v={v_dims:?}",
4995                ))
4996                .bt());
4997            }
4998            if k_dims != v_dims {
4999                return Err(Error::Msg(format!(
5000                    "Op::FlashAttn: k {k_dims:?} and v {v_dims:?} must share shape",
5001                ))
5002                .bt());
5003            }
5004            if q_dims[0] != k_dims[0] || q_dims[3] != k_dims[3] {
5005                return Err(Error::Msg(format!(
5006                    "Op::FlashAttn: q {q_dims:?} and k {k_dims:?} must share B and D",
5007                ))
5008                .bt());
5009            }
5010            let sk = k_dims[2];
5011            // Resolve the logical attended length. `None` ⇒ attend the
5012            // full K extent (today's behavior). `Some(dyn)` ⇒ resolve
5013            // against the per-pass SymEnv; the resolved length must fit
5014            // the capacity and cover Sq (a valid causal prefix).
5015            let attended_k_len = match k_len {
5016                None => sk,
5017                Some(dyn_k) => {
5018                    let kl = dyn_k.resolve(sym_env).ok_or_else(|| {
5019                        Error::Msg(format!(
5020                            "Op::FlashAttn: dynamic k_len {dyn_k:?} is unbound in the SymEnv at realize",
5021                        ))
5022                        .bt()
5023                    })?;
5024                    if kl > sk {
5025                        return Err(Error::Msg(format!(
5026                            "Op::FlashAttn: resolved k_len ({kl}) exceeds K capacity ({sk})",
5027                        ))
5028                        .bt());
5029                    }
5030                    if kl < q_dims[2] {
5031                        return Err(Error::Msg(format!(
5032                            "Op::FlashAttn: resolved k_len ({kl}) < Sq ({}) — not a valid causal prefix",
5033                            q_dims[2],
5034                        ))
5035                        .bt());
5036                    }
5037                    kl
5038                }
5039            };
5040            OpParams::FlashAttn {
5041                b: q_dims[0],
5042                hq: q_dims[1],
5043                hkv: k_dims[1],
5044                sq: q_dims[2],
5045                sk,
5046                d: q_dims[3],
5047                k_len: attended_k_len,
5048                softmax_scale: *softmax_scale,
5049                causal: *causal,
5050                window_size_left: *window_size_left,
5051                window_size_right: *window_size_right,
5052                softcap: *softcap,
5053            }
5054        }
5055        Op::ReduceSumTo(target_shape) => {
5056            if node.inputs.len() != 1 {
5057                return Err(Error::Msg(format!(
5058                    "Op::ReduceSumTo expects 1 input, got {}",
5059                    node.inputs.len(),
5060                ))
5061                .bt());
5062            }
5063            let in_layout = input_layout(node.inputs[0]);
5064            let input_shape: Vec<usize> = in_layout.shape().dims().to_vec();
5065            let output_shape: Vec<usize> = target_shape.dims().to_vec();
5066            OpParams::ReduceSumTo {
5067                input_shape,
5068                output_shape,
5069            }
5070        }
5071        Op::ReduceMaxTo(target_shape) => {
5072            if node.inputs.len() != 1 {
5073                return Err(Error::Msg(format!(
5074                    "Op::ReduceMaxTo expects 1 input, got {}",
5075                    node.inputs.len(),
5076                ))
5077                .bt());
5078            }
5079            let in_layout = input_layout(node.inputs[0]);
5080            let input_shape: Vec<usize> = in_layout.shape().dims().to_vec();
5081            let output_shape: Vec<usize> = target_shape.dims().to_vec();
5082            OpParams::ReduceMaxTo {
5083                input_shape,
5084                output_shape,
5085            }
5086        }
5087        // Phase 7.6 step 5 (final): legacy `Op::ConvTranspose2D` arm dropped.
5088        Op::Fused(
5089            _,
5090            fuel_graph::registry::FusedOpParams::ConvTranspose2D {
5091                stride,
5092                padding,
5093                output_padding,
5094                dilation,
5095                groups,
5096            },
5097        ) => {
5098            // Inputs[0] = x [N, Cin, Hin, Win]; inputs[1] = weight
5099            // [Cin, Cout/groups, Kh, Kw]; inputs[2] (optional) = bias [Cout].
5100            // Output (this Node's shape) = [N, Cout, Hout, Wout].
5101            if node.inputs.len() != 2 && node.inputs.len() != 3 {
5102                return Err(Error::Msg(format!(
5103                    "Op::ConvTranspose2D expects 2 or 3 inputs, got {}",
5104                    node.inputs.len(),
5105                ))
5106                .bt());
5107            }
5108            let x_layout = input_layout(node.inputs[0]);
5109            let w_layout = input_layout(node.inputs[1]);
5110            let x_dims = x_layout.shape().dims();
5111            let w_dims = w_layout.shape().dims();
5112            if x_dims.len() != 4 || w_dims.len() != 4 {
5113                return Err(Error::Msg(format!(
5114                    "Op::ConvTranspose2D requires rank-4 x and weight; got x={x_dims:?} w={w_dims:?}",
5115                ))
5116                .bt());
5117            }
5118            let out_dims = node.shape.dims();
5119            if out_dims.len() != 4 {
5120                return Err(Error::Msg(format!(
5121                    "Op::ConvTranspose2D output must be rank 4, got {out_dims:?}",
5122                ))
5123                .bt());
5124            }
5125            let x_shape = [x_dims[0], x_dims[1], x_dims[2], x_dims[3]];
5126            let w_shape = [w_dims[0], w_dims[1], w_dims[2], w_dims[3]];
5127            let out_shape = [out_dims[0], out_dims[1], out_dims[2], out_dims[3]];
5128            OpParams::ConvTranspose2D {
5129                x_shape,
5130                w_shape,
5131                out_shape,
5132                stride: *stride,
5133                padding: *padding,
5134                output_padding: *output_padding,
5135                dilation: *dilation,
5136                groups: *groups,
5137            }
5138        }
5139        Op::WriteSlice { ranges, dyn_offset } => {
5140            // inputs[0] = destination (its shape == this node's shape
5141            // since WriteSlice's output adopts the destination's
5142            // Layout). inputs[1] = source slab; its shape is implied
5143            // by `ranges`. The kernel needs the destination shape to
5144            // compute strides for the slab walk.
5145            if node.inputs.len() != 2 {
5146                return Err(Error::Msg(format!(
5147                    "Op::WriteSlice expects 2 inputs (destination, source), got {}",
5148                    node.inputs.len(),
5149                ))
5150                .bt());
5151            }
5152            let dest_dims = node.shape.dims().to_vec();
5153            if ranges.len() != dest_dims.len() {
5154                return Err(Error::Msg(format!(
5155                    "Op::WriteSlice: ranges.len() ({}) must equal destination rank ({})",
5156                    ranges.len(),
5157                    dest_dims.len(),
5158                ))
5159                .bt());
5160            }
5161            // Phase D symbolic extents: when present, resolve the runtime
5162            // start offset against the per-pass SymEnv, overriding
5163            // `ranges[axis].0`. The slab WIDTH on that axis stays
5164            // `ranges[axis].1 - ranges[axis].0`, so the effective range
5165            // becomes `(base, base + width)`. `None` ⇒ fully static, and
5166            // the SymEnv is never consulted (empty-env realize unchanged).
5167            //
5168            // DUAL-PATH (increment 2b — data-determined dynamic shapes):
5169            //  - The offset resolves in the compile-time `sym_env` (static,
5170            //    or an INPUT-determined `cached_len`): bake it into `ranges`
5171            //    now, exactly as before.
5172            //  - It is UNBOUND at compile AND a producer in this graph binds
5173            //    it (`Op::NonZeroIndices`'s count, etc.): it is
5174            //    DATA-DETERMINED — leave `ranges[axis]` as the static
5175            //    placeholder and DEFER, carrying the `DynScalar` in
5176            //    `deferred_dyn_offset`. The `WorkItemKind::WriteSlice`
5177            //    executor arm resolves it from `produced_syms` (after the
5178            //    producer runs) and bounds-checks the resolved range there.
5179            //  - It is unbound AND no producer binds it: a genuine caller
5180            //    error → surface it here (preserves the unbound-error path).
5181            let mut ranges = ranges.clone();
5182            let mut deferred_dyn_offset: Option<(usize, fuel_ir::DynScalar)> = None;
5183            if let Some((axis, off)) = dyn_offset {
5184                if *axis >= ranges.len() {
5185                    return Err(Error::Msg(format!(
5186                        "Op::WriteSlice: dyn_offset axis ({axis}) out of bounds for rank {}",
5187                        ranges.len(),
5188                    ))
5189                    .bt());
5190                }
5191                match off.resolve(sym_env) {
5192                    Some(base) => {
5193                        let (start, end) = ranges[*axis];
5194                        let width = end - start;
5195                        ranges[*axis] = (base, base + width);
5196                    }
5197                    None => {
5198                        let is_data_determined = matches!(off, fuel_ir::DynScalar::Sym(s)
5199                            if graph.binds_data_determined_sym(*s));
5200                        if is_data_determined {
5201                            deferred_dyn_offset = Some((*axis, *off));
5202                        } else {
5203                            return Err(Error::Msg(format!(
5204                                "Op::WriteSlice: dynamic offset {off:?} on axis {axis} is \
5205                                 unbound in the SymEnv at realize (and no producer in the \
5206                                 graph binds it, so it is not data-determined)",
5207                            ))
5208                            .bt());
5209                        }
5210                    }
5211                }
5212            }
5213            for (i, &(start, end)) in ranges.iter().enumerate() {
5214                // The deferred axis still holds its static placeholder; the
5215                // executor bounds-checks the resolved range after producing
5216                // the count. Every other axis is fully known now.
5217                if deferred_dyn_offset.is_some_and(|(a, _)| a == i) {
5218                    continue;
5219                }
5220                if end < start || end > dest_dims[i] {
5221                    return Err(Error::Msg(format!(
5222                        "Op::WriteSlice: ranges[{i}] = ({start}, {end}) invalid \
5223                         for destination dim {i} = {}",
5224                        dest_dims[i],
5225                    ))
5226                    .bt());
5227                }
5228            }
5229            OpParams::WriteSlice {
5230                dest_shape: dest_dims,
5231                ranges,
5232                deferred_dyn_offset,
5233            }
5234        }
5235        Op::WriteSliceRotating {
5236            axis,
5237            modulus,
5238            ranges,
5239        } => {
5240            // inputs[0] = destination, inputs[1] = source slab,
5241            // inputs[2] = dynamic position scalar (U32). The builder
5242            // already validated rank / dtype / shape parity; the
5243            // exec-time check below mirrors WriteSlice for the
5244            // structural invariants the executor depends on.
5245            if node.inputs.len() != 3 {
5246                return Err(Error::Msg(format!(
5247                    "Op::WriteSliceRotating expects 3 inputs (destination, source, position), got {}",
5248                    node.inputs.len(),
5249                ))
5250                .bt());
5251            }
5252            let dest_dims = node.shape.dims().to_vec();
5253            if ranges.len() != dest_dims.len() {
5254                return Err(Error::Msg(format!(
5255                    "Op::WriteSliceRotating: ranges.len() ({}) must equal destination rank ({})",
5256                    ranges.len(),
5257                    dest_dims.len(),
5258                ))
5259                .bt());
5260            }
5261            if *axis >= dest_dims.len() {
5262                return Err(Error::Msg(format!(
5263                    "Op::WriteSliceRotating: axis {axis} out of bounds for rank {}",
5264                    dest_dims.len(),
5265                ))
5266                .bt());
5267            }
5268            if *modulus == 0 || *modulus > dest_dims[*axis] {
5269                return Err(Error::Msg(format!(
5270                    "Op::WriteSliceRotating: modulus {modulus} invalid for dest_shape[{axis}] = {}",
5271                    dest_dims[*axis],
5272                ))
5273                .bt());
5274            }
5275            OpParams::WriteSliceRotating {
5276                dest_shape: dest_dims,
5277                axis: *axis,
5278                modulus: *modulus,
5279                ranges: ranges.clone(),
5280            }
5281        }
5282        Op::WriteSliceDoff { axis, ranges } => {
5283            // inputs[0] = destination, inputs[1] = source slab,
5284            // inputs[2] = device-resident I64 offset scalar. The
5285            // builder validated rank / dtype / static-width parity; the
5286            // exec-time check below mirrors WriteSliceRotating minus the
5287            // modulus (no wrap). Bounds on the *dynamic* offset are the
5288            // caller's contract (device-only, un-checkable here).
5289            if node.inputs.len() != 3 {
5290                return Err(Error::Msg(format!(
5291                    "Op::WriteSliceDoff expects 3 inputs (destination, source, offset), got {}",
5292                    node.inputs.len(),
5293                ))
5294                .bt());
5295            }
5296            let dest_dims = node.shape.dims().to_vec();
5297            if ranges.len() != dest_dims.len() {
5298                return Err(Error::Msg(format!(
5299                    "Op::WriteSliceDoff: ranges.len() ({}) must equal destination rank ({})",
5300                    ranges.len(),
5301                    dest_dims.len(),
5302                ))
5303                .bt());
5304            }
5305            if *axis >= dest_dims.len() {
5306                return Err(Error::Msg(format!(
5307                    "Op::WriteSliceDoff: axis {axis} out of bounds for rank {}",
5308                    dest_dims.len(),
5309                ))
5310                .bt());
5311            }
5312            OpParams::WriteSliceDoff {
5313                dest_shape: dest_dims,
5314                axis: *axis,
5315                ranges: ranges.clone(),
5316            }
5317        }
5318        _ => OpParams::None,
5319    })
5320}
5321
5322/// Execute one work item. Three branches by `WorkItemKind`:
5323///
5324/// - `ConstAdopt` — verify cache has an entry pre-seeded by the
5325///   caller; record the layout from the WorkItem.
5326/// - `ViewOf { input }` — clone the input's Storage Arc into the
5327///   output slot (bytes are shared); record the strided layout
5328///   from the WorkItem.
5329/// - `Kernel` — gather input Arcs, allocate the output, run the
5330///   compiled kernel, store the result; record the contiguous
5331///   layout from the WorkItem.
5332///
5333/// Best-effort: prefix a realize-time node error with the failing node's graph
5334/// location — `Graph::describe_node` renders `Node#N (op, out shape, dtype,
5335/// inputs=[...])`, enough to grep-locate the offending op in a large graph. The
5336/// legacy per-node executors (`fuel-graph-executor`, the retired
5337/// `fuel-reference-backend`) wrapped panics this way; the PipelinedExecutor
5338/// surfaces the raw kernel error, so a dtype/shape/OOB failure deep in a model
5339/// arrived with no graph coordinate. On a graph read-lock failure the original
5340/// error passes through unchanged — the location is a navigation aid, never
5341/// worth masking the real error with a lock issue. Zero happy-path cost: only
5342/// the error branch touches the graph.
5343fn with_node_location(graph: &Arc<RwLock<Graph>>, node_id: NodeId, err: Error) -> Error {
5344    match graph.read() {
5345        Ok(g) => err.context(g.describe_node(node_id)),
5346        Err(_) => err,
5347    }
5348}
5349
5350/// Execute one [`WorkItem`] against the cache, returning the node's
5351/// [`CompletionHandle`].
5352///
5353/// Step E A4b-1: the producing arms (Kernel / WriteSlice / WriteSliceRotating /
5354/// in-place / cross-device Copy alloc) return the handle from `execute_compiled`
5355/// *without* waiting it inline — the realize loop stores it in its per-node
5356/// handle map and drains at realize-end. Non-producing arms (const adopt, view,
5357/// slot projection, release marker, contiguize) are pure Arc-clones / host
5358/// allocs whose work is already complete → [`CompletionHandle::Ready`].
5359/// Read a data-determined runtime count from bundle slot 1 of a
5360/// just-realized producer and bind it into the per-pass `SymEnv` under
5361/// `count_sym` — the data-dependent dynamic-shapes seam (increment 2a).
5362/// The producer's bundle is `[indices [capacity] U32 ; count [1] U32]`;
5363/// slot 1's single U32 starts at byte `capacity * 4` (after the
5364/// `capacity`-element U32 primary slot). CPU only for now — device
5365/// backends need a D2H after the completion handle is waited (a documented
5366/// follow-up; the whole data-dependent path is CPU-first). Called AFTER
5367/// `execute_compiled`, whose CPU path returns a `Ready` handle, so the
5368/// bytes are already valid.
5369fn bind_data_determined_count(
5370    arc: &Arc<RwLock<Storage>>,
5371    capacity: usize,
5372    count_sym: fuel_ir::SymId,
5373    produced_syms: &mut SymEnv,
5374) -> Result<()> {
5375    let guard = arc
5376        .read()
5377        .map_err(|_| poisoned("NonZeroIndices output storage"))?;
5378    let count_byte_off = capacity * std::mem::size_of::<u32>();
5379    let end = count_byte_off + std::mem::size_of::<u32>();
5380    // The non-CPU `BackendStorage` variants are cfg-gated; with GPU
5381    // features off, `Cpu` is the only variant and the fallback arm is
5382    // unreachable (a documented CPU-first limitation, not dead logic).
5383    #[allow(unreachable_patterns)]
5384    let count = match &guard.inner {
5385        fuel_memory::BackendStorage::Cpu(cpu_bytes) => {
5386            let bytes = cpu_bytes.bytes();
5387            if end > bytes.len() {
5388                return Err(Error::Msg(format!(
5389                    "NonZeroIndices: count slot byte range [{count_byte_off}..{end}) \
5390                     exceeds bundle byte length {}",
5391                    bytes.len(),
5392                ))
5393                .bt());
5394            }
5395            u32::from_le_bytes(
5396                bytes[count_byte_off..end]
5397                    .try_into()
5398                    .expect("4 bytes → u32"),
5399            )
5400        }
5401        other => {
5402            return Err(Error::Msg(format!(
5403                "NonZeroIndices: data-determined count read is CPU-only today; got \
5404                 BackendStorage::{:?} (device backends need a D2H after the completion \
5405                 handle is waited — a documented follow-up)",
5406                other.backend_id(),
5407            ))
5408            .bt());
5409        }
5410    };
5411    produced_syms.bind(count_sym, count as usize)?;
5412    Ok(())
5413}
5414
5415/// Increment 2b — the consumer half of data-dependent dynamic shapes. When
5416/// a `WriteSlice`'s offset is DATA-DETERMINED (its `SymId` is produced
5417/// mid-pass, so `op_to_op_params` deferred it into
5418/// `OpParams::WriteSlice::deferred_dyn_offset` instead of baking it at
5419/// compile), resolve it HERE from `produced_syms` — populated by the
5420/// producer's execute step (single-threaded topological order guarantees
5421/// the producer already ran). Returns a patched clone of the `CompiledNode`
5422/// with the resolved `ranges` (and `deferred_dyn_offset` cleared) for the
5423/// kernel; `None` when there is nothing to defer (the common path — no
5424/// clone). Bounds-checks the resolved range (deferred past compile).
5425fn resolve_deferred_write_slice(
5426    compiled: &CompiledNode,
5427    produced_syms: &SymEnv,
5428    node_id: NodeId,
5429) -> Result<Option<CompiledNode>> {
5430    let OpParams::WriteSlice {
5431        dest_shape,
5432        ranges,
5433        deferred_dyn_offset,
5434    } = &compiled.op_params
5435    else {
5436        return Ok(None);
5437    };
5438    let Some((axis, off)) = deferred_dyn_offset else {
5439        return Ok(None);
5440    };
5441    let base = off.resolve(produced_syms).ok_or_else(|| {
5442        Error::Msg(format!(
5443            "Op::WriteSlice {node_id:?}: data-determined offset {off:?} on axis {axis} is \
5444             unbound in produced_syms at execute (its producer did not run / bind it)",
5445        ))
5446        .bt()
5447    })?;
5448    let mut ranges = ranges.clone();
5449    let (start, end) = ranges[*axis];
5450    let width = end - start;
5451    let resolved = (base, base + width);
5452    if resolved.1 > dest_shape[*axis] {
5453        return Err(Error::Msg(format!(
5454            "Op::WriteSlice {node_id:?}: resolved data-determined range {resolved:?} on axis \
5455             {axis} exceeds destination dim = {}",
5456            dest_shape[*axis],
5457        ))
5458        .bt());
5459    }
5460    ranges[*axis] = resolved;
5461    let mut patched = compiled.clone();
5462    patched.op_params = OpParams::WriteSlice {
5463        dest_shape: dest_shape.clone(),
5464        ranges,
5465        deferred_dyn_offset: None,
5466    };
5467    Ok(Some(patched))
5468}
5469
5470/// Dynamic-M matmul: when a matmul's row count is DATA-DETERMINED
5471/// (`MatmulM::Deferred`, deferred by `op_to_op_params` because a producer
5472/// binds its `SymId` mid-pass), resolve it HERE from `produced_syms` and
5473/// run the kernel against a patched clone whose `m_compute` is
5474/// `MatmulM::Rows(count)`. Mirrors `resolve_deferred_write_slice`. `None`
5475/// when nothing is deferred (the common path — no clone). The kernel then
5476/// computes exactly `count` rows of the `m`-row capacity buffer.
5477fn resolve_deferred_matmul(
5478    compiled: &CompiledNode,
5479    produced_syms: &SymEnv,
5480    node_id: NodeId,
5481) -> Result<Option<CompiledNode>> {
5482    let OpParams::Matmul {
5483        lhs_batch_dims,
5484        rhs_batch_dims,
5485        m,
5486        n,
5487        k,
5488        m_compute,
5489    } = &compiled.op_params
5490    else {
5491        return Ok(None);
5492    };
5493    let MatmulM::Deferred(dyn_m) = m_compute else {
5494        return Ok(None);
5495    };
5496    let rows = dyn_m.resolve(produced_syms).ok_or_else(|| {
5497        Error::Msg(format!(
5498            "Op::MatMul {node_id:?}: data-determined row count {dyn_m:?} is unbound in \
5499             produced_syms at execute (its producer did not run / bind it)",
5500        ))
5501        .bt()
5502    })?;
5503    if rows > *m {
5504        return Err(Error::Msg(format!(
5505            "Op::MatMul {node_id:?}: resolved row count {rows} exceeds capacity {m}",
5506        ))
5507        .bt());
5508    }
5509    let mut patched = compiled.clone();
5510    patched.op_params = OpParams::Matmul {
5511        lhs_batch_dims: lhs_batch_dims.clone(),
5512        rhs_batch_dims: rhs_batch_dims.clone(),
5513        m: *m,
5514        n: *n,
5515        k: *k,
5516        m_compute: MatmulM::Rows(rows),
5517    };
5518    Ok(Some(patched))
5519}
5520
5521fn execute_work_item(
5522    item: &WorkItem,
5523    cache: &mut StorageCache,
5524    layout_cache: &mut HashMap<NodeId, Layout>,
5525    produced_syms: &mut SymEnv,
5526    // Step E A4b open question #4 — "event only where waited": whether
5527    // THIS item's node id is in the realize's `WaitSet` (`will_be_waited`
5528    // in `pipelined.rs`, computed once per item by the caller). Forwarded
5529    // to every `execute_compiled_with_wait_hint` call below so a CUDA
5530    // kernel with no mid-walk reader skips its `Event` entirely.
5531    will_be_waited: bool,
5532    // CapturedRun executor build-out: persistent-output mode. `None` on
5533    // every existing realize path ⇒ byte-identical (fresh alloc, nothing
5534    // recorded). `Some(Record)` records each Kernel output's fixed Arc;
5535    // `Some(Reuse)` reuses the recorded buffer (no alloc — capture-safe)
5536    // and the write-into kernel path writes into it in place. Only the
5537    // `Kernel` arm consults it; every other arm ignores it.
5538    mut persistent: Option<&mut PersistentOutputs>,
5539) -> Result<CompletionHandle> {
5540    match &item.kind {
5541        WorkItemKind::ConstAdopt => {
5542            if !cache.contains_key(&item.node_id) {
5543                return Err(Error::Msg(format!(
5544                    "PipelinedExecutor: Const node {:?} not in input cache",
5545                    item.node_id
5546                ))
5547                .bt());
5548            }
5549            // Layout for input cache entries was seeded at realize
5550            // start; refresh from the WorkItem in case the side-table
5551            // was set after seeding.
5552            layout_cache.insert(item.node_id, item.output_layout.clone());
5553            Ok(CompletionHandle::Ready)
5554        }
5555        WorkItemKind::ViewOf { input } => {
5556            let input_arc = cache.get(input).cloned().ok_or_else(|| {
5557                Error::Msg(format!(
5558                    "PipelinedExecutor: view-op input {:?} of {:?} not realized",
5559                    input, item.node_id,
5560                ))
5561                .bt()
5562            })?;
5563            cache.insert(item.node_id, input_arc);
5564            layout_cache.insert(item.node_id, item.output_layout.clone());
5565            Ok(CompletionHandle::Ready)
5566        }
5567        WorkItemKind::SlotView { producer } => {
5568            // Op::View — multi-output projection. Same realization
5569            // shape as ViewOf: clone the producer's Storage Arc into
5570            // the View's cache slot. The WorkItem's output_layout was
5571            // computed at graph-build time by `Tensor::view`, with
5572            // the slot's byte_offset baked into start_offset (in
5573            // slot-dtype-element units). Downstream kernels reading
5574            // the producer's bytes as the slot's dtype starting at
5575            // that offset see the slot's typed window.
5576            let producer_arc = cache.get(producer).cloned().ok_or_else(|| {
5577                Error::Msg(format!(
5578                    "PipelinedExecutor: Op::View producer {:?} of {:?} not realized",
5579                    producer, item.node_id,
5580                ))
5581                .bt()
5582            })?;
5583            cache.insert(item.node_id, producer_arc);
5584            layout_cache.insert(item.node_id, item.output_layout.clone());
5585            Ok(CompletionHandle::Ready)
5586        }
5587        WorkItemKind::SlotOwn { producer, slot } => {
5588            // Op::ViewOwned — allocate a fresh Storage of the slot's
5589            // (shape, dtype) on the producer's device and copy the
5590            // slot's bytes in. Per-backend fast paths:
5591            //   - CPU:    direct &[u8]→&mut[u8] memcpy via CpuStorageBytes
5592            //   - CUDA:   D2D via CudaStorageBytes::slot_copy_to_new
5593            //             (cuMemcpyDtoDAsync with offset src pointer)
5594            //   - Vulkan: vkCmdCopyBuffer via
5595            //             VulkanBackend::slot_copy_to_new_handle
5596            //             (srcOffset/dstOffset/size)
5597            // For backends without a copy-with-offset hook we fall
5598            // back to a host round-trip (`to_host_buffer_dyn` →
5599            // slice → `storage_from_host_buffer_owned_dyn`), which
5600            // works but is wasteful.
5601            let producer_arc = cache.get(producer).cloned().ok_or_else(|| {
5602                Error::Msg(format!(
5603                    "PipelinedExecutor: Op::ViewOwned producer {:?} of {:?} not realized",
5604                    producer, item.node_id,
5605                ))
5606                .bt()
5607            })?;
5608            let new_storage = {
5609                let guard = producer_arc
5610                    .read()
5611                    .map_err(|_| poisoned("ViewOwned producer storage"))?;
5612                let bundle = guard.bundle().ok_or_else(|| {
5613                    Error::Msg(format!(
5614                        "Op::ViewOwned: producer {:?} has no bundle side-table \
5615                         — the multi-output authoring contract requires \
5616                         Storage::with_bundle / new_bundled at allocation \
5617                         time. Node {:?} slot {} cannot resolve its source.",
5618                        producer, item.node_id, slot,
5619                    ))
5620                    .bt()
5621                })?;
5622                let sv = bundle.get(*slot as usize).cloned().ok_or_else(|| {
5623                    Error::Msg(format!(
5624                        "Op::ViewOwned: slot {} out of range for producer {:?} \
5625                         (bundle has {} slots)",
5626                        slot,
5627                        producer,
5628                        bundle.len(),
5629                    ))
5630                    .bt()
5631                })?;
5632                use fuel_memory::BackendStorage;
5633                match &guard.inner {
5634                    BackendStorage::Cpu(cpu_bytes) => {
5635                        let src_bytes = cpu_bytes.bytes();
5636                        let end = sv.byte_offset + sv.len_bytes();
5637                        if end > src_bytes.len() {
5638                            return Err(Error::Msg(format!(
5639                                "Op::ViewOwned: slot {} byte range [{}..{}) \
5640                                 exceeds producer's CPU byte length {}",
5641                                slot,
5642                                sv.byte_offset,
5643                                end,
5644                                src_bytes.len(),
5645                            ))
5646                            .bt());
5647                        }
5648                        let owned = fuel_cpu_backend::CpuStorageBytes::from_bytes(
5649                            &src_bytes[sv.byte_offset..end],
5650                        );
5651                        fuel_memory::Storage::new(BackendStorage::Cpu(owned), sv.dtype)
5652                    }
5653                    #[cfg(feature = "cuda")]
5654                    BackendStorage::Cuda(cuda_bytes) => {
5655                        let dst = cuda_bytes.slot_copy_to_new(sv.byte_offset, sv.len_bytes())?;
5656                        fuel_memory::Storage::new(BackendStorage::Cuda(dst), sv.dtype)
5657                    }
5658                    #[cfg(feature = "vulkan")]
5659                    BackendStorage::Vulkan(vk_bytes) => {
5660                        let backend = vk_bytes.backend().ok_or_else(|| {
5661                            Error::Msg(format!(
5662                                "Op::ViewOwned: producer {:?} is on Vulkan but \
5663                                 its storage has no VulkanBackend handle. \
5664                                 Storages flowing through the pipelined executor \
5665                                 must be constructed via alloc_bytes_handle / \
5666                                 upload_bytes_handle so the bundle's slot extraction \
5667                                 path can reach the backend.",
5668                                producer,
5669                            ))
5670                            .bt()
5671                        })?;
5672                        let dst = backend.slot_copy_to_new_handle(
5673                            vk_bytes,
5674                            sv.byte_offset,
5675                            sv.len_bytes(),
5676                        )?;
5677                        fuel_memory::Storage::new(BackendStorage::Vulkan(dst), sv.dtype)
5678                    }
5679                    #[allow(unreachable_patterns)]
5680                    _ => {
5681                        return Err(Error::Msg(format!(
5682                            "Op::ViewOwned: producer {:?} is on a backend \
5683                             without a slot-copy-with-offset hook \
5684                             (CPU + CUDA + Vulkan wired). Add a per-backend \
5685                             `slot_copy_to_new`-equivalent and extend the \
5686                             match arm.",
5687                            producer,
5688                        ))
5689                        .bt());
5690                    }
5691                }
5692            };
5693            cache.insert(item.node_id, Arc::new(RwLock::new(new_storage)));
5694            layout_cache.insert(item.node_id, item.output_layout.clone());
5695            // A4b-1: Op::ViewOwned's slot copy (CUDA D2D) is same-stream; its
5696            // completion is carried by the realize-end full-stream sync in
5697            // `to_cpu_bytes` (unchanged) — `Ready` here is behavior-preserving.
5698            Ok(CompletionHandle::Ready)
5699        }
5700        WorkItemKind::WriteSlice { dest, source } => {
5701            let compiled = item.compiled.as_ref().ok_or_else(|| {
5702                Error::Msg(format!(
5703                    "PipelinedExecutor: WriteSlice work item {:?} has no compiled node",
5704                    item.node_id,
5705                ))
5706                .bt()
5707            })?;
5708            // Increment 2b: if the offset is DATA-DETERMINED, resolve it from
5709            // the producer-bound `produced_syms` and run the kernel against
5710            // the patched (resolved-range) node. `None` on the common path.
5711            let patched_ws = resolve_deferred_write_slice(compiled, produced_syms, item.node_id)?;
5712            let compiled = patched_ws.as_ref().unwrap_or(compiled);
5713            let dest_arc = cache.get(dest).cloned().ok_or_else(|| {
5714                Error::Msg(format!(
5715                    "PipelinedExecutor: WriteSlice destination {:?} of {:?} not realized",
5716                    dest, item.node_id,
5717                ))
5718                .bt()
5719            })?;
5720            let source_arc = cache.get(source).cloned().ok_or_else(|| {
5721                Error::Msg(format!(
5722                    "PipelinedExecutor: WriteSlice source {:?} of {:?} not realized",
5723                    source, item.node_id,
5724                ))
5725                .bt()
5726            })?;
5727            let dest_layout = layout_cache.get(dest).cloned().ok_or_else(|| {
5728                Error::Msg(format!(
5729                    "PipelinedExecutor: WriteSlice destination {:?} of {:?} has no cached layout",
5730                    dest, item.node_id,
5731                ))
5732                .bt()
5733            })?;
5734            let source_layout = layout_cache.get(source).cloned().ok_or_else(|| {
5735                Error::Msg(format!(
5736                    "PipelinedExecutor: WriteSlice source {:?} of {:?} has no cached layout",
5737                    source, item.node_id,
5738                ))
5739                .bt()
5740            })?;
5741            // v1 contract: destination must be contiguous + zero
5742            // offset. Strided dests would force the kernel to walk
5743            // both source and dest strides; defer until KV cache
5744            // exposes a non-contig dest. Source CAN be non-contig —
5745            // we auto-contiguize it here so the kernel sees a flat
5746            // slab.
5747            if !dest_layout.is_contiguous() || dest_layout.start_offset() != 0 {
5748                return Err(Error::Msg(format!(
5749                    "Op::WriteSlice (Phase E.3.2 v1): destination {:?} must be \
5750                     contiguous + zero-offset; got Layout {:?}",
5751                    dest, dest_layout,
5752                ))
5753                .bt());
5754            }
5755            let source_arc_contig = {
5756                let s_dtype = source_arc
5757                    .read()
5758                    .map_err(|_| poisoned("WriteSlice source storage"))?
5759                    .dtype;
5760                let s_len_bytes = source_arc
5761                    .read()
5762                    .map_err(|_| poisoned("WriteSlice source storage"))?
5763                    .inner
5764                    .len_bytes();
5765                let layout_bytes = source_layout.shape().elem_count() * s_dtype.size_in_bytes();
5766                let bytes_match_shape = s_len_bytes == layout_bytes;
5767                let already_contig = source_layout.is_contiguous()
5768                    && source_layout.start_offset() == 0
5769                    && bytes_match_shape;
5770                if already_contig {
5771                    source_arc
5772                } else {
5773                    auto_contiguize(&source_arc, &source_layout)?
5774                }
5775            };
5776            let source_layout_kernel = fuel_ir::Layout::contiguous(source_layout.shape().clone());
5777            // The kernel sees inputs=[source] and outputs=[dest_arc].
5778            // The dest input slot is intentionally absent — the kernel
5779            // doesn't read from dest; it only writes to its bytes
5780            // through the output slot's write lock.
5781            let input_arcs = vec![source_arc_contig];
5782            let mut output_arcs = vec![dest_arc.clone()];
5783            let kernel_layouts = vec![source_layout_kernel, dest_layout.clone()];
5784            // A4b-1: defer the wait — return the handle to the realize loop.
5785            let handle = execute_compiled_with_wait_hint(
5786                compiled,
5787                &input_arcs,
5788                &mut output_arcs,
5789                &kernel_layouts,
5790                will_be_waited,
5791            )?;
5792            // Adopt the dest Arc at this WriteSlice node's slot. The
5793            // realize loop's destructive_input cleanup evicts the
5794            // dest's own NodeId from the cache afterward — downstream
5795            // readers go through this node's NodeId.
5796            cache.insert(item.node_id, dest_arc);
5797            layout_cache.insert(item.node_id, item.output_layout.clone());
5798            Ok(handle)
5799        }
5800        WorkItemKind::WriteSliceRotating {
5801            dest,
5802            source,
5803            position,
5804        } => {
5805            // Same shape as WriteSlice but with a position input.
5806            // Kernel sees `[source, position]` as inputs; `dest` is the
5807            // pre-allocated output buffer (in-place adoption).
5808            let compiled = item.compiled.as_ref().ok_or_else(|| {
5809                Error::Msg(format!(
5810                    "PipelinedExecutor: WriteSliceRotating work item {:?} has no compiled node",
5811                    item.node_id,
5812                ))
5813                .bt()
5814            })?;
5815            let dest_arc = cache.get(dest).cloned().ok_or_else(|| {
5816                Error::Msg(format!(
5817                    "PipelinedExecutor: WriteSliceRotating destination {:?} of {:?} not realized",
5818                    dest, item.node_id,
5819                ))
5820                .bt()
5821            })?;
5822            let source_arc = cache.get(source).cloned().ok_or_else(|| {
5823                Error::Msg(format!(
5824                    "PipelinedExecutor: WriteSliceRotating source {:?} of {:?} not realized",
5825                    source, item.node_id,
5826                ))
5827                .bt()
5828            })?;
5829            let position_arc = cache.get(position).cloned().ok_or_else(|| {
5830                Error::Msg(format!(
5831                    "PipelinedExecutor: WriteSliceRotating position {:?} of {:?} not realized",
5832                    position, item.node_id,
5833                ))
5834                .bt()
5835            })?;
5836            let dest_layout = layout_cache.get(dest).cloned().ok_or_else(|| {
5837                Error::Msg(format!(
5838                    "PipelinedExecutor: WriteSliceRotating destination {:?} of {:?} has no cached layout",
5839                    dest, item.node_id,
5840                ))
5841                .bt()
5842            })?;
5843            let source_layout = layout_cache.get(source).cloned().ok_or_else(|| {
5844                Error::Msg(format!(
5845                    "PipelinedExecutor: WriteSliceRotating source {:?} of {:?} has no cached layout",
5846                    source, item.node_id,
5847                ))
5848                .bt()
5849            })?;
5850            // v1: destination contiguous + zero offset (same as WriteSlice).
5851            if !dest_layout.is_contiguous() || dest_layout.start_offset() != 0 {
5852                return Err(Error::Msg(format!(
5853                    "Op::WriteSliceRotating (v1): destination {:?} must be \
5854                     contiguous + zero-offset; got Layout {:?}",
5855                    dest, dest_layout,
5856                ))
5857                .bt());
5858            }
5859            let source_arc_contig = {
5860                let s_dtype = source_arc
5861                    .read()
5862                    .map_err(|_| poisoned("WriteSliceRotating source storage"))?
5863                    .dtype;
5864                let s_len_bytes = source_arc
5865                    .read()
5866                    .map_err(|_| poisoned("WriteSliceRotating source storage"))?
5867                    .inner
5868                    .len_bytes();
5869                let layout_bytes = source_layout.shape().elem_count() * s_dtype.size_in_bytes();
5870                let bytes_match_shape = s_len_bytes == layout_bytes;
5871                let already_contig = source_layout.is_contiguous()
5872                    && source_layout.start_offset() == 0
5873                    && bytes_match_shape;
5874                if already_contig {
5875                    source_arc
5876                } else {
5877                    auto_contiguize(&source_arc, &source_layout)?
5878                }
5879            };
5880            let source_layout_kernel = fuel_ir::Layout::contiguous(source_layout.shape().clone());
5881            let position_layout = fuel_ir::Layout::contiguous(fuel_ir::Shape::from_dims(&[]));
5882            let input_arcs = vec![source_arc_contig, position_arc];
5883            let mut output_arcs = vec![dest_arc.clone()];
5884            let kernel_layouts = vec![source_layout_kernel, position_layout, dest_layout.clone()];
5885            // A4b-1: defer the wait — return the handle to the realize loop.
5886            let handle = execute_compiled_with_wait_hint(
5887                compiled,
5888                &input_arcs,
5889                &mut output_arcs,
5890                &kernel_layouts,
5891                will_be_waited,
5892            )?;
5893            cache.insert(item.node_id, dest_arc);
5894            layout_cache.insert(item.node_id, item.output_layout.clone());
5895            Ok(handle)
5896        }
5897        WorkItemKind::WriteSliceDoff {
5898            dest,
5899            source,
5900            offset,
5901        } => {
5902            // Same shape as WriteSliceRotating: kernel sees
5903            // `[source, offset]` as inputs; `dest` is the pre-allocated
5904            // output buffer (in-place adoption). The offset (rank-0
5905            // I64) is passed through as a kernel input — the CUDA
5906            // wrapper threads its device pointer straight to the kernel
5907            // (no D2H), which is what makes a captured graph replay at
5908            // the host-updated position.
5909            let compiled = item.compiled.as_ref().ok_or_else(|| {
5910                Error::Msg(format!(
5911                    "PipelinedExecutor: WriteSliceDoff work item {:?} has no compiled node",
5912                    item.node_id,
5913                ))
5914                .bt()
5915            })?;
5916            let dest_arc = cache.get(dest).cloned().ok_or_else(|| {
5917                Error::Msg(format!(
5918                    "PipelinedExecutor: WriteSliceDoff destination {:?} of {:?} not realized",
5919                    dest, item.node_id,
5920                ))
5921                .bt()
5922            })?;
5923            let source_arc = cache.get(source).cloned().ok_or_else(|| {
5924                Error::Msg(format!(
5925                    "PipelinedExecutor: WriteSliceDoff source {:?} of {:?} not realized",
5926                    source, item.node_id,
5927                ))
5928                .bt()
5929            })?;
5930            let offset_arc = cache.get(offset).cloned().ok_or_else(|| {
5931                Error::Msg(format!(
5932                    "PipelinedExecutor: WriteSliceDoff offset {:?} of {:?} not realized",
5933                    offset, item.node_id,
5934                ))
5935                .bt()
5936            })?;
5937            let dest_layout = layout_cache.get(dest).cloned().ok_or_else(|| {
5938                Error::Msg(format!(
5939                    "PipelinedExecutor: WriteSliceDoff destination {:?} of {:?} has no cached layout",
5940                    dest, item.node_id,
5941                ))
5942                .bt()
5943            })?;
5944            let source_layout = layout_cache.get(source).cloned().ok_or_else(|| {
5945                Error::Msg(format!(
5946                    "PipelinedExecutor: WriteSliceDoff source {:?} of {:?} has no cached layout",
5947                    source, item.node_id,
5948                ))
5949                .bt()
5950            })?;
5951            // v1: destination contiguous + zero offset (same as WriteSlice).
5952            if !dest_layout.is_contiguous() || dest_layout.start_offset() != 0 {
5953                return Err(Error::Msg(format!(
5954                    "Op::WriteSliceDoff (v1): destination {:?} must be \
5955                     contiguous + zero-offset; got Layout {:?}",
5956                    dest, dest_layout,
5957                ))
5958                .bt());
5959            }
5960            let source_arc_contig = {
5961                let s_dtype = source_arc
5962                    .read()
5963                    .map_err(|_| poisoned("WriteSliceDoff source storage"))?
5964                    .dtype;
5965                let s_len_bytes = source_arc
5966                    .read()
5967                    .map_err(|_| poisoned("WriteSliceDoff source storage"))?
5968                    .inner
5969                    .len_bytes();
5970                let layout_bytes = source_layout.shape().elem_count() * s_dtype.size_in_bytes();
5971                let bytes_match_shape = s_len_bytes == layout_bytes;
5972                let already_contig = source_layout.is_contiguous()
5973                    && source_layout.start_offset() == 0
5974                    && bytes_match_shape;
5975                if already_contig {
5976                    source_arc
5977                } else {
5978                    auto_contiguize(&source_arc, &source_layout)?
5979                }
5980            };
5981            let source_layout_kernel = fuel_ir::Layout::contiguous(source_layout.shape().clone());
5982            let offset_layout = fuel_ir::Layout::contiguous(fuel_ir::Shape::from_dims(&[]));
5983            let input_arcs = vec![source_arc_contig, offset_arc];
5984            let mut output_arcs = vec![dest_arc.clone()];
5985            let kernel_layouts = vec![source_layout_kernel, offset_layout, dest_layout.clone()];
5986            // A4b-1: defer the wait — return the handle to the realize loop.
5987            let handle = execute_compiled_with_wait_hint(
5988                compiled,
5989                &input_arcs,
5990                &mut output_arcs,
5991                &kernel_layouts,
5992                will_be_waited,
5993            )?;
5994            cache.insert(item.node_id, dest_arc);
5995            layout_cache.insert(item.node_id, item.output_layout.clone());
5996            Ok(handle)
5997        }
5998        WorkItemKind::Alloc { target_location } => {
5999            // Op::Alloc { target }: allocate a fresh, zero-init storage
6000            // on target_location. No inputs, no kernel call — direct
6001            // executor dispatch. For non-CPU targets we derive the
6002            // per-backend device handle by searching the input cache
6003            // for any storage on the target backend (callers seed this
6004            // via `pipelined_bridge::device_seed_storage`).
6005            // Used only by the Vulkan arm below (alloc_bytes_handle); a
6006            // default-feature build sees it unused. GAP-229: 68161981's
6007            // unused_variables --fix renamed it `_n_bytes` at default
6008            // features and broke `--features vulkan` (E0425). Guard the
6009            // decline instead of the name so the binding stays usable.
6010            #[cfg_attr(not(feature = "vulkan"), allow(unused_variables))]
6011            let n_bytes = item.elem_count * item.dtype.size_in_bytes();
6012            let alloced: Storage = match target_location {
6013                // CPU has no separate uninit alloc primitive in safe
6014                // Rust (`vec![0; n]` is the canonical path). Op::Alloc
6015                // on CPU returns zero-init storage; the following
6016                // Op::ZeroFill is a redundant memset the optimizer
6017                // can elide and LLVM folds away regardless.
6018                DeviceLocation::Cpu => fuel_memory::alloc_cpu_zeroed(item.dtype, item.elem_count)?,
6019                #[cfg(feature = "cuda")]
6020                DeviceLocation::Cuda { gpu_id } => {
6021                    let cuda_dev = find_cuda_device_in_cache(cache, *gpu_id).ok_or_else(|| {
6022                        Error::Msg(format!(
6023                            "Op::Alloc on Cuda {{ gpu_id: {} }}: no CUDA \
6024                             storage in input cache to derive the device \
6025                             handle from. The caller must seed the cache \
6026                             (e.g. via `fuel-core::pipelined_bridge::\
6027                             device_seed_storage`) before realizing.",
6028                            gpu_id,
6029                        ))
6030                        .bt()
6031                    })?;
6032                    // Phase 3a follow-up: true uninit alloc via
6033                    // baracuda alpha.30's unsafe alloc. The bytes are
6034                    // uninit until a subsequent Op::ZeroFill or full-
6035                    // overwrite op runs. The byte-storage Arc has no
6036                    // typed-slice accessor that would dereference
6037                    // uninit bytes.
6038                    let cuda_bytes =
6039                        fuel_cuda_backend::CudaStorageBytes::alloc_uninit(&cuda_dev, n_bytes)?;
6040                    Storage::new(fuel_memory::BackendStorage::Cuda(cuda_bytes), item.dtype)
6041                }
6042                #[cfg(not(feature = "cuda"))]
6043                DeviceLocation::Cuda { .. } => {
6044                    return Err(Error::Msg(
6045                        "Op::Alloc on Cuda but fuel-storage wasn't built \
6046                         with --features cuda"
6047                            .to_string(),
6048                    )
6049                    .bt());
6050                }
6051                #[cfg(feature = "vulkan")]
6052                DeviceLocation::Vulkan { gpu_id } => {
6053                    let backend =
6054                        find_vulkan_backend_in_cache(cache, *gpu_id).ok_or_else(|| {
6055                            Error::Msg(format!(
6056                                "Op::Alloc on Vulkan {{ gpu_id: {} }}: no Vulkan \
6057                             storage in input cache to derive the backend \
6058                             handle from. The caller must seed the cache \
6059                             (e.g. via `fuel-core::pipelined_bridge::\
6060                             device_seed_storage`) before realizing.",
6061                                gpu_id,
6062                            ))
6063                            .bt()
6064                        })?;
6065                    // Phase 3a follow-up: true uninit alloc. The old
6066                    // `upload_bytes_handle(vec![0u8; n])` host-staged
6067                    // zeros (~2× the bandwidth of a device-side fill);
6068                    // we now allocate uninit and rely on a paired
6069                    // Op::ZeroFill (vkCmdFillBuffer) for the
6070                    // initialization. Faster KV-cache init on Vulkan.
6071                    let vk_bytes = backend.alloc_bytes_handle(n_bytes)?;
6072                    Storage::new(fuel_memory::BackendStorage::Vulkan(vk_bytes), item.dtype)
6073                }
6074                #[cfg(not(feature = "vulkan"))]
6075                DeviceLocation::Vulkan { .. } => {
6076                    return Err(Error::Msg(
6077                        "Op::Alloc on Vulkan but fuel-storage wasn't built \
6078                         with --features vulkan"
6079                            .to_string(),
6080                    )
6081                    .bt());
6082                }
6083                other => {
6084                    return Err(Error::Msg(format!(
6085                        "Op::Alloc on {:?}: target not yet wired (CPU + \
6086                         CUDA + Vulkan land in Phase 3a of bridge-retirement; \
6087                         Metal extends when its byte-storage substrate is \
6088                         ready).",
6089                        other,
6090                    ))
6091                    .bt());
6092                }
6093            };
6094            cache.insert(item.node_id, Arc::new(RwLock::new(alloced)));
6095            layout_cache.insert(item.node_id, item.output_layout.clone());
6096            Ok(CompletionHandle::Ready)
6097        }
6098        WorkItemKind::Iota { len } => {
6099            // Op::Iota { len }: 0-input F32 position generator
6100            // [0.0, 1.0, …, (len-1)]. Direct executor dispatch (no kernel /
6101            // binding-table lookup), like WorkItemKind::Alloc. CPU-only
6102            // today — GPU flash-attn keeps its fused kernel, so the alibi
6103            // decomposition (the sole Iota consumer) realizes on CPU.
6104            if item.target_backend != BackendId::Cpu {
6105                return Err(Error::Msg(format!(
6106                    "WorkItemKind::Iota: only CPU is wired today, got {:?}",
6107                    item.target_backend,
6108                ))
6109                .bt());
6110            }
6111            let v: Vec<f32> = (0..*len).map(|i| i as f32).collect();
6112            let iota = fuel_memory::from_slice_cpu(&v);
6113            cache.insert(item.node_id, Arc::new(RwLock::new(iota)));
6114            layout_cache.insert(item.node_id, item.output_layout.clone());
6115            Ok(CompletionHandle::Ready)
6116        }
6117        WorkItemKind::ZeroFill => {
6118            // Op::ZeroFill: in-place zero the input's bytes. Output
6119            // adopts the input's Storage Arc (same Storage; bytes
6120            // are mutated). Direct per-backend dispatch — no kernel
6121            // call, no binding-table lookup.
6122            if item.inputs.len() != 1 {
6123                return Err(Error::Msg(format!(
6124                    "PipelinedExecutor: ZeroFill work item {:?} expects \
6125                     1 input, got {}",
6126                    item.node_id,
6127                    item.inputs.len(),
6128                ))
6129                .bt());
6130            }
6131            let src_id = item.inputs[0];
6132            let src_arc = cache.get(&src_id).cloned().ok_or_else(|| {
6133                Error::Msg(format!(
6134                    "PipelinedExecutor: ZeroFill input {:?} of {:?} \
6135                     not realized",
6136                    src_id, item.node_id,
6137                ))
6138                .bt()
6139            })?;
6140            // Per-backend in-place fill. Acquired the write lock once
6141            // for the duration of the fill — kernels on async backends
6142            // (CUDA / Vulkan) issue the memset and return; the fence
6143            // happens when downstream readers acquire the read lock
6144            // through the executor's standard synchronization path.
6145            {
6146                let mut guard = src_arc
6147                    .write()
6148                    .map_err(|_| poisoned("ZeroFill destination storage"))?;
6149                match &mut guard.inner {
6150                    fuel_memory::BackendStorage::Cpu(c) => {
6151                        let bytes = c.bytes_mut();
6152                        bytes.fill(0);
6153                    }
6154                    #[cfg(feature = "cuda")]
6155                    fuel_memory::BackendStorage::Cuda(c) => {
6156                        c.zero_async()?;
6157                    }
6158                    #[cfg(feature = "vulkan")]
6159                    fuel_memory::BackendStorage::Vulkan(v) => {
6160                        let backend = v
6161                            .backend()
6162                            .ok_or_else(|| {
6163                                Error::Msg(
6164                                    "Op::ZeroFill on Vulkan: input has no \
6165                                 attached backend handle. Storage must \
6166                                 come from VulkanBackend::alloc_bytes_handle \
6167                                 / upload_bytes_handle."
6168                                        .to_string(),
6169                                )
6170                                .bt()
6171                            })?
6172                            .clone();
6173                        backend.fill_bytes_zero(v)?;
6174                    }
6175                    #[allow(unreachable_patterns)]
6176                    other => {
6177                        return Err(Error::Msg(format!(
6178                            "Op::ZeroFill: backend not wired ({other:?}); \
6179                             CPU + CUDA + Vulkan covered, Metal extends \
6180                             when its byte-storage substrate is ready.",
6181                        ))
6182                        .bt());
6183                    }
6184                }
6185            }
6186            // Adopt the (now-zero) Storage Arc at this node's slot.
6187            // Downstream readers go through `node_id`; the original
6188            // input's NodeId is evicted from the cache by the
6189            // realize loop's destructive_input cleanup.
6190            cache.insert(item.node_id, src_arc);
6191            layout_cache.insert(item.node_id, item.output_layout.clone());
6192            // A4b-1: ZeroFill's CUDA memset is same-stream (and Op::Alloc
6193            // typically zero-inits, so this is usually elided). Its completion
6194            // is carried by the realize-end full-stream sync in `to_cpu_bytes`
6195            // (unchanged) and same-stream ordering — `Ready` is behavior-preserving.
6196            Ok(CompletionHandle::Ready)
6197        }
6198        WorkItemKind::Copy { target_location } | WorkItemKind::Move { target_location } => {
6199            // Op::Copy / Op::Move { target }: kernel lookup at
6200            // (OpKind::Copy, [dt, dt], source_backend) — the wrapper
6201            // downloads from its own residency into a freshly-
6202            // allocated output on `target_location`. We auto-
6203            // contiguize the input first so the kernel always sees
6204            // the logical view's bytes (a transpose-view source
6205            // materializes into a contiguous buffer before download).
6206            //
6207            // Move shares this entire data-movement half; its
6208            // destructive half (release the source) is driven by the
6209            // realize loop's `destructive_input` cleanup after this
6210            // arm returns — see `WorkItemKind::Move`.
6211            let op_label = if matches!(item.kind, WorkItemKind::Move { .. }) {
6212                "Move"
6213            } else {
6214                "Copy"
6215            };
6216            let compiled = item.compiled.as_ref().ok_or_else(|| {
6217                Error::Msg(format!(
6218                    "PipelinedExecutor: {op_label} work item {:?} has no compiled node",
6219                    item.node_id,
6220                ))
6221                .bt()
6222            })?;
6223            if item.inputs.len() != 1 {
6224                return Err(Error::Msg(format!(
6225                    "PipelinedExecutor: {op_label} work item {:?} expects 1 input, got {}",
6226                    item.node_id,
6227                    item.inputs.len(),
6228                ))
6229                .bt());
6230            }
6231            let src_id = item.inputs[0];
6232            let src_arc = cache.get(&src_id).cloned().ok_or_else(|| {
6233                Error::Msg(format!(
6234                    "PipelinedExecutor: {op_label} input {:?} of {:?} not realized",
6235                    src_id, item.node_id,
6236                ))
6237                .bt()
6238            })?;
6239            // Multi-output Option C guard: Op::Copy on a bundled
6240            // producer would silently drop the bundle metadata on
6241            // the destination, and the auto-contiguize step below
6242            // would treat the bundle as a flat slot-0-shaped buffer
6243            // and corrupt non-primary slots. Until the per-backend
6244            // whole-bundle-Copy hook lands, point callers at the
6245            // supported per-slot path:
6246            // Op::View → Op::Copy → Op::ViewOwned.
6247            //
6248            // Exception: when the immediate input is an Op::View
6249            // projection (its layout's byte extent is strictly less
6250            // than the bundle's total bytes), the View has already
6251            // narrowed the slab. auto-contiguize walks the View's
6252            // layout and produces a flat slot-shaped buffer that's
6253            // correctly sized — no data loss, no slot corruption.
6254            // The guard only fires when the Copy targets the bundle
6255            // root directly.
6256            {
6257                let guard = src_arc
6258                    .read()
6259                    .map_err(|_| poisoned("Copy source storage"))?;
6260                if guard.is_bundled() {
6261                    let layout_bytes_for_guard = layout_cache
6262                        .get(&src_id)
6263                        .map(|l| l.shape().elem_count() * guard.dtype.size_in_bytes())
6264                        .unwrap_or(usize::MAX);
6265                    let bundle_bytes = guard.inner.len_bytes();
6266                    let is_whole_bundle = layout_bytes_for_guard >= bundle_bytes;
6267                    if is_whole_bundle {
6268                        return Err(Error::Msg(format!(
6269                            "PipelinedExecutor: Op::{op_label} on a bundled producer \
6270                             ({:?}) is not yet supported (Option C followup). \
6271                             Use Op::View → Op::Copy → Op::ViewOwned for \
6272                             per-slot cross-device moves, or wait for the \
6273                             per-backend whole-bundle-Copy hook.",
6274                            src_id,
6275                        ))
6276                        .bt());
6277                    }
6278                }
6279            }
6280            let src_layout = layout_cache.get(&src_id).cloned().ok_or_else(|| {
6281                Error::Msg(format!(
6282                    "PipelinedExecutor: {op_label} input {:?} of {:?} has no cached layout",
6283                    src_id, item.node_id,
6284                ))
6285                .bt()
6286            })?;
6287            let src_dtype = src_arc
6288                .read()
6289                .map_err(|_| poisoned("Copy source storage"))?
6290                .dtype;
6291            let src_len_bytes = src_arc
6292                .read()
6293                .map_err(|_| poisoned("Copy source storage"))?
6294                .inner
6295                .len_bytes();
6296            let layout_bytes = src_layout.shape().elem_count() * src_dtype.size_in_bytes();
6297            let bytes_match_shape = src_len_bytes == layout_bytes;
6298            let already_contig =
6299                src_layout.is_contiguous() && src_layout.start_offset() == 0 && bytes_match_shape;
6300            let src_input = if already_contig {
6301                src_arc
6302            } else {
6303                auto_contiguize(&src_arc, &src_layout)?
6304            };
6305            let kernel_input_layout = fuel_ir::Layout::contiguous(src_layout.shape().clone());
6306            // CapturedRun build-out (4b-ζ): in Reuse (capture/replay) mode,
6307            // reuse the fixed-address buffer recorded during the warm run
6308            // instead of allocating — device allocation is illegal inside a
6309            // capture scope. Only a same-device CUDA target_location ever
6310            // reaches Reuse mode for a Copy node in practice: capture_decode's
6311            // validation loop rejects every Cpu/Vulkan target_location before
6312            // a capture scope is ever entered (Move is rejected unconditionally
6313            // there too), so this arm trusts that invariant rather than
6314            // re-deriving it — the `DeviceLocation::Cuda` guard below is just
6315            // belt-and-suspenders for any other Reuse-mode caller.
6316            let reuse_arc = match &persistent {
6317                Some(p) if p.mode == PersistentMode::Reuse => match target_location {
6318                    DeviceLocation::Cuda { .. } => p.map.get(&item.node_id).cloned(),
6319                    _ => None,
6320                },
6321                _ => None,
6322            };
6323            // Allocate the output on `target_location`. Phase 2
6324            // covered D2H (target=Cpu); Phase 3b extends to H2D
6325            // (target=Cuda / Vulkan from a CPU source). For non-CPU
6326            // targets the executor's Op::Alloc-style device-handle
6327            // search applies (find_cuda_device_in_cache /
6328            // find_vulkan_backend_in_cache); callers seed the cache
6329            // (e.g. `pipelined_bridge::device_seed_storage`) before
6330            // realizing.
6331            // Used only by the Vulkan arm below (alloc_bytes_handle); a
6332            // default-feature build sees it unused. GAP-229: 68161981's
6333            // unused_variables --fix renamed it `_n_bytes` at default
6334            // features and broke `--features vulkan` (E0425). Guard the
6335            // decline instead of the name so the binding stays usable.
6336            #[cfg_attr(not(feature = "vulkan"), allow(unused_variables))]
6337            let n_bytes = item.elem_count * item.dtype.size_in_bytes();
6338            let input_arcs = vec![src_input];
6339            let mut output_arcs = if let Some(arc) = reuse_arc {
6340                vec![arc]
6341            } else {
6342                let output = match target_location {
6343                    DeviceLocation::Cpu => {
6344                        fuel_memory::alloc_cpu_zeroed(item.dtype, item.elem_count)?
6345                    }
6346                    #[cfg(feature = "cuda")]
6347                    DeviceLocation::Cuda { gpu_id } => {
6348                        let cuda_dev =
6349                            find_cuda_device_in_cache(cache, *gpu_id).ok_or_else(|| {
6350                                Error::Msg(format!(
6351                                    "Op::{op_label} on Cuda {{ gpu_id: {} }}: no CUDA \
6352                                 storage in input cache to derive the device \
6353                                 handle from. The caller must seed the cache \
6354                                 (e.g. via `fuel-core::pipelined_bridge::\
6355                                 device_seed_storage`) before realizing an \
6356                                 H2D Op::{op_label}.",
6357                                    gpu_id,
6358                                ))
6359                                .bt()
6360                            })?;
6361                        let cuda_bytes =
6362                            fuel_cuda_backend::CudaStorageBytes::alloc_uninit(&cuda_dev, n_bytes)?;
6363                        Storage::new(fuel_memory::BackendStorage::Cuda(cuda_bytes), item.dtype)
6364                    }
6365                    #[cfg(not(feature = "cuda"))]
6366                    DeviceLocation::Cuda { .. } => {
6367                        return Err(Error::Msg(format!(
6368                            "Op::{op_label} target Cuda but fuel-storage wasn't built \
6369                             with --features cuda",
6370                        ))
6371                        .bt());
6372                    }
6373                    #[cfg(feature = "vulkan")]
6374                    DeviceLocation::Vulkan { gpu_id } => {
6375                        let backend =
6376                            find_vulkan_backend_in_cache(cache, *gpu_id).ok_or_else(|| {
6377                                Error::Msg(format!(
6378                                    "Op::{op_label} on Vulkan {{ gpu_id: {} }}: no Vulkan \
6379                                 storage in input cache to derive the backend \
6380                                 handle from. The caller must seed the cache \
6381                                 (e.g. via `fuel-core::pipelined_bridge::\
6382                                 device_seed_storage`) before realizing an \
6383                                 H2D Op::{op_label}.",
6384                                    gpu_id,
6385                                ))
6386                                .bt()
6387                            })?;
6388                        let vk_bytes = backend.alloc_bytes_handle(n_bytes)?;
6389                        Storage::new(fuel_memory::BackendStorage::Vulkan(vk_bytes), item.dtype)
6390                    }
6391                    #[cfg(not(feature = "vulkan"))]
6392                    DeviceLocation::Vulkan { .. } => {
6393                        return Err(Error::Msg(format!(
6394                            "Op::{op_label} target Vulkan but fuel-storage wasn't built \
6395                             with --features vulkan",
6396                        ))
6397                        .bt());
6398                    }
6399                    other => {
6400                        return Err(Error::Msg(format!(
6401                            "PipelinedExecutor: Op::{op_label} target_location {:?} not yet \
6402                             wired (CPU + CUDA + Vulkan covered; Metal extends when \
6403                             its byte-storage substrate is ready).",
6404                            other
6405                        ))
6406                        .bt());
6407                    }
6408                };
6409                vec![Arc::new(RwLock::new(output))]
6410            };
6411            let kernel_layouts = vec![kernel_input_layout, item.output_layout.clone()];
6412            // A4b-1: defer the wait — return the handle to the realize loop.
6413            let handle = execute_compiled_with_wait_hint(
6414                compiled,
6415                &input_arcs,
6416                &mut output_arcs,
6417                &kernel_layouts,
6418                will_be_waited,
6419            )?;
6420            let arc = output_arcs.into_iter().next().expect("one output");
6421            // CapturedRun build-out (4b-ζ): Record (warm) mode remembers this
6422            // node's fixed output buffer so the capture run reuses the
6423            // identical device address. No-op in Reuse mode (the buffer came
6424            // FROM the map) and in None mode. Mirrors the Kernel arm's
6425            // Record-mode snapshot (above) exactly.
6426            if let Some(p) = persistent.as_deref_mut()
6427                && p.mode == PersistentMode::Record
6428            {
6429                p.map.insert(item.node_id, Arc::clone(&arc));
6430            }
6431            cache.insert(item.node_id, arc);
6432            layout_cache.insert(item.node_id, item.output_layout.clone());
6433            Ok(handle)
6434        }
6435        WorkItemKind::ReleaseMarker => {
6436            // Emit a zero-byte CPU storage at the Release node's
6437            // slot. Per Op::Release's contract the marker is never
6438            // read — this exists so any downstream cache lookup of
6439            // `release_id` resolves rather than failing. The actual
6440            // deallocation of `inputs[0]` is driven by the realize
6441            // loop's `destructive_input` cleanup (Phase B).
6442            let marker = fuel_memory::alloc_cpu_zeroed(item.dtype, 0)?;
6443            cache.insert(item.node_id, Arc::new(RwLock::new(marker)));
6444            layout_cache.insert(item.node_id, item.output_layout.clone());
6445            Ok(CompletionHandle::Ready)
6446        }
6447        WorkItemKind::ContiguizeOf { input } => {
6448            let input_arc = cache.get(input).cloned().ok_or_else(|| {
6449                Error::Msg(format!(
6450                    "PipelinedExecutor: reshape input {:?} of {:?} not realized",
6451                    input, item.node_id,
6452                ))
6453                .bt()
6454            })?;
6455            let input_layout = layout_cache.get(input).cloned().ok_or_else(|| {
6456                Error::Msg(format!(
6457                    "PipelinedExecutor: reshape input {:?} of {:?} has no cached layout",
6458                    input, item.node_id,
6459                ))
6460                .bt()
6461            })?;
6462            // CapturedRun build-out (4b-γ): in Reuse (capture/replay) mode,
6463            // reuse the fixed-address buffer recorded during the warm run —
6464            // device allocation is illegal inside a capture scope. Always
6465            // write-into when reusing (skip the zero-copy-vs-allocate
6466            // branch entirely): a given ContiguizeOf node's zero-copy-ness
6467            // is a static layout/stride property, identical across the warm
6468            // and capture passes (both replay the same compiled item list
6469            // with the same static layouts per capture_decode's own
6470            // design), so if this node ever needed the map entry it
6471            // allocated on warm too and the entry is guaranteed present.
6472            let reuse_arc = match &persistent {
6473                Some(p) if p.mode == PersistentMode::Reuse => p.map.get(&item.node_id).cloned(),
6474                _ => None,
6475            };
6476            let out_arc = if let Some(dest_arc) = reuse_arc {
6477                contiguize_into(&dest_arc, &input_arc, &input_layout)?;
6478                dest_arc
6479            } else if input_layout.is_contiguous() && input_layout.start_offset() == 0 {
6480                // Zero-copy when the input is already contiguous + zero
6481                // offset — never allocates, so Record mode has nothing to
6482                // record for this node (no fixed address to reuse).
6483                input_arc
6484            } else {
6485                // Allocate + copy via the contiguize kernel.
6486                let arc = auto_contiguize(&input_arc, &input_layout)?;
6487                if let Some(p) = persistent.as_deref_mut()
6488                    && p.mode == PersistentMode::Record
6489                {
6490                    p.map.insert(item.node_id, Arc::clone(&arc));
6491                }
6492                arc
6493            };
6494            cache.insert(item.node_id, out_arc);
6495            layout_cache.insert(item.node_id, item.output_layout.clone());
6496            // A4b-1: a materializing contiguize (CUDA) is same-stream; its
6497            // completion is carried by the realize-end full-stream sync in
6498            // `to_cpu_bytes` (unchanged) — `Ready` here is behavior-preserving.
6499            Ok(CompletionHandle::Ready)
6500        }
6501        WorkItemKind::Kernel => {
6502            let compiled = item.compiled.as_ref().ok_or_else(|| {
6503                Error::Msg(format!(
6504                    "PipelinedExecutor: Kernel work item {:?} has no compiled node",
6505                    item.node_id,
6506                ))
6507                .bt()
6508            })?;
6509            // Dynamic-M matmul (sparse MoE): resolve a DATA-DETERMINED row
6510            // count from the producer-bound `produced_syms` and run against
6511            // the patched (resolved-M) node. `None` on the common path.
6512            let patched_mm = resolve_deferred_matmul(compiled, produced_syms, item.node_id)?;
6513            let compiled = patched_mm.as_ref().unwrap_or(compiled);
6514            // Gather input Arcs from the cache, auto-contiguizing
6515            // any input whose layout is non-contiguous (typically
6516            // produced by an upstream metadata-only view op).
6517            // Today's kernels assume contiguous; this pass keeps
6518            // that invariant true at every kernel call site.
6519            //
6520            // We assemble a parallel `kernel_layouts` vec — the layout
6521            // of the bytes the kernel actually receives. After
6522            // auto-contiguize, that's `Layout::contiguous(shape)` for
6523            // the input's shape; for inputs already contiguous we use
6524            // the cached layout directly. Output layout comes last.
6525            let mut input_arcs: Vec<Arc<RwLock<Storage>>> = Vec::with_capacity(item.inputs.len());
6526            let mut kernel_layouts: Vec<fuel_ir::Layout> =
6527                Vec::with_capacity(item.inputs.len() + 1);
6528            // The kernel's `strided_input` cap lets non-contiguous
6529            // inputs (broadcast, transpose, etc.) flow through without
6530            // materialization — the kernel walks strides itself. Inputs
6531            // with non-zero `start_offset` still go through auto-
6532            // Contiguize today; offset honoring on the byte buffer is
6533            // a separate concern from stride support.
6534            let kernel_handles_strided = compiled.caps.strided_input;
6535            let t_gather = crate::compiled::op_profile::PhaseTimer::start("kernel.gather_inputs");
6536            for in_id in &item.inputs {
6537                let in_arc = cache.get(in_id).cloned().ok_or_else(|| {
6538                    Error::Msg(format!(
6539                        "PipelinedExecutor: input {:?} of {:?} not realized",
6540                        in_id, item.node_id,
6541                    ))
6542                    .bt()
6543                })?;
6544                let in_layout = layout_cache.get(in_id).cloned().ok_or_else(|| {
6545                    Error::Msg(format!(
6546                        "PipelinedExecutor: input {:?} of {:?} has no cached layout",
6547                        in_id, item.node_id,
6548                    ))
6549                    .bt()
6550                })?;
6551                // "Already contig" means more than `is_contiguous()`:
6552                // the LAYOUT's element count must also match the
6553                // STORAGE's byte count for shape-validating kernels
6554                // (concat_cpu, etc.) that read `storage.len_bytes()`.
6555                // A first-N slice view has `is_contiguous() == true`
6556                // (strides match canonical [1] for shape [N]) but its
6557                // storage is the parent's full bytes — too big. In
6558                // that case we auto-contiguize to materialize only
6559                // the view's portion as a fresh storage.
6560                //
6561                // Same constraint applies to strided_ok: kernels that
6562                // declare strided support can walk strided inputs, but
6563                // the byte count check at the kernel surface still
6564                // assumes storage.len_bytes() == layout.elem_count() *
6565                // dtype.size_bytes(). Until kernels universally trust
6566                // layout over storage, we conservatively materialize.
6567                let in_dtype = in_arc.read().map_err(|_| poisoned("input storage"))?.dtype;
6568                let in_len_bytes = in_arc
6569                    .read()
6570                    .map_err(|_| poisoned("input storage"))?
6571                    .inner
6572                    .len_bytes();
6573                let layout_bytes = in_layout.shape().elem_count() * in_dtype.size_in_bytes();
6574                let bytes_match_shape = in_len_bytes == layout_bytes;
6575                let already_contig =
6576                    in_layout.is_contiguous() && in_layout.start_offset() == 0 && bytes_match_shape;
6577                let strided_ok =
6578                    kernel_handles_strided && in_layout.start_offset() == 0 && bytes_match_shape;
6579                if already_contig || strided_ok {
6580                    input_arcs.push(in_arc);
6581                    kernel_layouts.push(in_layout);
6582                } else {
6583                    let contig_arc = auto_contiguize(&in_arc, &in_layout)?;
6584                    input_arcs.push(contig_arc);
6585                    kernel_layouts.push(fuel_ir::Layout::contiguous(in_layout.shape().clone()));
6586                }
6587            }
6588            drop(t_gather);
6589            kernel_layouts.push(item.output_layout.clone());
6590
6591            // Allocate output on the target backend. For GPU backends
6592            // we derive the device handle from the first input —
6593            // every kernel has ≥1 input (Op::Const is handled via
6594            // ConstAdopt, never via Kernel), and an input on the
6595            // target backend carries its own device. This avoids
6596            // threading a device handle through `realize`.
6597            //
6598            // Multi-output (Option C, item 3): when the WorkItem
6599            // carries an `output_bundle`, size the allocation to
6600            // span every slot's bytes (primary-dtype-element count
6601            // rounded up from the bundle's total byte span) and
6602            // attach the bundle metadata after allocation.
6603            let (alloc_elem_count, bundle_to_attach) = match &item.output_bundle {
6604                Some(bundle) => {
6605                    let dtype_bytes = item.dtype.size_in_bytes().max(1);
6606                    let total_bytes = bundle.iter().fold(0usize, |acc, s| {
6607                        let end = s.byte_offset.saturating_add(s.len_bytes());
6608                        acc.max(end)
6609                    });
6610                    let elems = total_bytes.div_ceil(dtype_bytes);
6611                    (elems, Some(Arc::clone(bundle)))
6612                }
6613                None => (item.elem_count, None),
6614            };
6615            // CapturedRun build-out: in Reuse (capture/replay) mode, reuse the
6616            // FIXED-ADDRESS buffer recorded during the warm run instead of
6617            // allocating — device allocation is illegal inside a capture scope,
6618            // and reusing the same address is what makes the captured graph's
6619            // baked kernel arguments valid on replay. In Record (warm) or None
6620            // mode, allocate as usual (below).
6621            let reuse_arc = match &persistent {
6622                Some(p) if p.mode == PersistentMode::Reuse => {
6623                    Some(p.map.get(&item.node_id).cloned().ok_or_else(|| {
6624                        Error::Msg(format!(
6625                            "PipelinedExecutor: capture (reuse) mode has no persistent \
6626                             output buffer for kernel node {:?}; the warm (record) run \
6627                             must realize every kernel node before capture",
6628                            item.node_id,
6629                        ))
6630                        .bt()
6631                    })?)
6632                }
6633                _ => None,
6634            };
6635            let t_alloc = crate::compiled::op_profile::PhaseTimer::start("kernel.alloc_output");
6636            let mut output_arcs = if let Some(arc) = reuse_arc {
6637                vec![arc]
6638            } else {
6639                let output = match item.target_backend {
6640                    BackendId::Cpu => fuel_memory::alloc_cpu_zeroed(item.dtype, alloc_elem_count)?,
6641                    #[cfg(feature = "cuda")]
6642                    BackendId::Cuda => {
6643                        let first_in = input_arcs.first().ok_or_else(|| {
6644                            Error::Msg(format!(
6645                                "PipelinedExecutor: kernel {:?} on Cuda has no inputs; \
6646                             cannot derive device for output allocation",
6647                                item.node_id,
6648                            ))
6649                            .bt()
6650                        })?;
6651                        let guard = first_in.read().map_err(|_| poisoned("input storage"))?;
6652                        let cuda_in = match &guard.inner {
6653                            fuel_memory::BackendStorage::Cuda(c) => c,
6654                            other => {
6655                                return Err(Error::Msg(format!(
6656                                    "PipelinedExecutor: kernel {:?} target_backend=Cuda but \
6657                                 input has BackendStorage::{:?}; mixed-backend kernels \
6658                                 require an explicit Op::Copy first",
6659                                    item.node_id,
6660                                    other.backend_id(),
6661                                ))
6662                                .bt());
6663                            }
6664                        };
6665                        let n_bytes = alloc_elem_count * item.dtype.size_in_bytes();
6666                        let cuda_bytes =
6667                            fuel_cuda_backend::CudaStorageBytes::alloc(cuda_in.device(), n_bytes)?;
6668                        fuel_memory::Storage::new(
6669                            fuel_memory::BackendStorage::Cuda(cuda_bytes),
6670                            item.dtype,
6671                        )
6672                    }
6673                    #[cfg(feature = "vulkan")]
6674                    BackendId::Vulkan => {
6675                        // Mirror the CUDA path: derive the backend handle
6676                        // from the first input's `VulkanStorageBytes::backend()`.
6677                        // Vulkan catch-up V.1.B (2026-05-21) — requires
6678                        // inputs constructed via `alloc_bytes_handle` /
6679                        // `upload_bytes_handle` so they carry the
6680                        // `Arc<VulkanBackend>` (mirroring CUDA's
6681                        // `Arc<CudaDevice>`).
6682                        let first_in = input_arcs.first().ok_or_else(|| {
6683                            Error::Msg(format!(
6684                                "PipelinedExecutor: kernel {:?} on Vulkan has no inputs; \
6685                             cannot derive backend handle for output allocation",
6686                                item.node_id,
6687                            ))
6688                            .bt()
6689                        })?;
6690                        let guard = first_in.read().map_err(|_| poisoned("input storage"))?;
6691                        let vk_in = match &guard.inner {
6692                            fuel_memory::BackendStorage::Vulkan(v) => v,
6693                            other => {
6694                                return Err(Error::Msg(format!(
6695                                    "PipelinedExecutor: kernel {:?} target_backend=Vulkan but \
6696                                 input has BackendStorage::{:?}; mixed-backend kernels \
6697                                 require an explicit Op::Copy first",
6698                                    item.node_id,
6699                                    other.backend_id(),
6700                                ))
6701                                .bt());
6702                            }
6703                        };
6704                        let backend = vk_in.backend().ok_or_else(|| {
6705                            Error::Msg(format!(
6706                                "PipelinedExecutor: Vulkan kernel {:?} input has no backend \
6707                             handle. Storages flowing through the pipelined executor's \
6708                             Vulkan path must be constructed via \
6709                             VulkanBackend::alloc_bytes_handle / upload_bytes_handle \
6710                             (not the legacy alloc_bytes / upload_bytes which leave \
6711                             VulkanStorageBytes::backend = None).",
6712                                item.node_id,
6713                            ))
6714                            .bt()
6715                        })?;
6716                        let n_bytes = alloc_elem_count * item.dtype.size_in_bytes();
6717                        let vk_bytes = backend.alloc_bytes_handle(n_bytes)?;
6718                        fuel_memory::Storage::new(
6719                            fuel_memory::BackendStorage::Vulkan(vk_bytes),
6720                            item.dtype,
6721                        )
6722                    }
6723                    other => {
6724                        return Err(Error::Msg(format!(
6725                            "PipelinedExecutor: target_backend {:?} output allocation \
6726                         not yet implemented (CPU + CUDA + Vulkan wired; Metal extends later)",
6727                            other
6728                        ))
6729                        .bt());
6730                    }
6731                };
6732                // Attach bundle metadata when this is a multi-output op.
6733                // The kernel sees the allocated bytes; the bundle lives
6734                // at the Storage wrapper level so downstream Op::View /
6735                // Op::ViewOwned can resolve their slot windows.
6736                let output = match bundle_to_attach {
6737                    Some(bundle) => output.with_bundle(bundle)?,
6738                    None => output,
6739                };
6740                vec![Arc::new(RwLock::new(output))]
6741            };
6742            drop(t_alloc);
6743
6744            // A4b-1: defer the wait — return the handle to the realize loop.
6745            let t_launch =
6746                crate::compiled::op_profile::PhaseTimer::start("kernel.execute_compiled");
6747            let handle = execute_compiled_with_wait_hint(
6748                compiled,
6749                &input_arcs,
6750                &mut output_arcs,
6751                &kernel_layouts,
6752                will_be_waited,
6753            )?;
6754            drop(t_launch);
6755
6756            let arc = output_arcs.into_iter().next().expect("one output");
6757
6758            // CapturedRun build-out: Record (warm) mode remembers this node's
6759            // fixed output buffer so the capture run reuses the identical
6760            // device address. No-op in Reuse mode (the buffer came FROM the
6761            // map) and in None mode.
6762            if let Some(p) = persistent
6763                && p.mode == PersistentMode::Record
6764            {
6765                p.map.insert(item.node_id, Arc::clone(&arc));
6766            }
6767
6768            // Data-determined dynamic-shapes seam (increment 2a): a
6769            // producer that computes a runtime count publishes it into the
6770            // per-pass `SymEnv` so downstream ops can consume it as a
6771            // dynamic extent. `Op::NonZeroIndices` writes its count into
6772            // bundle slot 1; read it back and bind `count_sym`. This is the
6773            // FIRST op to bind a *data-determined* symbol mid-realize (all
6774            // prior binds are host-known before realize). Single-threaded:
6775            // the executor runs items topologically, so this bind precedes
6776            // any consumer's execute-time resolution.
6777            if let OpParams::NonZeroIndices {
6778                capacity,
6779                count_sym,
6780            } = &compiled.op_params
6781            {
6782                bind_data_determined_count(&arc, *capacity, *count_sym, produced_syms)?;
6783            }
6784
6785            cache.insert(item.node_id, arc);
6786            layout_cache.insert(item.node_id, item.output_layout.clone());
6787            Ok(handle)
6788        }
6789        WorkItemKind::InplaceKernel { target_idx } => {
6790            let compiled = item.compiled.as_ref().ok_or_else(|| {
6791                Error::Msg(format!(
6792                    "PipelinedExecutor: InplaceKernel work item {:?} has no compiled node",
6793                    item.node_id,
6794                ))
6795                .bt()
6796            })?;
6797            let target_id = *item.inputs.get(*target_idx).ok_or_else(|| {
6798                Error::Msg(format!(
6799                    "PipelinedExecutor: InplaceKernel work item {:?} target_idx={} \
6800                     out of bounds (inputs.len()={})",
6801                    item.node_id,
6802                    target_idx,
6803                    item.inputs.len(),
6804                ))
6805                .bt()
6806            })?;
6807            let target_arc = cache.get(&target_id).cloned().ok_or_else(|| {
6808                Error::Msg(format!(
6809                    "PipelinedExecutor: InplaceKernel target {:?} of {:?} not realized",
6810                    target_id, item.node_id,
6811                ))
6812                .bt()
6813            })?;
6814            let target_layout = layout_cache.get(&target_id).cloned().ok_or_else(|| {
6815                Error::Msg(format!(
6816                    "PipelinedExecutor: InplaceKernel target {:?} of {:?} has no cached layout",
6817                    target_id, item.node_id,
6818                ))
6819                .bt()
6820            })?;
6821            // v1 contract: target must be contiguous + zero offset.
6822            // Strided in-place targets would force the kernel to walk
6823            // strides for writes too; defer until a concrete consumer
6824            // needs it (mirrors `Op::WriteSlice`'s v1 dest contract).
6825            if !target_layout.is_contiguous() || target_layout.start_offset() != 0 {
6826                return Err(Error::Msg(format!(
6827                    "InplaceKernel (Phase 3 v1): target {:?} must be contiguous + \
6828                     zero-offset; got Layout {:?}",
6829                    target_id, target_layout,
6830                ))
6831                .bt());
6832            }
6833            // Kernel sees inputs=[non-target IR inputs in order] and
6834            // outputs=[target_arc]. For unary in-place (1 IR input at
6835            // target_idx=0) the input vec is empty, matching the
6836            // original Phase 3e contract. For binary in-place
6837            // (target_idx=0, 2 IR inputs) the wrapper sees the
6838            // non-destructive RHS as `inputs[0]`. The wrapper acquires
6839            // outputs[0]'s write lock and mutates through its
6840            // bytes_mut(). Layout vector contains the kernel's
6841            // inputs+outputs layouts in that order.
6842            let mut input_arcs: Vec<Arc<RwLock<Storage>>> = Vec::new();
6843            let mut kernel_layouts: Vec<Layout> = Vec::new();
6844            for (i, &input_id) in item.inputs.iter().enumerate() {
6845                if i == *target_idx {
6846                    continue;
6847                }
6848                let arc = cache.get(&input_id).cloned().ok_or_else(|| {
6849                    Error::Msg(format!(
6850                        "PipelinedExecutor: InplaceKernel non-target input {:?} of {:?} \
6851                         not realized",
6852                        input_id, item.node_id,
6853                    ))
6854                    .bt()
6855                })?;
6856                let lay = layout_cache.get(&input_id).cloned().ok_or_else(|| {
6857                    Error::Msg(format!(
6858                        "PipelinedExecutor: InplaceKernel non-target input {:?} of {:?} \
6859                         has no cached layout",
6860                        input_id, item.node_id,
6861                    ))
6862                    .bt()
6863                })?;
6864                input_arcs.push(arc);
6865                kernel_layouts.push(lay);
6866            }
6867            let mut output_arcs = vec![target_arc.clone()];
6868            kernel_layouts.push(target_layout.clone());
6869            // A4b-1: defer the wait — return the handle to the realize loop.
6870            let handle = execute_compiled_with_wait_hint(
6871                compiled,
6872                &input_arcs,
6873                &mut output_arcs,
6874                &kernel_layouts,
6875                will_be_waited,
6876            )?;
6877            // Adopt the target Arc at this node's slot. The realize
6878            // loop's destructive_input cleanup evicts the target's own
6879            // NodeId from the cache afterward.
6880            cache.insert(item.node_id, target_arc);
6881            layout_cache.insert(item.node_id, item.output_layout.clone());
6882            Ok(handle)
6883        }
6884    }
6885}
6886
6887fn poisoned(what: &'static str) -> Error {
6888    Error::Msg(format!("PipelinedExecutor: {} poisoned", what)).bt()
6889}
6890
6891/// Step E A4b-1: record a node's [`CompletionHandle`] in the executor's
6892/// per-node handle map.
6893///
6894/// `Ready` handles (CPU / Vulkan / view-and-alloc arms) carry no async work, so
6895/// we DON'T store them — keeping the map to genuinely-pending entries makes the
6896/// realize-end empty-after-drain assert (open question #6) meaningful and keeps
6897/// the drain O(pending) rather than O(nodes). A re-used NodeId (in-place adopt
6898/// re-keys an existing slot) waits the prior handle first so nothing leaks.
6899#[inline]
6900fn store_handle(
6901    handles: &mut HashMap<NodeId, CompletionHandle>,
6902    node_id: NodeId,
6903    handle: CompletionHandle,
6904) {
6905    if matches!(handle, CompletionHandle::Ready) {
6906        // A prior pending handle at this slot must still be waited (don't drop a
6907        // Pending silently). In practice NodeIds are unique per realize, so this
6908        // is just defensive.
6909        if let Some(prev) = handles.remove(&node_id) {
6910            let _ = prev.wait();
6911        }
6912        return;
6913    }
6914    if let Some(prev) = handles.insert(node_id, handle) {
6915        let _ = prev.wait();
6916    }
6917}
6918
6919/// Step E A4b-3: the FINER cross-device producer wait.
6920///
6921/// Before dispatching a cross-device `Op::Copy` / `Op::Move` WorkItem, the
6922/// executor calls this on the copy's single source input. It removes the
6923/// source producer's [`CompletionHandle`] from the map and waits it — so the
6924/// specific producer P is complete before the D2H reads P's device buffer,
6925/// WITHOUT draining the whole source device (the conservative pre-A4b-3
6926/// behavior, where `to_cpu_bytes`'s `device.synchronize()` blocked on ALL
6927/// in-flight work on that device — including the OTHER sub-DAG's independent
6928/// work A4b-4 wants to overlap).
6929///
6930/// - **CUDA producer** → waits P's recorded `Event` (`cuEventSynchronize`):
6931///   fires after P + its already-ordered stream predecessors, nothing else.
6932/// - **Absent / `Ready` producer** (CPU producer, or a Vulkan producer — which
6933///   under A4b-2 is `Ready` mid-walk because nothing is submitted until
6934///   realize-end) → no-op. A Vulkan SOURCE's own ordering is handled inside
6935///   `download_bytes` (it `force_flush`es the open batch then reads), so there
6936///   is no mid-walk Vulkan handle to wait here; the cross-device Vulkan→CPU hop
6937///   stays correct without one.
6938///
6939/// Removing the handle here (rather than waiting it again at realize-end) keeps
6940/// `drain_handles`' post-drain empty-map assert meaningful and avoids a
6941/// double-wait. Waiting it twice would be harmless (`cuEventSynchronize` on an
6942/// already-signalled event is a fast no-op), but the consume-once contract is
6943/// cleaner. The producing node's *storage* stays in the cache for downstream
6944/// readers; only its completion handle is consumed.
6945fn wait_producer_handle(
6946    handles: &mut HashMap<NodeId, CompletionHandle>,
6947    producer: NodeId,
6948) -> Result<()> {
6949    if let Some(handle) = handles.remove(&producer) {
6950        handle.wait()?;
6951    }
6952    Ok(())
6953}
6954
6955/// Step E A4b-1: realize-end drain — wait every outstanding async handle, then
6956/// clear the map.
6957///
6958/// **Event-recording / wait strategy (A4b-1 §1.2).** CUDA has one stream per
6959/// device, and an `Event` recorded after a node's launch signals when that
6960/// node *and all prior stream work* have completed. So once the
6961/// latest-recorded event on a device has signalled, every earlier event on that
6962/// device is already signalled too: waiting them is a non-blocking
6963/// `cuEventQuery` fast-path, not N host stalls. We therefore wait every stored
6964/// handle (correct + simple).
6965///
6966/// **Open question #4 — "event only where waited" — RESOLVED.** Recording an
6967/// `Event` for every node was measured negligible on a 32-op synthetic, but
6968/// real decode graphs run 150-200+ ops; `pipelined`'s `WaitSet` pre-scan (see
6969/// `compiler_work_and_wait_set_for` / `build_wait_set`) now restricts event
6970/// production to the nodes some later cross-device `Copy`/`Move` will
6971/// individually wait — same-device-only ("elided") nodes get
6972/// `CompletionHandle::Ready` with no `cuEventCreate`/`cuEventRecord` at all
6973/// (`execute_compiled_with_wait_hint`). This drain therefore now retires only
6974/// the (typically few) wait-set handles that were never consumed mid-walk by
6975/// `wait_producer_handle`; it is no longer sufficient on its own to guarantee
6976/// every enqueued CUDA kernel has completed — `sync_active_cuda_devices` below
6977/// covers the elided remainder. We keep a per-node handle (rather than a
6978/// single per-device event) for the wait-set members because A4b-3's finer
6979/// cross-device wait needs to wait a *specific producer's* completion — the
6980/// per-node handle is that seam.
6981fn drain_handles(handles: &mut HashMap<NodeId, CompletionHandle>) -> Result<()> {
6982    for (_node, handle) in handles.drain() {
6983        handle.wait()?;
6984    }
6985    // Open question #6: once handles are stored instead of `wait`ed inline, the
6986    // `#[must_use]` on `CompletionHandle` can't catch a leaked (never-waited)
6987    // handle at the call site. The drain consumes the whole map, so it is empty
6988    // here by construction; assert it to catch a future leak (e.g. a new
6989    // dispatch path that forgets to thread its handle through `store_handle`).
6990    debug_assert!(
6991        handles.is_empty(),
6992        "A4b-1: handle map must be empty after drain"
6993    );
6994    Ok(())
6995}
6996
6997/// Step E A4b open question #4 step 3 — the realize-end complement to the
6998/// "event only where waited" elision. Because most CUDA nodes in a long
6999/// single-device chain no longer record an `Event` (see `drain_handles`'s
7000/// doc), this does ONE blanket `cuStreamSynchronize` per CUDA device that
7001/// still holds LIVE storage in `cache` — the realize target(s) plus any
7002/// surviving intermediates — instead of relying on per-node handles to cover
7003/// them.
7004///
7005/// **Why this is safe + sufficient.** CUDA has one stream per device, and
7006/// this executor dispatches strictly sequentially (one work item at a time,
7007/// in topological order) — so by the time a live node's own kernel was
7008/// launched, every same-device ancestor it depends on was ALREADY enqueued
7009/// earlier on the SAME stream. Stream ordering (not a host wait) guarantees
7010/// those ancestors run to completion no later than the live node's own
7011/// kernel. Syncing the live node's device therefore flushes its entire
7012/// same-device dependency chain, elided or not. Cross-device ancestors are
7013/// unaffected by elision — they always went through an `Op::Copy`/`Move`,
7014/// whose producer is in the `WaitSet` and was already waited explicitly at
7015/// the cross-device boundary (`wait_producer_handle`), mid-walk.
7016///
7017/// **Why evicted (non-live) intermediates don't need this.** A node whose
7018/// storage was evicted before realize-end (the `destructive_input` cleanup)
7019/// is never read by anything this realize returns; A3's stream-ordered
7020/// alloc/free already makes its eventual completion safe without a host
7021/// wait (the driver serializes the free after the freeing stream position,
7022/// same as any other stream-ordered op) — nothing to synchronize for.
7023///
7024/// No-op when `cache` holds no CUDA storage (CPU/Vulkan-only realize).
7025#[cfg(feature = "cuda")]
7026fn sync_active_cuda_devices(cache: &StorageCache) -> Result<()> {
7027    let mut devices: HashMap<fuel_ir::DeviceLocation, fuel_cuda_backend::CudaDevice> =
7028        HashMap::new();
7029    for arc in cache.values() {
7030        let guard = arc
7031            .read()
7032            .map_err(|_| poisoned("cache storage (cuda realize-end sync scan)"))?;
7033        if let fuel_memory::BackendStorage::Cuda(c) = &guard.inner {
7034            devices
7035                .entry(c.device().location())
7036                .or_insert_with(|| c.device().clone());
7037        }
7038    }
7039    for dev in devices.values() {
7040        dev.synchronize()?;
7041    }
7042    Ok(())
7043}
7044
7045/// Non-CUDA builds never produce CUDA storage, so there is nothing to sync —
7046/// keeps the call site unconditional across both feature configurations.
7047#[cfg(not(feature = "cuda"))]
7048fn sync_active_cuda_devices(_cache: &StorageCache) -> Result<()> {
7049    Ok(())
7050}
7051
7052/// Search the input cache for any `BackendStorage::Cuda(s)` whose
7053/// device matches `gpu_id`. Returns a clone of the `CudaDevice` Arc
7054/// the storage carries — the caller uses it to call
7055/// `CudaStorageBytes::alloc` for `Op::Alloc` on Cuda. Returns `None`
7056/// if no matching storage exists.
7057///
7058/// Phase 3a of bridge-retirement: callers seed the cache with a 0-byte
7059/// CUDA storage (`fuel-tensor::pipelined_bridge::device_seed_storage`)
7060/// so this lookup succeeds for the first Op::Alloc; subsequent
7061/// Op::Allocs see prior Op::Alloc outputs in the cache.
7062#[cfg(feature = "cuda")]
7063fn find_cuda_device_in_cache(
7064    cache: &StorageCache,
7065    gpu_id: usize,
7066) -> Option<fuel_cuda_backend::CudaDevice> {
7067    for arc in cache.values() {
7068        let guard = arc.read().ok()?;
7069        if let fuel_memory::BackendStorage::Cuda(c) = &guard.inner {
7070            // CudaDevice carries its DeviceLocation (gpu_id ordinal)
7071            // through `location()`; match against the target gpu_id.
7072            // Multi-GPU future work can refine the match; today's
7073            // single-GPU setups always match.
7074            if matches!(c.device().location(), DeviceLocation::Cuda { gpu_id: g } if g == gpu_id) {
7075                return Some(c.device().clone());
7076            }
7077        }
7078    }
7079    None
7080}
7081
7082/// Step E A4b-2: a Vulkan [`Completion`](crate::compiled::Completion) over an
7083/// in-flight (submitted, not-yet-waited) batch. `wait` blocks on the batch's
7084/// fence (`vkWaitForFences`) — which fires when the whole submitted command
7085/// buffer has retired on the single compute queue — then releases the batch
7086/// (frees the CB / descriptor sets / transient buffers / retired pool, all now
7087/// idle on the GPU).
7088///
7089/// The fence is per-BATCH, not per-node: one `submit_pending` flushes every op
7090/// recorded since the last submit, so this single handle covers a contiguous run
7091/// of Vulkan nodes (the A2 batching win, preserved — fewer fences, larger
7092/// submissions). `backend` keeps the [`VulkanBackend`] alive so the
7093/// post-fence pool retire + the `DeviceInner` the batch's resources reference
7094/// outlive the wait.
7095///
7096/// `Send` (required by `Completion`): every owned field is `Send` — `Fence` /
7097/// `CommandBuffer` / `DescriptorSet` / `Buffer` / `Allocation` / `CommandPool`
7098/// are all `Send` in vulkane (Arc-of-`DeviceInner` + explicit `unsafe impl`s),
7099/// and `Arc<VulkanBackend>` is `Send + Sync`.
7100/// Step E B1: `batch` is an `Option` ONLY so [`Drop`] can coexist with the
7101/// by-value `into_wait` consume. A type with a `Drop` impl cannot be
7102/// destructured by move (`let VulkanCompletion { backend, batch } = self`,
7103/// E0509), so `into_wait` `take()`s the batch out of the `Option` instead of
7104/// moving it out of the struct, then lets the normal `Drop` run. In every
7105/// reachable state the batch is `Some` until exactly one `into_wait` consumes it.
7106#[cfg(feature = "vulkan")]
7107struct VulkanCompletion {
7108    backend: Arc<fuel_vulkan_backend::VulkanBackend>,
7109    batch: Option<fuel_vulkan_backend::SubmittedBatch>,
7110    /// The device this submitted batch counts against in the in-flight counter
7111    /// (Step E B1). `Drop` decrements this slot.
7112    loc: fuel_ir::DeviceLocation,
7113}
7114
7115/// Step E A4b-4: the element type of the executor's in-flight-Vulkan-batch list.
7116/// A [`VulkanCompletion`] on a Vulkan build; a zero-sized placeholder otherwise
7117/// so the realize loops carry one `Vec<InflightVulkan>` local without `cfg` on
7118/// every use site (the helpers `eager_submit_all_vulkan` / `drain_inflight_vulkan`
7119/// are the only code that ever pushes/drains it, and they are `cfg`-gated).
7120#[cfg(feature = "vulkan")]
7121type InflightVulkan = VulkanCompletion;
7122#[cfg(not(feature = "vulkan"))]
7123type InflightVulkan = ();
7124
7125/// Step E A4b-4: is the cross-device copy's SOURCE buffer Vulkan-resident?
7126///
7127/// Used at the cross-device `Op::Copy`/`Op::Move` boundary to decide whether the
7128/// executor must wait the in-flight Vulkan batches before the copy. A Vulkan→CPU
7129/// D2H reads the source on the host, and the Vulkan `download` path only
7130/// `force_flush`es the OPEN batch (never the executor's eagerly-submitted
7131/// in-flight ones), so for a VULKAN source we must `drain_inflight_vulkan` first
7132/// to read completed data. For a CUDA / CPU source we must NOT wait Vulkan — the
7133/// copy doesn't read any Vulkan buffer, and waiting Vulkan there would needlessly
7134/// serialize the independent Vulkan sub-DAG (killing the overlap A4b-4 exists to
7135/// win). Returns `false` when the producer's storage isn't in the cache (treated
7136/// as not-Vulkan → no Vulkan wait; the CUDA/CPU producer handle still covers it).
7137#[cfg(feature = "vulkan")]
7138fn copy_source_is_vulkan(cache: &StorageCache, producer: NodeId) -> Result<bool> {
7139    if let Some(arc) = cache.get(&producer) {
7140        let guard = arc
7141            .read()
7142            .map_err(|_| poisoned("storage lock probing copy-source backend"))?;
7143        return Ok(matches!(
7144            guard.inner,
7145            fuel_memory::BackendStorage::Vulkan(_)
7146        ));
7147    }
7148    Ok(false)
7149}
7150
7151#[cfg(not(feature = "vulkan"))]
7152#[inline]
7153fn copy_source_is_vulkan(_cache: &StorageCache, _producer: NodeId) -> Result<bool> {
7154    Ok(false)
7155}
7156
7157#[cfg(feature = "vulkan")]
7158impl crate::compiled::Completion for VulkanCompletion {
7159    fn wait(self: Box<Self>) -> Result<()> {
7160        // Move the whole `VulkanCompletion` out of the `Box` (allowed even with a
7161        // `Drop` impl — it's a full move, not a destructure) and consume by value.
7162        (*self).into_wait()
7163    }
7164}
7165
7166#[cfg(feature = "vulkan")]
7167impl VulkanCompletion {
7168    /// Build the handle for an eagerly-submitted Vulkan batch and register it as
7169    /// one in-flight batch on `loc` (Step E B1). The matching decrement is in
7170    /// [`Drop`]. `loc` is the backend's `DeviceLocation::Vulkan { gpu_id }`.
7171    fn new(
7172        backend: Arc<fuel_vulkan_backend::VulkanBackend>,
7173        batch: fuel_vulkan_backend::SubmittedBatch,
7174        loc: fuel_ir::DeviceLocation,
7175    ) -> Self {
7176        crate::dispatch::inflight_inc(loc);
7177        Self {
7178            backend,
7179            batch: Some(batch),
7180            loc,
7181        }
7182    }
7183
7184    /// Block on this batch's fence, retire pools, then free the batch. Consumes
7185    /// `self` by value (the by-value sibling of the boxed `Completion::wait`),
7186    /// used by the executor's `inflight_vulkan` drain (A4b-4) where we hold the
7187    /// `VulkanCompletion` unboxed in a `Vec`.
7188    ///
7189    /// Step E B1: `take()`s the batch out of the `Option` (NOT a destructure
7190    /// move — that's illegal with a `Drop` impl) and waits it; the in-flight
7191    /// decrement then rides `self`'s `Drop` as this returns. So a wait-consume
7192    /// and a bare drop (e.g. an error unwinding before the wait) BOTH decrement
7193    /// exactly once, and `into_wait` never double-counts.
7194    fn into_wait(mut self) -> Result<()> {
7195        // `wait_submitted` consumes the batch by value: waits the fence, retires
7196        // pools, then drops the batch (UAF-safe — nothing the in-flight CB
7197        // references frees before the fence signals). After a `new` the batch is
7198        // always `Some`; `take` leaves `None` so `Drop` doesn't touch it again.
7199        if let Some(batch) = self.batch.take() {
7200            self.backend.wait_submitted(batch)?;
7201        }
7202        Ok(())
7203        // `self` drops here → `inflight_dec(self.loc)`.
7204    }
7205
7206    /// Step E A2.1 (deferred-deletion): retain an evicted DATA buffer until THIS
7207    /// in-flight batch's fence signals, then free it post-fence (on the batch's
7208    /// `Drop` — guaranteed post-fence by follow-on #2). Delegates to
7209    /// [`fuel_vulkan_backend::SubmittedBatch::retain_buffer`].
7210    ///
7211    /// The executor calls this for every in-flight batch when it evicts a Vulkan
7212    /// buffer those batches' CBs may read, INSTEAD of host-blocking on a drain.
7213    /// `batch` is `Some` in every reachable mid-walk state (it is `take`n only by
7214    /// `into_wait`/`wait`, which consume the whole `VulkanCompletion`), so the
7215    /// retain always lands on a live in-flight batch.
7216    fn retain_data(&mut self, buf: std::sync::Arc<fuel_vulkan_backend::VulkanBuffer>) {
7217        if let Some(batch) = self.batch.as_mut() {
7218            batch.retain_buffer(buf);
7219        }
7220    }
7221}
7222
7223#[cfg(feature = "vulkan")]
7224impl Drop for VulkanCompletion {
7225    fn drop(&mut self) {
7226        // The single in-flight decrement for a Vulkan batch — fires whether the
7227        // batch was waited (`into_wait` / `wait`) or merely dropped (error
7228        // unwind), so the per-device count returns to baseline. Relaxed +
7229        // saturating (a scheduling hint, never a correctness gate).
7230        crate::dispatch::inflight_dec(self.loc);
7231    }
7232}
7233
7234/// Step E A4b-4 — eager Vulkan submission during the walk (the OVERLAP enabler).
7235///
7236/// Submits each DISTINCT Vulkan backend's currently-open batch WITHOUT waiting,
7237/// pushing the resulting in-flight [`VulkanCompletion`]s onto `inflight` so the
7238/// executor waits them later (at the in-flight-lifetime guard / realize-end). An
7239/// empty open batch yields `None` and is skipped (idempotent).
7240///
7241/// This is what makes a Vulkan sub-DAG actually START on the iGPU while the
7242/// executor records/dispatches the next (CUDA) chunk — without it the Vulkan
7243/// batch sits merely *recorded* until realize-end and never overlaps the CUDA
7244/// stream (design §5). Called ONLY on a genuinely multi-backend realize (gated by
7245/// the executor's `multi_backend` flag); on a single-device graph it is never
7246/// reached, so pure-Vulkan stays byte-identical to A4b-2 (one realize-end submit).
7247///
7248/// **Whole-chunk granularity (UAF/race-safety, design §4 + the Vulkan
7249/// single-queue OOO-completion semantics).** We submit only at chunk boundaries
7250/// and before a cross-device wait — never mid-chunk — so the batch handed to the
7251/// GPU is a COMPLETE contiguous run of Vulkan nodes with all its intra-CB
7252/// dependency barriers (`recorder.rs` `vkCmdPipelineBarrier`) already in place.
7253/// Vulkan only guarantees that batches on one queue BEGIN in submission order;
7254/// they may overlap / complete out of order, so a split mid-chunk would lose the
7255/// write-before-read ordering for ops that read an earlier op's buffer in the
7256/// SAME chunk. By submitting whole chunks and re-syncing (`drain_inflight_vulkan`)
7257/// before any later Vulkan op records, before any cross-device copy, and before
7258/// any Vulkan-referenced eviction, no in-flight batch is ever read or freed while
7259/// still running.
7260#[cfg(feature = "vulkan")]
7261fn eager_submit_all_vulkan(
7262    cache: &StorageCache,
7263    inflight: &mut Vec<VulkanCompletion>,
7264) -> Result<()> {
7265    // Collect distinct Vulkan backends referenced by the cache (dedup by gpu_id).
7266    let mut seen: Vec<usize> = Vec::new();
7267    let mut backends: Vec<Arc<fuel_vulkan_backend::VulkanBackend>> = Vec::new();
7268    for arc in cache.values() {
7269        let guard = arc
7270            .read()
7271            .map_err(|_| poisoned("storage lock during eager vulkan submit"))?;
7272        if let fuel_memory::BackendStorage::Vulkan(v) = &guard.inner
7273            && let Some(backend) = v.backend()
7274            && !seen.contains(&backend.gpu_id)
7275        {
7276            seen.push(backend.gpu_id);
7277            backends.push(backend.clone());
7278        }
7279    }
7280    for backend in backends {
7281        // Step E B1: the per-device location for the in-flight counter. A batch
7282        // submitted here is one in-flight unit on this iGPU until its handle's
7283        // `Drop` (after `drain_inflight_vulkan` / realize-end).
7284        let loc = DeviceLocation::Vulkan {
7285            gpu_id: backend.gpu_id,
7286        };
7287        if let Some(batch) = backend.submit_pending()? {
7288            inflight.push(VulkanCompletion::new(backend, batch, loc));
7289        }
7290    }
7291    Ok(())
7292}
7293
7294#[cfg(not(feature = "vulkan"))]
7295#[inline]
7296fn eager_submit_all_vulkan(
7297    _cache: &StorageCache,
7298    _inflight: &mut Vec<InflightVulkan>,
7299) -> Result<()> {
7300    Ok(())
7301}
7302
7303/// Step E A4b-4 — wait every in-flight (eagerly-submitted) Vulkan batch, then
7304/// clear the list. The re-sync half of [`eager_submit_all_vulkan`].
7305///
7306/// Each `into_wait` blocks on the batch fence (`vkWaitForFences`), retires the
7307/// backend's descriptor pools, and frees the batch (CB / descriptor sets /
7308/// transient buffers / retired command pool — all now idle on the GPU). After
7309/// this returns, NO submitted Vulkan command buffer is still executing, so it is
7310/// safe to (a) record a new Vulkan op that may read a just-produced buffer,
7311/// (b) D2H-copy a Vulkan buffer on the host, or (c) free a buffer a batch read.
7312///
7313/// Because the eager submit happened at the PRIOR chunk boundary and an
7314/// intervening (e.g. CUDA) chunk has since been recorded/dispatched, the fence is
7315/// typically already signalled here — the wait is a fast no-op, and the iGPU work
7316/// genuinely overlapped the other device's stream. Waiting the Vulkan fence does
7317/// NOT touch the CUDA stream, so the other device keeps running (concurrency
7318/// preserved — design §5 "the per-device guards don't cross-stall").
7319#[cfg(feature = "vulkan")]
7320fn drain_inflight_vulkan(inflight: &mut Vec<VulkanCompletion>) -> Result<()> {
7321    for vc in inflight.drain(..) {
7322        vc.into_wait()?;
7323    }
7324    Ok(())
7325}
7326
7327#[cfg(not(feature = "vulkan"))]
7328#[inline]
7329fn drain_inflight_vulkan(_inflight: &mut Vec<InflightVulkan>) -> Result<()> {
7330    Ok(())
7331}
7332
7333/// Step E A4b-2: the realize-end Vulkan drain, SPLIT into submit-then-wait.
7334///
7335/// Replaces A2's `force_flush_all_vulkan` (which submitted + waited atomically
7336/// inside `force_flush`). For each DISTINCT Vulkan backend referenced by the
7337/// cache, `submit_pending` submits the still-open batch WITHOUT waiting (→ a
7338/// `SubmittedBatch`), wraps it in the executor's [`VulkanCompletion`] handle, and
7339/// `wait`s it. Net for a pure-Vulkan realize: the batch still accumulates across
7340/// the whole walk (the per-op path keeps returning `Ready`; no eager submit —
7341/// that is A4b-4) and is submitted ONCE here, then waited — **byte-identical to
7342/// A2**, same single submission at realize-end, just split through the handle.
7343///
7344/// Idempotent across repeated cache arcs: the first `submit_pending` on a backend
7345/// returns `Some(batch)`; subsequent calls on the same backend see an empty batch
7346/// and return `None` (skipped) — exactly the `force_flush` idempotence A2 relied
7347/// on. No-op for a non-Vulkan build.
7348#[cfg(feature = "vulkan")]
7349fn drain_vulkan_pending(cache: &StorageCache) -> Result<()> {
7350    use crate::compiled::CompletionHandle;
7351    for arc in cache.values() {
7352        let backend = {
7353            let guard = arc
7354                .read()
7355                .map_err(|_| poisoned("storage lock during vulkan submit_pending"))?;
7356            match &guard.inner {
7357                fuel_memory::BackendStorage::Vulkan(v) => v.backend().cloned(),
7358                _ => None,
7359            }
7360        };
7361        let Some(backend) = backend else { continue };
7362        // Submit the open batch (if any) without waiting, then wait via the
7363        // completion handle. Empty batch → None → nothing to wait.
7364        // Step E B1: `new` increments the in-flight counter for this device;
7365        // `handle.wait()` waits + drops the `VulkanCompletion`, decrementing it
7366        // — a balanced submit/retire even on this transient realize-end path.
7367        let loc = DeviceLocation::Vulkan {
7368            gpu_id: backend.gpu_id,
7369        };
7370        if let Some(batch) = backend.submit_pending()? {
7371            let handle: CompletionHandle =
7372                CompletionHandle::Pending(Box::new(VulkanCompletion::new(backend, batch, loc)));
7373            handle.wait()?;
7374        }
7375    }
7376    Ok(())
7377}
7378
7379#[cfg(not(feature = "vulkan"))]
7380fn drain_vulkan_pending(_cache: &StorageCache) -> Result<()> {
7381    Ok(())
7382}
7383
7384/// Step E A2: force the Vulkan backend behind `arc` (if any) to submit + WAIT
7385/// its open batch — the blocking drain before freeing a buffer the batch may
7386/// reference (a destructive eviction) so a recorded-but-unsubmitted command never
7387/// reads freed memory. No-op for non-Vulkan storage, an empty batch, or a
7388/// non-Vulkan build.
7389///
7390/// **Retained for the SINGLE-DEVICE path (byte-identical to pre-A2.1).** A2.1's
7391/// deferred-deletion ([`defer_evicted_vulkan_buffer`]) replaces this only on a
7392/// MULTI-backend realize, where eager-submit + in-flight tracking + the
7393/// realize-end `drain_inflight_vulkan` are all live. On a single-device Vulkan
7394/// realize the A4b machinery is gated off (`multi_backend == false`): the
7395/// cross-batch RAW guard (`pipelined.rs:832`) does not run, so a later Vulkan op
7396/// reading a buffer an eager-submitted batch wrote could race (separate
7397/// submissions only BEGIN in order, may overlap). The blocking `force_flush`
7398/// (submit + wait) is the coherent eviction drain there — exactly the original
7399/// behavior — so single-device stays byte-identical and UAF-safe.
7400#[cfg(feature = "vulkan")]
7401fn force_flush_vulkan(arc: &Arc<RwLock<Storage>>) -> Result<()> {
7402    let guard = arc
7403        .read()
7404        .map_err(|_| poisoned("storage lock during vulkan force_flush"))?;
7405    if let fuel_memory::BackendStorage::Vulkan(v) = &guard.inner
7406        && let Some(backend) = v.backend()
7407    {
7408        backend.force_flush()?;
7409    }
7410    Ok(())
7411}
7412
7413#[cfg(not(feature = "vulkan"))]
7414fn force_flush_vulkan(_arc: &Arc<RwLock<Storage>>) -> Result<()> {
7415    Ok(())
7416}
7417
7418/// Step E A2.1 — DEFERRED-DELETION of a Vulkan data buffer evicted while Vulkan
7419/// work is in flight (the throughput refinement that REPLACES the eviction-time
7420/// drain on a MULTI-backend realize). Called at the per-NodeId destructive
7421/// eviction (`Op::Release`/`Op::Move` cleanup) for the buffer about to leave the
7422/// cache, INSTEAD of `drain_inflight_vulkan` + `force_flush` (two host-blocking
7423/// fence waits) — so the iGPU work the executor was overlapping with CUDA is not
7424/// stalled at every eviction.
7425///
7426/// Two classes of Vulkan reader can hold a reference to `destroyed`'s buffer at
7427/// the eviction:
7428///   1. the **in-flight** `SubmittedBatch`es in `inflight` (submitted CBs, each
7429///      fenced), and
7430///   2. the **open**, not-yet-submitted recorder batch (recorded commands, NO
7431///      fence yet).
7432///
7433/// We make BOTH fence-gated without blocking the host:
7434///   - `eager_submit_all_vulkan` submits the open batch WITHOUT waiting, turning
7435///     it into one more in-flight `SubmittedBatch` (now fenced) pushed onto
7436///     `inflight`. (Whole-chunk granularity — UAF/race-safe per its contract; at a
7437///     destructive eviction the open batch is a contiguous Vulkan run.)
7438///   - We then move a refcount clone of the evicted buffer's `Arc<VulkanBuffer>`
7439///     into EVERY in-flight batch (conservative: we cannot cheaply map
7440///     buffer→batch, exactly the reason the old drain waited *all* of them). Each
7441///     batch frees its retained clone POST-fence on `Drop` (follow-on #2).
7442///
7443/// After this returns the caller `cache.remove`s `destroyed`; the cache's
7444/// `Arc<RwLock<Storage>>` drops, but the buffer's recycler
7445/// (`VulkanBuffer::drop`) reclaims it only when its LAST `Arc` drops — and the
7446/// retained clones keep it alive until their owning batches' fences signal. So the
7447/// GPU's last read of the buffer strictly precedes the free (NO use-after-free),
7448/// the host never blocks at the eviction (the iGPU keeps overlapping CUDA — the
7449/// throughput win), and every batch (hence every retained buffer) is drained by
7450/// realize-end at the latest (`drain_inflight_vulkan`, `pipelined.rs:916/1238`,
7451/// runs unconditionally → NO leak).
7452///
7453/// **Multi-backend only** (the call site gates `if multi_backend`). On a
7454/// single-device realize the open batch is drained by the blocking
7455/// [`force_flush_vulkan`] instead (byte-identical to pre-A2.1; see its doc for
7456/// why the deferred path is unsafe without the cross-batch RAW guard). No-op for a
7457/// non-Vulkan storage, an empty open + no in-flight batches, or a non-Vulkan build.
7458/// Open-batch size (dispatches) at which a deferred eviction submits the batch so the
7459/// GPU runs it while the host keeps recording.
7460#[cfg(feature = "vulkan")]
7461const EVICT_SUBMIT_MIN_DISPATCHES: usize = 48;
7462
7463#[cfg(feature = "vulkan")]
7464fn defer_evicted_vulkan_buffer(
7465    cache: &StorageCache,
7466    destroyed: NodeId,
7467    inflight: &mut Vec<VulkanCompletion>,
7468) -> Result<()> {
7469    // Pull the evicted buffer's device Arc (and its backend) out of the cache BEFORE
7470    // it is removed. Non-Vulkan storage, a host-evicted (no device buffer) Vulkan
7471    // storage, or an absent entry → nothing to retain (no Vulkan reader can hold a
7472    // device buffer).
7473    let (buf, backend) = {
7474        let Some(arc) = cache.get(&destroyed) else {
7475            return Ok(());
7476        };
7477        let guard = arc
7478            .read()
7479            .map_err(|_| poisoned("storage lock during deferred-eviction retain"))?;
7480        match &guard.inner {
7481            fuel_memory::BackendStorage::Vulkan(v) => (v.device_buffer_arc(), v.backend().cloned()),
7482            _ => (None, None),
7483        }
7484    };
7485    let Some(buf) = buf else { return Ok(()) };
7486
7487    // The OPEN batch may hold recorded-but-unsubmitted commands that read `destroyed`:
7488    // retain the buffer on the open batch itself (freed post-fence once that batch is
7489    // submitted and waited). This neither submits nor waits — it used to eager-submit
7490    // here, i.e. one queue submit per eviction (61 per Qwen3 decode step).
7491    if let Some(backend) = &backend {
7492        backend.retain_in_open_batch(buf.clone());
7493    }
7494    // Retain a clone of the evicted buffer in EVERY in-flight batch. Each frees it
7495    // POST-fence on `Drop` — the buffer outlives the GPU's last read with no host
7496    // block. Conservative over all batches (no cheap buffer→batch map); over-retention
7497    // only lengthens the lifetime, never a UAF, and all batches drain by realize-end.
7498    for vc in inflight.iter_mut() {
7499        vc.retain_data(buf.clone());
7500    }
7501    // Keep the GPU fed: submit the open batch once it has grown by a chunk.
7502    if let Some(backend) = backend
7503        && backend.open_batch_len() >= EVICT_SUBMIT_MIN_DISPATCHES
7504    {
7505        eager_submit_all_vulkan(cache, inflight)?;
7506    }
7507    // Step E A2.1 — throughput-observability. Count a DEFERRED retain that
7508    // actually replaced a host block: an evicted Vulkan buffer retained onto ≥1
7509    // in-flight batch (the open-batch eager-submit and/or pre-existing in-flight
7510    // batches). Pre-A2.1 every such site host-blocked (`force_flush` and/or
7511    // `drain_inflight_vulkan`); now it does not. A test reads
7512    // [`deferred_eviction_retains`] to assert the deferred path fired without a
7513    // drain (deterministic — no wall-clock, which is noisy on this box). When
7514    // `inflight` is empty here there was genuinely no in-flight/open Vulkan reader
7515    // to wait for, so no host block was avoided (and none was needed) — not counted.
7516    if !inflight.is_empty() {
7517        DEFERRED_EVICTION_RETAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7518    }
7519    Ok(())
7520}
7521
7522/// Step E A2.1 — cumulative count of deferred-deletion retains that replaced a
7523/// host-blocking eviction drain (an evicted Vulkan buffer retained onto ≥1
7524/// in-flight batch instead of waiting it). Process-global, `Relaxed` — a pure
7525/// test/telemetry observation, never a correctness gate (mirrors the B1 in-flight
7526/// counter idiom). Read by the live deferred-eviction throughput test.
7527#[cfg(feature = "vulkan")]
7528pub static DEFERRED_EVICTION_RETAINS: std::sync::atomic::AtomicUsize =
7529    std::sync::atomic::AtomicUsize::new(0);
7530
7531/// Read the A2.1 deferred-eviction-retain counter (see
7532/// [`DEFERRED_EVICTION_RETAINS`]). `pub` so the live throughput test can assert a
7533/// deferred retain fired (the eviction did NOT host-block on a Vulkan fence).
7534#[cfg(feature = "vulkan")]
7535pub fn deferred_eviction_retains() -> usize {
7536    DEFERRED_EVICTION_RETAINS.load(std::sync::atomic::Ordering::Relaxed)
7537}
7538
7539#[cfg(not(feature = "vulkan"))]
7540#[inline]
7541fn defer_evicted_vulkan_buffer(
7542    _cache: &StorageCache,
7543    _destroyed: NodeId,
7544    _inflight: &mut Vec<InflightVulkan>,
7545) -> Result<()> {
7546    Ok(())
7547}
7548
7549/// Vulkan counterpart of [`find_cuda_device_in_cache`]. Returns an
7550/// `Arc<VulkanBackend>` clone derived from any cached Vulkan storage
7551/// whose backend's `gpu_id` matches.
7552#[cfg(feature = "vulkan")]
7553fn find_vulkan_backend_in_cache(
7554    cache: &StorageCache,
7555    gpu_id: usize,
7556) -> Option<std::sync::Arc<fuel_vulkan_backend::VulkanBackend>> {
7557    for arc in cache.values() {
7558        let guard = arc.read().ok()?;
7559        if let fuel_memory::BackendStorage::Vulkan(v) = &guard.inner
7560            && let Some(backend) = v.backend()
7561            && backend.gpu_id == gpu_id
7562        {
7563            return Some(backend.clone());
7564        }
7565    }
7566    None
7567}
7568
7569/// Materialize a contiguous Storage Arc from a non-contiguous one.
7570/// Allocates a fresh buffer on the input's backend and copies the
7571/// strided / offset / broadcast input into it via the backend's
7572/// contiguize kernel. The returned Arc is a brand-new buffer; the
7573/// caller is responsible for replacing the cache entry only for the
7574/// duration of one kernel call (the upstream view op's output stays
7575/// in the cache so other consumers still see the strided view).
7576///
7577/// Stage 4 of Layout-on-Node — auto-Contiguize.
7578fn auto_contiguize(arc: &Arc<RwLock<Storage>>, layout: &Layout) -> Result<Arc<RwLock<Storage>>> {
7579    let in_guard = arc
7580        .read()
7581        .map_err(|_| poisoned("input storage lock during auto_contiguize"))?;
7582    let dtype = in_guard.dtype;
7583    let dtype_size = dtype.size_in_bytes();
7584    let new_storage = match &in_guard.inner {
7585        fuel_memory::BackendStorage::Cpu(c) => {
7586            let new_bytes = fuel_cpu_backend::byte_kernels::contiguize_cpu(c, layout, dtype_size)?;
7587            Storage::new(fuel_memory::BackendStorage::Cpu(new_bytes), dtype)
7588        }
7589        #[cfg(feature = "cuda")]
7590        fuel_memory::BackendStorage::Cuda(c) => {
7591            // Native baracuda contiguize (alpha.29). Byte-width-
7592            // dispatched: 1/2/4/8/16 byte elements all route to the
7593            // appropriate kernel. Handles signed strides (Flip),
7594            // zero strides (BroadcastTo), and non-zero element offset.
7595            //
7596            // Three host-side fast paths bake into the baracuda
7597            // launchers: already-contiguous → single cuMemcpyDtoDAsync;
7598            // innermost-stride-1 → per-outer-coord run copy; generic
7599            // → one thread per output element. Retires the prior
7600            // D2H → CPU contiguize_cpu → H2D fallback (two device
7601            // round-trips per non-contig input).
7602            let contig = fuel_cuda_backend::baracuda::contiguize::contiguize_to_fresh(
7603                c, layout, dtype_size,
7604            )?;
7605            Storage::new(fuel_memory::BackendStorage::Cuda(contig), dtype)
7606        }
7607        #[cfg(feature = "vulkan")]
7608        fuel_memory::BackendStorage::Vulkan(v) => {
7609            // Native `strided_copy_signed_*` kernel when it applies (2/4/8-byte
7610            // elements; see `contiguize_vulkan`). Otherwise the V.1.B host round trip:
7611            // D2H → CPU contiguize_cpu → H2D, which forces a flush and a wait
7612            // per call.
7613            let backend = v.backend().ok_or_else(|| {
7614                Error::Msg(
7615                    "auto_contiguize: Vulkan input has no backend handle. \
7616                     Storages flowing through the pipelined executor's Vulkan \
7617                     path must be constructed via VulkanBackend::alloc_bytes_handle \
7618                     / upload_bytes_handle (not the legacy alloc_bytes / \
7619                     upload_bytes which leave VulkanStorageBytes::backend = None)."
7620                        .to_string(),
7621                )
7622                .bt()
7623            })?;
7624            if let Some(native) = crate::vulkan_dispatch::contiguize_vulkan(v, layout, dtype_size)?
7625            {
7626                return Ok(Arc::new(RwLock::new(Storage::new(
7627                    fuel_memory::BackendStorage::Vulkan(native),
7628                    dtype,
7629                ))));
7630            }
7631            let _t = crate::compiled::op_profile::PhaseTimer::start(
7632                "auto_contiguize.vulkan_host_roundtrip",
7633            );
7634            let host_bytes = backend.download_bytes(v)?;
7635            let host_cpu = fuel_cpu_backend::byte_storage::CpuStorageBytes::from_bytes(&host_bytes);
7636            let contig_cpu =
7637                fuel_cpu_backend::byte_kernels::contiguize_cpu(&host_cpu, layout, dtype_size)?;
7638            let host_contig_bytes = contig_cpu.bytes().to_vec();
7639            let vk_bytes = backend.upload_bytes_handle(&host_contig_bytes)?;
7640            Storage::new(fuel_memory::BackendStorage::Vulkan(vk_bytes), dtype)
7641        }
7642        #[allow(unreachable_patterns)]
7643        _ => {
7644            return Err(Error::Msg(
7645                "auto_contiguize: backend not wired (CPU + CUDA + Vulkan are \
7646                 wired today; Metal extends this match when its byte-storage \
7647                 substrate lands)"
7648                    .to_string(),
7649            )
7650            .bt());
7651        }
7652    };
7653    Ok(Arc::new(RwLock::new(new_storage)))
7654}
7655
7656/// Write-into sibling of [`auto_contiguize`] (CapturedRun executor
7657/// build-out, 4b-γ): materializes a contiguous copy of `arc` at `layout`
7658/// INTO `dest`'s EXISTING buffer instead of allocating a fresh one — the
7659/// path `WorkItemKind::ContiguizeOf`'s Reuse-mode branch needs (device
7660/// allocation is illegal inside a capture scope). `dest` must already be
7661/// sized to the contiguized output's byte count — true by construction,
7662/// since the persistent map only ever holds a buffer THIS SAME code path
7663/// (the warm-run `auto_contiguize` allocation) sized.
7664///
7665/// CUDA-only today: `PersistentOutputs::reuse` (Reuse mode) is only ever
7666/// constructed inside [`PipelinedExecutor::capture_decode`], which is
7667/// `#[cfg(feature = "cuda")]`-gated and validates every compute node
7668/// targets `Cuda` — a CPU or Vulkan storage can never actually reach this
7669/// function in practice. Per this project's "never panic on production
7670/// paths" rule, the other backends still surface a typed gap rather than
7671/// silently mishandling it (never a crash).
7672#[cfg_attr(not(feature = "cuda"), allow(unused_variables))]
7673fn contiguize_into(
7674    dest: &Arc<RwLock<Storage>>,
7675    arc: &Arc<RwLock<Storage>>,
7676    layout: &Layout,
7677) -> Result<()> {
7678    let in_guard = arc
7679        .read()
7680        .map_err(|_| poisoned("input storage lock during contiguize_into"))?;
7681    match &in_guard.inner {
7682        #[cfg(feature = "cuda")]
7683        fuel_memory::BackendStorage::Cuda(src_cuda) => {
7684            let dtype_size = in_guard.dtype.size_in_bytes();
7685            let mut dest_guard = dest
7686                .write()
7687                .map_err(|_| poisoned("dest storage lock during contiguize_into"))?;
7688            let dest_cuda = match &mut dest_guard.inner {
7689                fuel_memory::BackendStorage::Cuda(d) => d,
7690                other => {
7691                    return Err(Error::Msg(format!(
7692                        "contiguize_into: dest is BackendStorage::{:?}, not Cuda",
7693                        other.backend_id(),
7694                    ))
7695                    .bt());
7696                }
7697            };
7698            fuel_cuda_backend::baracuda::contiguize::contiguize_into(
7699                src_cuda, layout, dest_cuda, dtype_size,
7700            )
7701        }
7702        #[allow(unreachable_patterns)]
7703        _ => Err(Error::Msg(
7704            "contiguize_into: only CUDA is wired (PersistentOutputs::reuse / \
7705             capture_decode is CUDA-only today — no CPU/Vulkan consumer exists \
7706             yet; extend this match if one appears)"
7707                .to_string(),
7708        )
7709        .bt()),
7710    }
7711}
7712
7713#[cfg(test)]
7714mod backend_neutral_tests {
7715    use super::*;
7716
7717    #[test]
7718    fn only_deviceless_items_are_backend_neutral() {
7719        let n = NodeId(0);
7720        // Adopting an input-cache entry or aliasing a producer touches no device.
7721        assert!(is_backend_neutral(&WorkItemKind::ConstAdopt));
7722        assert!(is_backend_neutral(&WorkItemKind::ViewOf { input: n }));
7723        assert!(is_backend_neutral(&WorkItemKind::SlotView { producer: n }));
7724        // Contiguize runs on its input's backend; its own `target_backend` is a
7725        // placeholder, so it must not count as a backend switch.
7726        assert!(is_backend_neutral(&WorkItemKind::ContiguizeOf { input: n }));
7727        // Sabotage siblings: anything that runs a kernel of its own or moves bytes
7728        // across devices is NOT, so a real backend switch still arms the
7729        // chunk-boundary logic.
7730        assert!(!is_backend_neutral(&WorkItemKind::Kernel));
7731        assert!(!is_backend_neutral(&WorkItemKind::Copy {
7732            target_location: DeviceLocation::Cpu
7733        }));
7734        assert!(!is_backend_neutral(&WorkItemKind::WriteSlice {
7735            dest: n,
7736            source: n
7737        }));
7738    }
7739}
7740
7741#[cfg(test)]
7742mod tests {
7743    use super::*;
7744    use fuel_graph::Node;
7745    use fuel_ir::Shape;
7746
7747    /// Task 5 (C6): `Op::Scan` has no native kernel in Phase 1 — it is
7748    /// always lowered/re-fused before execution — so `op_to_op_kind` must
7749    /// fall through its `_ => None` wildcard for it, exactly like any other
7750    /// not-yet-wired op. Regression lock, not born-red: this is expected to
7751    /// pass immediately.
7752    #[test]
7753    fn scan_has_no_dispatch_op_kind() {
7754        use fuel_graph::{Op, ScanEmit};
7755        assert_eq!(
7756            crate::pipelined::op_to_op_kind(&Op::Scan {
7757                n_carries: 1,
7758                n_xs: 0,
7759                bound: 2,
7760                emit: ScanEmit::All,
7761                early_exit: None
7762            }),
7763            None,
7764        );
7765    }
7766
7767    /// Step E A4b open question #4 — "event only where waited", step 1.
7768    /// `build_wait_set` collects exactly the producers of `Op::Copy`/`Move`
7769    /// nodes in the order: a same-device-only node (never copied/moved) must
7770    /// be ABSENT, and the Copy's own node id must not appear either (it is
7771    /// not its own producer).
7772    #[test]
7773    fn build_wait_set_collects_only_cross_device_copy_producers() {
7774        let mut g = Graph::new();
7775        let const_id = g.push(Node {
7776            op: Op::Const,
7777            inputs: vec![],
7778            shape: Shape::from_dims(&[4]),
7779            dtype: DType::F32,
7780        });
7781        // Same-device-only consumer of const_id — never fed into a Copy/Move.
7782        let same_device_id = g.push(Node {
7783            op: Op::Contiguize,
7784            inputs: vec![const_id],
7785            shape: Shape::from_dims(&[4]),
7786            dtype: DType::F32,
7787        });
7788        // A cross-device Copy whose producer is `same_device_id`.
7789        let copy_id = g.push(Node {
7790            op: Op::Copy {
7791                target: DeviceLocation::Cuda { gpu_id: 0 },
7792            },
7793            inputs: vec![same_device_id],
7794            shape: Shape::from_dims(&[4]),
7795            dtype: DType::F32,
7796        });
7797        let order = vec![const_id, same_device_id, copy_id];
7798
7799        let set = build_wait_set(&g, &order);
7800        assert!(
7801            set.contains(&same_device_id),
7802            "the Copy's producer must be in the wait set"
7803        );
7804        assert!(
7805            !set.contains(&const_id),
7806            "a node with no Copy/Move consumer must be absent from the wait set"
7807        );
7808        assert!(
7809            !set.contains(&copy_id),
7810            "the Copy node itself is not its own producer"
7811        );
7812        assert_eq!(
7813            set.len(),
7814            1,
7815            "only the one true cross-device producer is in the set"
7816        );
7817    }
7818
7819    /// A `Move` producer is collected the same way as a `Copy` producer.
7820    #[test]
7821    fn build_wait_set_collects_move_producers_too() {
7822        let mut g = Graph::new();
7823        let const_id = g.push(Node {
7824            op: Op::Const,
7825            inputs: vec![],
7826            shape: Shape::from_dims(&[4]),
7827            dtype: DType::F32,
7828        });
7829        let move_id = g.push(Node {
7830            op: Op::Move {
7831                target: DeviceLocation::Cpu,
7832            },
7833            inputs: vec![const_id],
7834            shape: Shape::from_dims(&[4]),
7835            dtype: DType::F32,
7836        });
7837        let order = vec![const_id, move_id];
7838
7839        let set = build_wait_set(&g, &order);
7840        assert!(
7841            set.contains(&const_id),
7842            "the Move's producer must be in the wait set"
7843        );
7844        assert_eq!(set.len(), 1);
7845    }
7846
7847    /// A CPU-only order (no `Op::Copy`/`Op::Move` anywhere) yields an empty
7848    /// wait set — every node in it is eligible for elision.
7849    #[test]
7850    fn build_wait_set_is_empty_for_cpu_only_order() {
7851        let mut g = Graph::new();
7852        let const_id = g.push(Node {
7853            op: Op::Const,
7854            inputs: vec![],
7855            shape: Shape::from_dims(&[4]),
7856            dtype: DType::F32,
7857        });
7858        let contig_id = g.push(Node {
7859            op: Op::Contiguize,
7860            inputs: vec![const_id],
7861            shape: Shape::from_dims(&[4]),
7862            dtype: DType::F32,
7863        });
7864        let order = vec![const_id, contig_id];
7865
7866        let set = build_wait_set(&g, &order);
7867        assert!(
7868            set.is_empty(),
7869            "a CPU-only order (no Copy/Move) yields an empty wait set"
7870        );
7871    }
7872
7873    /// `will_be_waited`'s two arms: the conservative `None` fallback (the
7874    /// `OrderSource::Streaming` case) is always `true`; a `Some(set)` checks
7875    /// membership.
7876    #[test]
7877    fn will_be_waited_none_is_conservative_true_for_any_node() {
7878        let ws: WaitSet = None;
7879        assert!(will_be_waited(&ws, NodeId(0)));
7880        assert!(will_be_waited(&ws, NodeId(12345)));
7881    }
7882
7883    #[test]
7884    fn will_be_waited_some_checks_membership() {
7885        let mut set = HashSet::new();
7886        set.insert(NodeId(3));
7887        let ws: WaitSet = Some(set);
7888        assert!(will_be_waited(&ws, NodeId(3)), "member must be waited");
7889        assert!(!will_be_waited(&ws, NodeId(4)), "non-member must be elided");
7890    }
7891
7892    /// A4b-1 test double: a `Completion` whose `wait` flips a shared flag, so a
7893    /// test can observe whether the drain actually waited it.
7894    struct FlagCompletion(std::sync::Arc<std::sync::atomic::AtomicUsize>);
7895    impl crate::compiled::Completion for FlagCompletion {
7896        fn wait(self: Box<Self>) -> Result<()> {
7897            self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
7898            Ok(())
7899        }
7900    }
7901
7902    /// A4b-1: `store_handle` keeps only `Pending` handles (so the post-drain
7903    /// empty-map assert is meaningful and the drain is O(pending)), and
7904    /// `drain_handles` waits each pending handle exactly once then empties the map.
7905    #[test]
7906    fn handle_map_stores_pending_and_drains_once() {
7907        use std::sync::Arc as StdArc;
7908        use std::sync::atomic::{AtomicUsize, Ordering};
7909
7910        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
7911
7912        // Ready handles are not stored.
7913        store_handle(&mut handles, NodeId(1), CompletionHandle::Ready);
7914        assert!(handles.is_empty(), "Ready handles must not be stored");
7915
7916        // Two pending handles are stored and each waited once on drain.
7917        let waited = StdArc::new(AtomicUsize::new(0));
7918        store_handle(
7919            &mut handles,
7920            NodeId(2),
7921            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
7922        );
7923        store_handle(
7924            &mut handles,
7925            NodeId(3),
7926            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
7927        );
7928        assert_eq!(handles.len(), 2);
7929
7930        drain_handles(&mut handles).expect("drain");
7931        assert_eq!(
7932            waited.load(Ordering::SeqCst),
7933            2,
7934            "each pending handle waited once"
7935        );
7936        assert!(handles.is_empty(), "map empty after drain");
7937    }
7938
7939    /// A4b-1: re-keying a NodeId with a new Pending handle waits the prior one
7940    /// (no leaked async work), and storing `Ready` over a prior Pending also
7941    /// waits it. Defensive — NodeIds are unique per realize in practice.
7942    #[test]
7943    fn handle_map_rekey_waits_previous() {
7944        use std::sync::Arc as StdArc;
7945        use std::sync::atomic::{AtomicUsize, Ordering};
7946
7947        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
7948        let waited = StdArc::new(AtomicUsize::new(0));
7949
7950        store_handle(
7951            &mut handles,
7952            NodeId(7),
7953            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
7954        );
7955        // Re-key with another Pending → prior is waited.
7956        store_handle(
7957            &mut handles,
7958            NodeId(7),
7959            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
7960        );
7961        assert_eq!(
7962            waited.load(Ordering::SeqCst),
7963            1,
7964            "rekey waited the prior pending"
7965        );
7966
7967        // Store Ready over the live Pending → it is waited too.
7968        store_handle(&mut handles, NodeId(7), CompletionHandle::Ready);
7969        assert_eq!(
7970            waited.load(Ordering::SeqCst),
7971            2,
7972            "Ready-over-Pending waited it"
7973        );
7974        assert!(handles.is_empty());
7975
7976        drain_handles(&mut handles).expect("drain empty");
7977    }
7978
7979    /// A4b-3: `wait_producer_handle` waits the named producer's handle EXACTLY
7980    /// once and removes it from the map (the finer cross-device source-drain
7981    /// consumes the producer's completion before the Copy reads its buffer), and
7982    /// is a no-op for an absent producer (CPU / Vulkan-`Ready` source, or an
7983    /// already-consumed handle). The realize-end drain then waits only what
7984    /// remains — no double-wait.
7985    #[test]
7986    fn wait_producer_handle_consumes_named_handle_once() {
7987        use std::sync::Arc as StdArc;
7988        use std::sync::atomic::{AtomicUsize, Ordering};
7989
7990        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
7991        let waited = StdArc::new(AtomicUsize::new(0));
7992
7993        // Two producers in flight; the Copy's source is NodeId(2).
7994        store_handle(
7995            &mut handles,
7996            NodeId(2),
7997            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
7998        );
7999        store_handle(
8000            &mut handles,
8001            NodeId(5),
8002            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8003        );
8004
8005        // Absent producer → no-op (a CPU/Vulkan-Ready source has no handle).
8006        wait_producer_handle(&mut handles, NodeId(99)).expect("absent is no-op");
8007        assert_eq!(
8008            waited.load(Ordering::SeqCst),
8009            0,
8010            "absent producer waited nothing"
8011        );
8012        assert_eq!(handles.len(), 2);
8013
8014        // The cross-device copy's source: waited once, removed from the map.
8015        wait_producer_handle(&mut handles, NodeId(2)).expect("wait source");
8016        assert_eq!(
8017            waited.load(Ordering::SeqCst),
8018            1,
8019            "source producer waited once"
8020        );
8021        assert!(!handles.contains_key(&NodeId(2)), "source handle consumed");
8022        assert!(
8023            handles.contains_key(&NodeId(5)),
8024            "unrelated handle untouched"
8025        );
8026
8027        // Re-waiting the (now absent) source is a no-op — no double-wait.
8028        wait_producer_handle(&mut handles, NodeId(2)).expect("re-wait is no-op");
8029        assert_eq!(waited.load(Ordering::SeqCst), 1, "no double-wait");
8030
8031        // Realize-end drain waits only the remaining unrelated producer.
8032        drain_handles(&mut handles).expect("drain");
8033        assert_eq!(
8034            waited.load(Ordering::SeqCst),
8035            2,
8036            "drain waited the remaining one"
8037        );
8038        assert!(handles.is_empty());
8039    }
8040
8041    /// Op::Contiguize on a contiguous-already input is zero-copy:
8042    /// the executor adopts the input Storage Arc unchanged.
8043    #[test]
8044    fn op_contiguize_zero_copy_on_contiguous_input() {
8045        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
8046
8047        let graph = Arc::new(RwLock::new(Graph::new()));
8048        let (const_id, contig_id) = {
8049            let mut g = graph.write().unwrap();
8050            let const_id = g.push(Node {
8051                op: Op::Const,
8052                inputs: vec![],
8053                shape: Shape::from_dims(&[2, 2]),
8054                dtype: DType::F32,
8055            });
8056            let contig_id = g.push(Node {
8057                op: Op::Contiguize,
8058                inputs: vec![const_id],
8059                shape: Shape::from_dims(&[2, 2]),
8060                dtype: DType::F32,
8061            });
8062            // No need to set target_backend on Contiguize — the
8063            // executor inherits or defaults to CPU.
8064            (const_id, contig_id)
8065        };
8066
8067        let mut inputs = StorageCache::new();
8068        let input_arc = Arc::new(RwLock::new(storage));
8069        let input_arc_for_compare = Arc::clone(&input_arc);
8070        inputs.insert(const_id, input_arc);
8071
8072        let (result_arc, _) =
8073            PipelinedExecutor::realize(graph, contig_id, inputs).expect("realize");
8074
8075        // Same Arc → zero-copy adoption. Compare by raw pointer.
8076        assert!(
8077            Arc::ptr_eq(&result_arc, &input_arc_for_compare),
8078            "Op::Contiguize on contiguous input must adopt the input Arc (zero copy)",
8079        );
8080    }
8081
8082    /// Op::Contiguize on a strided input (here: a transposed view)
8083    /// materializes a fresh contiguous Storage. The output bytes
8084    /// reflect the strided view's logical content, not the input
8085    /// storage's underlying memory order.
8086    #[test]
8087    fn op_contiguize_materializes_on_strided_input() {
8088        // 2x3 row-major: [[1,2,3],[4,5,6]] → transpose → 3x2:
8089        // [[1,4],[2,5],[3,6]]. The transposed view shares the
8090        // original buffer; Op::Contiguize on the transpose
8091        // materializes contiguous bytes matching the transposed
8092        // logical order.
8093        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
8094
8095        let graph = Arc::new(RwLock::new(Graph::new()));
8096        let (const_id, _transpose_id, contig_id) = {
8097            let mut g = graph.write().unwrap();
8098            let const_id = g.push(Node {
8099                op: Op::Const,
8100                inputs: vec![],
8101                shape: Shape::from_dims(&[2, 3]),
8102                dtype: DType::F32,
8103            });
8104            let transpose_id = g.push(Node {
8105                op: Op::Transpose,
8106                inputs: vec![const_id],
8107                shape: Shape::from_dims(&[3, 2]),
8108                dtype: DType::F32,
8109            });
8110            let contig_id = g.push(Node {
8111                op: Op::Contiguize,
8112                inputs: vec![transpose_id],
8113                shape: Shape::from_dims(&[3, 2]),
8114                dtype: DType::F32,
8115            });
8116            (const_id, transpose_id, contig_id)
8117        };
8118
8119        let mut inputs = StorageCache::new();
8120        inputs.insert(const_id, Arc::new(RwLock::new(storage)));
8121
8122        let (result_arc, _) =
8123            PipelinedExecutor::realize(graph, contig_id, inputs).expect("realize");
8124
8125        let guard = result_arc.read().unwrap();
8126        let cpu = if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
8127            c
8128        } else {
8129            panic!("expected Cpu storage");
8130        };
8131        let typed: &[f32] = cpu.as_slice().expect("f32 cast");
8132        // Transposed logical order: [1,4,2,5,3,6].
8133        assert_eq!(
8134            typed,
8135            &[1.0, 4.0, 2.0, 5.0, 3.0, 6.0],
8136            "contiguized transpose must reflect logical (transposed) byte order",
8137        );
8138    }
8139
8140    /// E2E: 3-node graph (Const + Const + Add), pre-seeded inputs,
8141    /// realized through the compiler+executor thread pair, returns
8142    /// expected sum bytes.
8143    #[test]
8144    fn pipelined_realize_const_const_add() {
8145        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
8146        let rhs_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
8147
8148        let graph = Arc::new(RwLock::new(Graph::new()));
8149        let (lhs_id, rhs_id, add_id) = {
8150            let mut g = graph.write().unwrap();
8151            let lhs_id = g.push(Node {
8152                op: Op::Const,
8153                inputs: vec![],
8154                shape: Shape::from_dims(&[3]),
8155                dtype: DType::F32,
8156            });
8157            let rhs_id = g.push(Node {
8158                op: Op::Const,
8159                inputs: vec![],
8160                shape: Shape::from_dims(&[3]),
8161                dtype: DType::F32,
8162            });
8163            let add_id = g.push(Node {
8164                op: Op::Add,
8165                inputs: vec![lhs_id, rhs_id],
8166                shape: Shape::from_dims(&[3]),
8167                dtype: DType::F32,
8168            });
8169            g.set_target_backend(add_id, BackendId::Cpu);
8170            (lhs_id, rhs_id, add_id)
8171        };
8172
8173        let mut inputs = StorageCache::new();
8174        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
8175        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
8176
8177        let (result_arc, _result_layout) =
8178            PipelinedExecutor::realize(graph, add_id, inputs).expect("realize");
8179
8180        let guard = result_arc.read().unwrap();
8181        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
8182            let typed: &[f32] = c.as_slice().expect("f32 cast");
8183            assert_eq!(typed, &[11.0, 22.0, 33.0]);
8184        } else {
8185            panic!("expected CPU output");
8186        }
8187    }
8188
8189    /// CapturedRun executor build-out (Increment 1): capture a 2-op binary
8190    /// chain `z = (a + b) * c` THROUGH the pipelined executor's
8191    /// persistent-output mode, then prove the three capture guarantees on a
8192    /// live GPU:
8193    ///   1. after capture, the fixed output buffer holds the warm-run result
8194    ///      (capture RECORDS launches, it does not execute them);
8195    ///   2. `replay()` recomputes bit-exactly into the SAME fixed buffer;
8196    ///   3. replay reads the FIXED input addresses — overwriting an input
8197    ///      buffer in place and replaying yields the new result, matching an
8198    ///      independent uncaptured `realize`. This is the whole mechanism:
8199    ///      the write-into binary wrapper + the executor's reuse mode +
8200    ///      `capture_run` compose into a replayable decode-step graph.
8201    #[test]
8202    #[ignore = "requires a live CUDA device"]
8203    #[cfg(feature = "cuda")]
8204    fn capture_decode_binary_chain_replays_bit_exact_cuda() {
8205        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8206        use fuel_ir::Shape;
8207        use fuel_memory::BackendStorage;
8208
8209        let Ok(dev) = CudaDevice::new(0) else {
8210            return fuel_test_support::hardware::skip(
8211                fuel_test_support::hardware::Hardware::Cuda,
8212                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
8213            );
8214        };
8215
8216        // z = (a + b) * c, shape [4]. `y = a + b` is a persistent
8217        // INTERMEDIATE; `z` is the persistent target — both fixed-address.
8218        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId, NodeId, NodeId) {
8219            let graph = Arc::new(RwLock::new(Graph::new()));
8220            let (a, b, c, z) = {
8221                let mut g = graph.write().unwrap();
8222                let a = g.push(Node {
8223                    op: Op::Const,
8224                    inputs: vec![],
8225                    shape: Shape::from_dims(&[4]),
8226                    dtype: DType::F32,
8227                });
8228                let b = g.push(Node {
8229                    op: Op::Const,
8230                    inputs: vec![],
8231                    shape: Shape::from_dims(&[4]),
8232                    dtype: DType::F32,
8233                });
8234                let c = g.push(Node {
8235                    op: Op::Const,
8236                    inputs: vec![],
8237                    shape: Shape::from_dims(&[4]),
8238                    dtype: DType::F32,
8239                });
8240                let y = g.push(Node {
8241                    op: Op::Add,
8242                    inputs: vec![a, b],
8243                    shape: Shape::from_dims(&[4]),
8244                    dtype: DType::F32,
8245                });
8246                let z = g.push(Node {
8247                    op: Op::Mul,
8248                    inputs: vec![y, c],
8249                    shape: Shape::from_dims(&[4]),
8250                    dtype: DType::F32,
8251                });
8252                g.set_target_backend(y, BackendId::Cuda);
8253                g.set_target_backend(z, BackendId::Cuda);
8254                (a, b, c, z)
8255            };
8256            (graph, a, b, c, z)
8257        };
8258
8259        let up = |v: &[f32]| -> Arc<RwLock<Storage>> {
8260            let bytes: &[u8] = bytemuck::cast_slice(v);
8261            let cb = CudaStorageBytes::from_cpu_bytes(&dev, bytes).expect("h2d");
8262            Arc::new(RwLock::new(Storage::new(
8263                BackendStorage::Cuda(cb),
8264                DType::F32,
8265            )))
8266        };
8267        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8268            let g = arc.read().unwrap();
8269            let BackendStorage::Cuda(c) = &g.inner else {
8270                panic!("not cuda")
8271            };
8272            let host = c.to_cpu_bytes().expect("d2h");
8273            bytemuck::cast_slice(&host).to_vec()
8274        };
8275
8276        let a_data = [1.0_f32, 2.0, 3.0, 4.0];
8277        let b_data = [10.0_f32, 20.0, 30.0, 40.0];
8278        let c_data = [2.0_f32, 2.0, 2.0, 2.0];
8279        let expect0 = [22.0_f32, 44.0, 66.0, 88.0]; // (a+b)*c
8280
8281        // Fixed input Arcs (shared into capture; overwritten in place later).
8282        let a_arc = up(&a_data);
8283        let b_arc = up(&b_data);
8284        let c_arc = up(&c_data);
8285
8286        let (graph, a, b, c, z) = build();
8287        let mut inputs = StorageCache::new();
8288        inputs.insert(a, a_arc.clone());
8289        inputs.insert(b, b_arc.clone());
8290        inputs.insert(c, c_arc.clone());
8291
8292        let captured =
8293            PipelinedExecutor::capture_decode(Arc::clone(&graph), z, inputs, SymEnv::default())
8294                .expect("capture_decode");
8295
8296        // (1) warm-run result sits in the captured output buffer.
8297        assert_eq!(
8298            read(&captured.output),
8299            &expect0,
8300            "warm-run result after capture"
8301        );
8302
8303        // (2) replay with the same inputs recomputes bit-exactly.
8304        captured.run.replay(&dev).expect("replay");
8305        dev.synchronize().expect("sync");
8306        assert_eq!(read(&captured.output), &expect0, "replay reproduces result");
8307
8308        // (3) overwrite input `a` IN PLACE (same device address), replay ->
8309        //     the new result flows from the FIXED input address. Compare to
8310        //     an independent uncaptured realize with the same new input.
8311        let a2 = [100.0_f32, 200.0, 300.0, 400.0];
8312        {
8313            let g = a_arc.read().unwrap();
8314            let BackendStorage::Cuda(c) = &g.inner else {
8315                panic!("a not cuda")
8316            };
8317            c.write_from_host(bytemuck::cast_slice(&a2))
8318                .expect("in-place H2D");
8319        }
8320        captured.run.replay(&dev).expect("replay 2");
8321        dev.synchronize().expect("sync 2");
8322        let got = read(&captured.output);
8323
8324        let (graph_ref, ar, br, cr, zr) = build();
8325        let mut inputs_ref = StorageCache::new();
8326        inputs_ref.insert(ar, up(&a2));
8327        inputs_ref.insert(br, up(&b_data));
8328        inputs_ref.insert(cr, up(&c_data));
8329        let (ref_arc, _) =
8330            PipelinedExecutor::realize(graph_ref, zr, inputs_ref).expect("ref realize");
8331        let expect1 = read(&ref_arc); // (a2+b)*c = [220,440,660,880]
8332        assert_eq!(
8333            got, expect1,
8334            "replay after in-place input update matches uncaptured realize"
8335        );
8336        assert_eq!(expect1, vec![220.0, 440.0, 660.0, 880.0]);
8337    }
8338
8339    /// CapturedRun executor build-out (Increment 3): capture a DECODE-SHAPED
8340    /// graph — the full dense op-set composing in one capture — and prove it
8341    /// replays bit-exactly against an independent uncaptured realize.
8342    ///
8343    /// Graph (an FFN block + norms, batch=seq=1 like real decode):
8344    ///   n1 = rms_norm(x);  u = n1 · w_up;  s = silu(u);
8345    /// cuBLAS `gemm_dense` matmul IS graph-capturable (regression for the
8346    /// dangling-input bug that once masqueraded as "cuBLAS not replay-safe").
8347    /// Captures `y = a·w` where the caller does NOT retain `w`, FORCES the
8348    /// freed-`w` slot to be reused by garbage buffers, then replays 50× — all
8349    /// must equal the uncaptured realize. Passes iff `capture_decode` retains
8350    /// its input buffers (`CapturedDecode::retained_inputs`).
8351    #[test]
8352    #[ignore = "requires a live CUDA device"]
8353    #[cfg(feature = "cuda")]
8354    fn capture_decode_matmul_replays_bit_exact_cuda() {
8355        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8356        use fuel_ir::Shape;
8357        use fuel_memory::BackendStorage;
8358        let Ok(dev) = CudaDevice::new(0) else { return };
8359        const H: usize = 4;
8360        const F: usize = 8;
8361        let a_data: Vec<f32> = (0..H).map(|i| 0.5 + i as f32).collect();
8362        let w_data: Vec<f32> = (0..H * F).map(|i| 0.01 * (i as f32 + 1.0)).collect();
8363        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId, NodeId) {
8364            let graph = Arc::new(RwLock::new(Graph::new()));
8365            let (a, w, y) = {
8366                let mut g = graph.write().unwrap();
8367                let a = g.push(Node {
8368                    op: Op::Const,
8369                    inputs: vec![],
8370                    shape: Shape::from_dims(&[1, H]),
8371                    dtype: DType::F32,
8372                });
8373                let w = g.push(Node {
8374                    op: Op::Const,
8375                    inputs: vec![],
8376                    shape: Shape::from_dims(&[H, F]),
8377                    dtype: DType::F32,
8378                });
8379                let y = g.push(Node {
8380                    op: Op::MatMul,
8381                    inputs: vec![a, w],
8382                    shape: Shape::from_dims(&[1, F]),
8383                    dtype: DType::F32,
8384                });
8385                g.set_target_backend(y, BackendId::Cuda);
8386                (a, w, y)
8387            };
8388            (graph, a, w, y)
8389        };
8390        let up = |v: &[f32]| {
8391            let b: Vec<u8> = v.iter().flat_map(|f| f.to_le_bytes()).collect();
8392            Arc::new(RwLock::new(Storage::new(
8393                BackendStorage::Cuda(CudaStorageBytes::from_cpu_bytes(&dev, &b).unwrap()),
8394                DType::F32,
8395            )))
8396        };
8397        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8398            let g = arc.read().unwrap();
8399            let BackendStorage::Cuda(c) = &g.inner else {
8400                panic!("not cuda")
8401            };
8402            c.to_cpu_bytes()
8403                .unwrap()
8404                .chunks_exact(4)
8405                .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
8406                .collect()
8407        };
8408        // Reference (uncaptured).
8409        let (gr, ar, wr, yr) = build();
8410        let mut insr = StorageCache::new();
8411        insr.insert(ar, up(&a_data));
8412        insr.insert(wr, up(&w_data));
8413        let (refarc, _) = PipelinedExecutor::realize(gr, yr, insr).unwrap();
8414        let expect = read(&refarc);
8415        // Capture (a + w NOT retained by caller).
8416        let (graph, a, w, y) = build();
8417        let mut inputs = StorageCache::new();
8418        inputs.insert(a, up(&a_data));
8419        inputs.insert(w, up(&w_data));
8420        let captured =
8421            PipelinedExecutor::capture_decode(Arc::clone(&graph), y, inputs, SymEnv::default())
8422                .expect("capture");
8423        assert_eq!(read(&captured.output), expect, "warm result after capture");
8424        // FORCE freed-memory reuse: same-size (H*F) garbage buffers. If `w`
8425        // were dangling, replay would read 999.0s.
8426        let mut squatters = Vec::new();
8427        for _ in 0..8 {
8428            let g: Vec<u8> = (0..H * F).flat_map(|_| 999.0f32.to_le_bytes()).collect();
8429            squatters.push(CudaStorageBytes::from_cpu_bytes(&dev, &g).unwrap());
8430        }
8431        dev.synchronize().unwrap();
8432        let mut bad = 0usize;
8433        for _ in 0..50 {
8434            captured.run.replay(&dev).unwrap();
8435            dev.synchronize().unwrap();
8436            if read(&captured.output) != expect {
8437                bad += 1;
8438            }
8439        }
8440        assert_eq!(
8441            bad, 0,
8442            "cuBLAS matmul capture replays bit-exact ({bad}/50 wrong)"
8443        );
8444    }
8445
8446    /// `Op::MulScalar` / `OpKind::Affine` (the `1/√d` attention scale) is
8447    /// capture-safe (write-into variant + forced-reuse regression).
8448    #[test]
8449    #[ignore = "requires a live CUDA device"]
8450    #[cfg(feature = "cuda")]
8451    fn capture_decode_affine_replays_bit_exact_cuda() {
8452        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8453        use fuel_ir::Shape;
8454        use fuel_memory::BackendStorage;
8455        let Ok(dev) = CudaDevice::new(0) else { return };
8456        const N: usize = 6;
8457        let x_data: Vec<f32> = (0..N).map(|i| 1.0 + i as f32).collect();
8458        let expect: Vec<f32> = x_data.iter().map(|v| v * 0.5).collect();
8459        let graph = Arc::new(RwLock::new(Graph::new()));
8460        let (x, y) = {
8461            let mut g = graph.write().unwrap();
8462            let x = g.push(Node {
8463                op: Op::Const,
8464                inputs: vec![],
8465                shape: Shape::from_dims(&[1, N]),
8466                dtype: DType::F32,
8467            });
8468            let y = g.push(Node {
8469                op: Op::MulScalar(0.5),
8470                inputs: vec![x],
8471                shape: Shape::from_dims(&[1, N]),
8472                dtype: DType::F32,
8473            });
8474            g.set_target_backend(y, BackendId::Cuda);
8475            (x, y)
8476        };
8477        let up = |v: &[f32]| {
8478            let b: Vec<u8> = v.iter().flat_map(|f| f.to_le_bytes()).collect();
8479            Arc::new(RwLock::new(Storage::new(
8480                BackendStorage::Cuda(CudaStorageBytes::from_cpu_bytes(&dev, &b).unwrap()),
8481                DType::F32,
8482            )))
8483        };
8484        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8485            let g = arc.read().unwrap();
8486            let BackendStorage::Cuda(c) = &g.inner else {
8487                panic!("not cuda")
8488            };
8489            c.to_cpu_bytes()
8490                .unwrap()
8491                .chunks_exact(4)
8492                .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
8493                .collect()
8494        };
8495        let mut inputs = StorageCache::new();
8496        inputs.insert(x, up(&x_data));
8497        let captured =
8498            PipelinedExecutor::capture_decode(Arc::clone(&graph), y, inputs, SymEnv::default())
8499                .expect("capture");
8500        assert_eq!(read(&captured.output), expect, "warm result after capture");
8501        let mut sq = Vec::new();
8502        for _ in 0..8 {
8503            let g: Vec<u8> = (0..N).flat_map(|_| 999.0f32.to_le_bytes()).collect();
8504            sq.push(CudaStorageBytes::from_cpu_bytes(&dev, &g).unwrap());
8505        }
8506        dev.synchronize().unwrap();
8507        let mut bad = 0usize;
8508        for _ in 0..50 {
8509            captured.run.replay(&dev).unwrap();
8510            dev.synchronize().unwrap();
8511            if read(&captured.output) != expect {
8512                bad += 1;
8513            }
8514        }
8515        assert_eq!(bad, 0, "affine capture replays bit-exact ({bad}/50 wrong)");
8516    }
8517
8518    /// `index_select` (embedding lookup) IS graph-capturable (regression for
8519    /// the dangling-input bug that once looked like "element 0 dropped on
8520    /// replay"). Captures `emb = index_select(wte, tok)` with `wte` NOT
8521    /// retained by the caller, FORCES the freed-`wte` slot to be reused by
8522    /// garbage buffers, then replays 50× — all must be `[1,2,3,4]`. Passes iff
8523    /// `capture_decode` retains its input buffers.
8524    #[test]
8525    #[ignore = "requires a live CUDA device"]
8526    #[cfg(feature = "cuda")]
8527    fn capture_decode_index_select_replays_bit_exact_cuda() {
8528        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8529        use fuel_ir::Shape;
8530        use fuel_memory::BackendStorage;
8531        let Ok(dev) = CudaDevice::new(0) else { return };
8532        const V: usize = 3;
8533        const H: usize = 4;
8534        let wte_data: Vec<f32> = (0..V)
8535            .flat_map(|v| (0..H).map(move |c| 1.0 + 10.0 * v as f32 + c as f32))
8536            .collect();
8537        let graph = Arc::new(RwLock::new(Graph::new()));
8538        let (tok, wte, emb) = {
8539            let mut g = graph.write().unwrap();
8540            let tok = g.push(Node {
8541                op: Op::Const,
8542                inputs: vec![],
8543                shape: Shape::from_dims(&[1]),
8544                dtype: DType::U32,
8545            });
8546            let wte = g.push(Node {
8547                op: Op::Const,
8548                inputs: vec![],
8549                shape: Shape::from_dims(&[V, H]),
8550                dtype: DType::F32,
8551            });
8552            let emb = g.push(Node {
8553                op: Op::IndexSelect { dim: 0 },
8554                inputs: vec![wte, tok],
8555                shape: Shape::from_dims(&[1, H]),
8556                dtype: DType::F32,
8557            });
8558            g.set_target_backend(emb, BackendId::Cuda);
8559            (tok, wte, emb)
8560        };
8561        let up_f32 = |v: &[f32]| {
8562            let b: Vec<u8> = v.iter().flat_map(|f| f.to_le_bytes()).collect();
8563            Arc::new(RwLock::new(Storage::new(
8564                BackendStorage::Cuda(CudaStorageBytes::from_cpu_bytes(&dev, &b).unwrap()),
8565                DType::F32,
8566            )))
8567        };
8568        let up_u32 = |v: &[u32]| {
8569            let b: Vec<u8> = v.iter().flat_map(|x| x.to_le_bytes()).collect();
8570            Arc::new(RwLock::new(Storage::new(
8571                BackendStorage::Cuda(CudaStorageBytes::from_cpu_bytes(&dev, &b).unwrap()),
8572                DType::U32,
8573            )))
8574        };
8575        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8576            let g = arc.read().unwrap();
8577            let BackendStorage::Cuda(c) = &g.inner else {
8578                panic!("not cuda")
8579            };
8580            c.to_cpu_bytes()
8581                .unwrap()
8582                .chunks_exact(4)
8583                .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
8584                .collect()
8585        };
8586        let tok_arc = up_u32(&[0]);
8587        let mut inputs = StorageCache::new();
8588        inputs.insert(tok, tok_arc.clone());
8589        inputs.insert(wte, up_f32(&wte_data));
8590        let captured =
8591            PipelinedExecutor::capture_decode(Arc::clone(&graph), emb, inputs, SymEnv::default())
8592                .expect("capture");
8593        assert_eq!(
8594            read(&captured.output),
8595            vec![1.0, 2.0, 3.0, 4.0],
8596            "warm result after capture"
8597        );
8598        // FORCE freed-memory reuse: same-size (V*H) garbage buffers reclaim
8599        // `wte`'s slot if it were dangling — replay would then read 999.0s.
8600        let mut squatters = Vec::new();
8601        for _ in 0..8 {
8602            let g: Vec<u8> = (0..V * H).flat_map(|_| 999.0f32.to_le_bytes()).collect();
8603            squatters.push(CudaStorageBytes::from_cpu_bytes(&dev, &g).unwrap());
8604        }
8605        dev.synchronize().unwrap();
8606        let mut bad = 0usize;
8607        for _ in 0..50 {
8608            captured.run.replay(&dev).unwrap();
8609            dev.synchronize().unwrap();
8610            if read(&captured.output) != vec![1.0, 2.0, 3.0, 4.0] {
8611                bad += 1;
8612            }
8613        }
8614        assert_eq!(
8615            bad, 0,
8616            "index_select capture replays bit-exact ({bad}/50 wrong)"
8617        );
8618    }
8619
8620    ///   n1 = rms_norm(x);  s = silu(n1);  p = softmax(s);
8621    ///   r  = p + x;  n2 = rms_norm(r);  y = n2 + x
8622    /// Exercises rms_norm (×2 — proves the per-device RMS workspace is reused
8623    /// across sequential norms inside ONE captured graph), silu + softmax
8624    /// (write-into), and residual adds through the persistent-output capture
8625    /// path. Verified across two input value-sets (robust, not luck).
8626    ///
8627    /// Deliberately EXCLUDES matmul (cuBLAS not graph-replay-safe) and
8628    /// index_select (its host-side shape/stride arrays dangle under capture —
8629    /// proven to mis-replay). Both are surfaced `capture_decode` gaps, not
8630    /// silent mis-replays. See `op_kind_is_capture_writeinto`.
8631    #[test]
8632    #[ignore = "requires a live CUDA device"]
8633    #[cfg(feature = "cuda")]
8634    fn capture_decode_norm_silu_softmax_replays_bit_exact_cuda() {
8635        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8636        use fuel_graph::registry::{FusedOpParams, FusedOps};
8637        use fuel_ir::Shape;
8638        use fuel_memory::BackendStorage;
8639
8640        let Ok(dev) = CudaDevice::new(0) else {
8641            return fuel_test_support::hardware::skip(
8642                fuel_test_support::hardware::Hardware::Cuda,
8643                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
8644            );
8645        };
8646        const H: usize = 6;
8647        let eps = 1e-5f64;
8648
8649        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId) {
8650            let graph = Arc::new(RwLock::new(Graph::new()));
8651            let (x, y) = {
8652                let mut g = graph.write().unwrap();
8653                let mk = |g: &mut Graph, op: Op, ins: Vec<NodeId>, dims: &[usize]| {
8654                    g.push(Node {
8655                        op,
8656                        inputs: ins,
8657                        shape: Shape::from_dims(dims),
8658                        dtype: DType::F32,
8659                    })
8660                };
8661                let rms = || {
8662                    Op::Fused(
8663                        FusedOps::RMS_NORM_LAST_DIM,
8664                        FusedOpParams::RmsNormLastDim { eps },
8665                    )
8666                };
8667                let sm = || Op::Fused(FusedOps::SOFTMAX_LAST_DIM, FusedOpParams::SoftmaxLastDim);
8668                let x = mk(&mut g, Op::Const, vec![], &[1, H]);
8669                let n1 = mk(&mut g, rms(), vec![x], &[1, H]);
8670                let s = mk(&mut g, Op::Silu, vec![n1], &[1, H]);
8671                let p = mk(&mut g, sm(), vec![s], &[1, H]);
8672                let r = mk(&mut g, Op::Add, vec![p, x], &[1, H]);
8673                let n2 = mk(&mut g, rms(), vec![r], &[1, H]);
8674                let y = mk(&mut g, Op::Add, vec![n2, x], &[1, H]);
8675                for id in [n1, s, p, r, n2, y] {
8676                    g.set_target_backend(id, BackendId::Cuda);
8677                }
8678                (x, y)
8679            };
8680            (graph, x, y)
8681        };
8682
8683        let up = |v: &[f32]| -> Arc<RwLock<Storage>> {
8684            let cb = CudaStorageBytes::from_cpu_bytes(&dev, bytemuck::cast_slice(v)).expect("h2d");
8685            Arc::new(RwLock::new(Storage::new(
8686                BackendStorage::Cuda(cb),
8687                DType::F32,
8688            )))
8689        };
8690        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8691            let g = arc.read().unwrap();
8692            let BackendStorage::Cuda(c) = &g.inner else {
8693                panic!("not cuda")
8694            };
8695            bytemuck::cast_slice(&c.to_cpu_bytes().expect("d2h")).to_vec()
8696        };
8697
8698        let x_data: Vec<f32> = (0..H).map(|c| 0.1 * (c as f32 + 1.0)).collect();
8699        let x_arc = up(&x_data);
8700        let (graph, x, y) = build();
8701        let mut inputs = StorageCache::new();
8702        inputs.insert(x, x_arc.clone());
8703
8704        let captured =
8705            PipelinedExecutor::capture_decode(Arc::clone(&graph), y, inputs, SymEnv::default())
8706                .expect("capture_decode norm/silu/softmax");
8707
8708        let realize_ref = |xv: &[f32]| -> Vec<f32> {
8709            let (g, xr, yr) = build();
8710            let mut ins = StorageCache::new();
8711            ins.insert(xr, up(xv));
8712            let (arc, _) = PipelinedExecutor::realize(g, yr, ins).expect("ref realize");
8713            read(&arc)
8714        };
8715        let expect0 = realize_ref(&x_data);
8716
8717        // (1) after capture the output holds the warm result.
8718        assert_eq!(read(&captured.output), expect0, "warm result after capture");
8719        // (2) replay reproduces bit-exactly (incl. RMS workspace reuse on replay).
8720        captured.run.replay(&dev).expect("replay");
8721        dev.synchronize().expect("sync");
8722        assert_eq!(read(&captured.output), expect0, "replay reproduces result");
8723
8724        // (3) overwrite x in place, replay -> matches uncaptured realize (a
8725        //     DIFFERENT value-set — so the chain is robust, not input-lucky).
8726        let x2: Vec<f32> = (0..H).map(|c| 0.3 * (c as f32 + 1.0)).collect();
8727        {
8728            let g = x_arc.read().unwrap();
8729            let BackendStorage::Cuda(c) = &g.inner else {
8730                panic!("x not cuda")
8731            };
8732            c.write_from_host(bytemuck::cast_slice(&x2))
8733                .expect("in-place H2D");
8734        }
8735        captured.run.replay(&dev).expect("replay 2");
8736        dev.synchronize().expect("sync 2");
8737        assert_eq!(
8738            read(&captured.output),
8739            realize_ref(&x2),
8740            "replay after x update matches realize"
8741        );
8742    }
8743
8744    /// CapturedRun executor build-out (Increment 4b-γ): make `ContiguizeOf`
8745    /// (a non-contiguous reshape after `Permute` — the real decode graph's
8746    /// attention-merge reshape shape) AND a 2-input `Op::Concat` (the shape
8747    /// RoPE's CUDA decomposition emits for its rotate-half) BOTH
8748    /// capture-safe in ONE graph, so the crux 4b-γ exists for — allocation
8749    /// of an INTERMEDIATE, non-final buffer inside a capture scope — is
8750    /// actually exercised, not just each gap in isolation.
8751    ///
8752    /// Graph: `x [2,3,4] --Permute[1,0,2]--> [3,2,4]` (non-contiguous)
8753    /// `--Reshape[3,8]--> r` (`ContiguizeOf`, MUST allocate: its input is
8754    /// non-contiguous) `--Concat(dim=1, with b [3,8])--> y [3,16]` (target).
8755    #[test]
8756    #[ignore = "requires a live CUDA device"]
8757    #[cfg(feature = "cuda")]
8758    fn capture_decode_contiguize_then_concat_replays_bit_exact_cuda() {
8759        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8760        use fuel_ir::Shape;
8761        use fuel_memory::BackendStorage;
8762
8763        let Ok(dev) = CudaDevice::new(0) else {
8764            return fuel_test_support::hardware::skip(
8765                fuel_test_support::hardware::Hardware::Cuda,
8766                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
8767            );
8768        };
8769
8770        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId, NodeId) {
8771            let graph = Arc::new(RwLock::new(Graph::new()));
8772            let (x, b, y) = {
8773                let mut g = graph.write().unwrap();
8774                let x = g.push(Node {
8775                    op: Op::Const,
8776                    inputs: vec![],
8777                    shape: Shape::from_dims(&[2, 3, 4]),
8778                    dtype: DType::F32,
8779                });
8780                let p = g.push(Node {
8781                    op: Op::Permute(vec![1, 0, 2]),
8782                    inputs: vec![x],
8783                    shape: Shape::from_dims(&[3, 2, 4]),
8784                    dtype: DType::F32,
8785                });
8786                let r = g.push(Node {
8787                    op: Op::Reshape(Shape::from_dims(&[3, 8])),
8788                    inputs: vec![p],
8789                    shape: Shape::from_dims(&[3, 8]),
8790                    dtype: DType::F32,
8791                });
8792                let b = g.push(Node {
8793                    op: Op::Const,
8794                    inputs: vec![],
8795                    shape: Shape::from_dims(&[3, 8]),
8796                    dtype: DType::F32,
8797                });
8798                let y = g.push(Node {
8799                    op: Op::Concat { dim: 1 },
8800                    inputs: vec![r, b],
8801                    shape: Shape::from_dims(&[3, 16]),
8802                    dtype: DType::F32,
8803                });
8804                g.set_target_backend(p, BackendId::Cuda);
8805                g.set_target_backend(r, BackendId::Cuda);
8806                g.set_target_backend(y, BackendId::Cuda);
8807                (x, b, y)
8808            };
8809            (graph, x, b, y)
8810        };
8811
8812        let up = |v: &[f32]| -> Arc<RwLock<Storage>> {
8813            let cb = CudaStorageBytes::from_cpu_bytes(&dev, bytemuck::cast_slice(v)).expect("h2d");
8814            Arc::new(RwLock::new(Storage::new(
8815                BackendStorage::Cuda(cb),
8816                DType::F32,
8817            )))
8818        };
8819        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8820            let g = arc.read().unwrap();
8821            let BackendStorage::Cuda(c) = &g.inner else {
8822                panic!("not cuda")
8823            };
8824            bytemuck::cast_slice(&c.to_cpu_bytes().expect("d2h")).to_vec()
8825        };
8826
8827        let x_data: Vec<f32> = (0..24).map(|i| i as f32).collect();
8828        let b_data: Vec<f32> = (0..24).map(|i| 100.0 + i as f32).collect();
8829        let x_arc = up(&x_data);
8830        let (graph, x, b, y) = build();
8831        let mut inputs = StorageCache::new();
8832        inputs.insert(x, x_arc.clone());
8833        // `b` deliberately NOT retained by a local variable — forces
8834        // reliance on `capture_decode`'s own `retained_inputs`, mirroring
8835        // the matmul/index_select regression precedent.
8836        inputs.insert(b, up(&b_data));
8837
8838        let captured =
8839            PipelinedExecutor::capture_decode(Arc::clone(&graph), y, inputs, SymEnv::default())
8840                .expect("capture_decode contiguize+concat");
8841
8842        let realize_ref = |xv: &[f32], bv: &[f32]| -> Vec<f32> {
8843            let (g, xr, br, yr) = build();
8844            let mut ins = StorageCache::new();
8845            ins.insert(xr, up(xv));
8846            ins.insert(br, up(bv));
8847            let (arc, _) = PipelinedExecutor::realize(g, yr, ins).expect("ref realize");
8848            read(&arc)
8849        };
8850        let expect0 = realize_ref(&x_data, &b_data);
8851
8852        // (1) warm-run result sits in the captured output buffer (capture
8853        //     RECORDS launches, it does not execute them at capture time).
8854        assert_eq!(read(&captured.output), expect0, "warm result after capture");
8855
8856        // (2) replay TWICE with unchanged inputs — proves the fixed-address
8857        //     reuse (both the ContiguizeOf intermediate and the Concat
8858        //     output) holds across multiple replay() calls, not just one.
8859        for i in 0..2 {
8860            captured
8861                .run
8862                .replay(&dev)
8863                .unwrap_or_else(|e| panic!("replay {i}: {e:?}"));
8864            dev.synchronize().expect("sync");
8865            assert_eq!(
8866                read(&captured.output),
8867                expect0,
8868                "replay {i} reproduces result"
8869            );
8870        }
8871
8872        // (3) overwrite x in place (a DIFFERENT value-set), replay again ->
8873        //     the new result flows from the FIXED input address, through
8874        //     the fixed ContiguizeOf intermediate, into the fixed Concat
8875        //     output — matches an independent uncaptured realize.
8876        let x2: Vec<f32> = (0..24).map(|i| 1000.0 + i as f32).collect();
8877        {
8878            let g = x_arc.read().unwrap();
8879            let BackendStorage::Cuda(c) = &g.inner else {
8880                panic!("x not cuda")
8881            };
8882            c.write_from_host(bytemuck::cast_slice(&x2))
8883                .expect("in-place H2D");
8884        }
8885        captured.run.replay(&dev).expect("replay 3");
8886        dev.synchronize().expect("sync 3");
8887        assert_eq!(
8888            read(&captured.output),
8889            realize_ref(&x2, &b_data),
8890            "replay after x update matches independent uncaptured realize"
8891        );
8892    }
8893
8894    /// CapturedRun executor build-out (Increment 4b-ζ): a same-device
8895    /// CUDA→CUDA `Op::Copy` — the shape `insert_safety_copies` emits for its
8896    /// aliasing-hazard snapshots in the real Llama decode graph — is
8897    /// capture-safe via `copy_from_cuda_wrapper`'s write-into
8898    /// `BackendStorage::Cuda` branch (`CudaStorageBytes::copy_from_device`).
8899    ///
8900    /// Graph: `x [2,4]`, `b [2,4]` --Copy{target: Cuda{0}}--> `c` (same-device
8901    /// snapshot of `x`) --Add(c, b)--> `y`. Capture, replay twice unchanged,
8902    /// then update `x` in place and replay again — every step must match an
8903    /// independent uncaptured `realize`.
8904    #[test]
8905    #[ignore = "requires a live CUDA device"]
8906    #[cfg(feature = "cuda")]
8907    fn capture_decode_same_device_copy_replays_bit_exact_cuda() {
8908        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8909        use fuel_ir::Shape;
8910        use fuel_memory::BackendStorage;
8911
8912        let Ok(dev) = CudaDevice::new(0) else {
8913            return fuel_test_support::hardware::skip(
8914                fuel_test_support::hardware::Hardware::Cuda,
8915                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
8916            );
8917        };
8918
8919        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId, NodeId) {
8920            let graph = Arc::new(RwLock::new(Graph::new()));
8921            let (x, b, y) = {
8922                let mut g = graph.write().unwrap();
8923                let x = g.push(Node {
8924                    op: Op::Const,
8925                    inputs: vec![],
8926                    shape: Shape::from_dims(&[2, 4]),
8927                    dtype: DType::F32,
8928                });
8929                let b = g.push(Node {
8930                    op: Op::Const,
8931                    inputs: vec![],
8932                    shape: Shape::from_dims(&[2, 4]),
8933                    dtype: DType::F32,
8934                });
8935                // Same-device CUDA->CUDA copy — the write-into-safe case.
8936                let c = g.push(Node {
8937                    op: Op::Copy {
8938                        target: DeviceLocation::Cuda { gpu_id: 0 },
8939                    },
8940                    inputs: vec![x],
8941                    shape: Shape::from_dims(&[2, 4]),
8942                    dtype: DType::F32,
8943                });
8944                let y = g.push(Node {
8945                    op: Op::Add,
8946                    inputs: vec![c, b],
8947                    shape: Shape::from_dims(&[2, 4]),
8948                    dtype: DType::F32,
8949                });
8950                // Copy's target_backend = SOURCE backend (x is Cuda-resident).
8951                g.set_target_backend(c, BackendId::Cuda);
8952                g.set_target_backend(y, BackendId::Cuda);
8953                (x, b, y)
8954            };
8955            (graph, x, b, y)
8956        };
8957
8958        let up = |v: &[f32]| -> Arc<RwLock<Storage>> {
8959            let cb = CudaStorageBytes::from_cpu_bytes(&dev, bytemuck::cast_slice(v)).expect("h2d");
8960            Arc::new(RwLock::new(Storage::new(
8961                BackendStorage::Cuda(cb),
8962                DType::F32,
8963            )))
8964        };
8965        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8966            let g = arc.read().unwrap();
8967            let BackendStorage::Cuda(c) = &g.inner else {
8968                panic!("not cuda")
8969            };
8970            bytemuck::cast_slice(&c.to_cpu_bytes().expect("d2h")).to_vec()
8971        };
8972
8973        let x_data: Vec<f32> = (0..8).map(|i| i as f32).collect();
8974        let b_data: Vec<f32> = (0..8).map(|i| 100.0 + i as f32).collect();
8975        let x_arc = up(&x_data);
8976        let (graph, x, b, y) = build();
8977        let mut inputs = StorageCache::new();
8978        inputs.insert(x, x_arc.clone());
8979        // `b` deliberately NOT retained by a local variable — forces
8980        // reliance on `capture_decode`'s own `retained_inputs`.
8981        inputs.insert(b, up(&b_data));
8982
8983        let captured =
8984            PipelinedExecutor::capture_decode(Arc::clone(&graph), y, inputs, SymEnv::default())
8985                .expect("capture_decode same-device copy");
8986
8987        let realize_ref = |xv: &[f32], bv: &[f32]| -> Vec<f32> {
8988            let (g, xr, br, yr) = build();
8989            let mut ins = StorageCache::new();
8990            ins.insert(xr, up(xv));
8991            ins.insert(br, up(bv));
8992            let (arc, _) = PipelinedExecutor::realize(g, yr, ins).expect("ref realize");
8993            read(&arc)
8994        };
8995        let expect0 = realize_ref(&x_data, &b_data);
8996
8997        // (1) warm-run result sits in the captured output buffer.
8998        assert_eq!(read(&captured.output), expect0, "warm result after capture");
8999
9000        // (2) replay TWICE with unchanged inputs — the Copy's write-into
9001        //     destination buffer must stay bit-exact across replays.
9002        for i in 0..2 {
9003            captured
9004                .run
9005                .replay(&dev)
9006                .unwrap_or_else(|e| panic!("replay {i}: {e:?}"));
9007            dev.synchronize().expect("sync");
9008            assert_eq!(
9009                read(&captured.output),
9010                expect0,
9011                "replay {i} reproduces result"
9012            );
9013        }
9014
9015        // (3) overwrite x in place (a DIFFERENT value-set), replay again ->
9016        //     the Copy re-runs on the fixed input address into its fixed
9017        //     destination buffer -> matches an independent uncaptured realize.
9018        let x2: Vec<f32> = (0..8).map(|i| 1000.0 + i as f32).collect();
9019        {
9020            let g = x_arc.read().unwrap();
9021            let BackendStorage::Cuda(c) = &g.inner else {
9022                panic!("x not cuda")
9023            };
9024            c.write_from_host(bytemuck::cast_slice(&x2))
9025                .expect("in-place H2D");
9026        }
9027        captured.run.replay(&dev).expect("replay 3");
9028        dev.synchronize().expect("sync 3");
9029        assert_eq!(
9030            read(&captured.output),
9031            realize_ref(&x2, &b_data),
9032            "replay after x update matches independent uncaptured realize"
9033        );
9034    }
9035
9036    /// CapturedRun executor build-out (Increment 4b-ζ): a genuinely
9037    /// cross-device `Op::Copy` (D2H — `target: DeviceLocation::Cpu` from a
9038    /// CUDA-resident source) must still be REJECTED by `capture_decode`'s
9039    /// validation loop — a host round-trip can never be part of a CUDA
9040    /// graph capture. Fast check: no replay, just confirm the typed `Err`.
9041    #[test]
9042    #[ignore = "requires a live CUDA device"]
9043    #[cfg(feature = "cuda")]
9044    fn capture_decode_rejects_cross_device_copy_cuda() {
9045        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
9046        use fuel_ir::Shape;
9047        use fuel_memory::BackendStorage;
9048
9049        let Ok(dev) = CudaDevice::new(0) else {
9050            return fuel_test_support::hardware::skip(
9051                fuel_test_support::hardware::Hardware::Cuda,
9052                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
9053            );
9054        };
9055
9056        let graph = Arc::new(RwLock::new(Graph::new()));
9057        let (x, y) = {
9058            let mut g = graph.write().unwrap();
9059            let x = g.push(Node {
9060                op: Op::Const,
9061                inputs: vec![],
9062                shape: Shape::from_dims(&[2, 4]),
9063                dtype: DType::F32,
9064            });
9065            // Genuinely cross-device: D2H.
9066            let y = g.push(Node {
9067                op: Op::Copy {
9068                    target: DeviceLocation::Cpu,
9069                },
9070                inputs: vec![x],
9071                shape: Shape::from_dims(&[2, 4]),
9072                dtype: DType::F32,
9073            });
9074            g.set_target_backend(y, BackendId::Cuda); // source backend = Cuda
9075            (x, y)
9076        };
9077
9078        let x_data: Vec<f32> = (0..8).map(|i| i as f32).collect();
9079        let cb =
9080            CudaStorageBytes::from_cpu_bytes(&dev, bytemuck::cast_slice(&x_data)).expect("h2d");
9081        let x_arc = Arc::new(RwLock::new(Storage::new(
9082            BackendStorage::Cuda(cb),
9083            DType::F32,
9084        )));
9085        let mut inputs = StorageCache::new();
9086        inputs.insert(x, x_arc);
9087
9088        let result = PipelinedExecutor::capture_decode(graph, y, inputs, SymEnv::default());
9089        let msg = match result {
9090            Ok(_) => panic!("D2H Op::Copy must be rejected by capture_decode"),
9091            Err(e) => e.to_string(),
9092        };
9093        assert!(
9094            msg.contains("cross-device"),
9095            "error should describe the cross-device rejection: {msg}"
9096        );
9097    }
9098
9099    /// CapturedDecodeSession (Increment 4a): drive the warm→capture→replay
9100    /// orchestration over MANY tokens on a synthetic decode-shaped session —
9101    /// the real per-token decode pattern. Capture once, then per token
9102    /// H2D-update the fixed input buffer IN PLACE + replay, asserting each
9103    /// token's output is bit-exact against an independent uncaptured realize.
9104    /// A kernel-agnostic proof of the state machine + fixed-buffer mechanics
9105    /// (matmul + index_select excluded pending baracuda capture-safe kernels).
9106    #[test]
9107    #[ignore = "requires a live CUDA device"]
9108    #[cfg(feature = "cuda")]
9109    fn captured_decode_session_replays_many_tokens_cuda() {
9110        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
9111        use fuel_graph::registry::{FusedOpParams, FusedOps};
9112        use fuel_ir::Shape;
9113        use fuel_memory::BackendStorage;
9114
9115        let Ok(dev) = CudaDevice::new(0) else {
9116            return fuel_test_support::hardware::skip(
9117                fuel_test_support::hardware::Hardware::Cuda,
9118                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
9119            );
9120        };
9121        const H: usize = 6;
9122        let eps = 1e-5f64;
9123
9124        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId) {
9125            let graph = Arc::new(RwLock::new(Graph::new()));
9126            let (x, y) = {
9127                let mut g = graph.write().unwrap();
9128                let mk = |g: &mut Graph, op: Op, ins: Vec<NodeId>, dims: &[usize]| {
9129                    g.push(Node {
9130                        op,
9131                        inputs: ins,
9132                        shape: Shape::from_dims(dims),
9133                        dtype: DType::F32,
9134                    })
9135                };
9136                let rms = || {
9137                    Op::Fused(
9138                        FusedOps::RMS_NORM_LAST_DIM,
9139                        FusedOpParams::RmsNormLastDim { eps },
9140                    )
9141                };
9142                let sm = || Op::Fused(FusedOps::SOFTMAX_LAST_DIM, FusedOpParams::SoftmaxLastDim);
9143                let x = mk(&mut g, Op::Const, vec![], &[1, H]);
9144                let n1 = mk(&mut g, rms(), vec![x], &[1, H]);
9145                let s = mk(&mut g, Op::Silu, vec![n1], &[1, H]);
9146                let p = mk(&mut g, sm(), vec![s], &[1, H]);
9147                let r = mk(&mut g, Op::Add, vec![p, x], &[1, H]);
9148                let n2 = mk(&mut g, rms(), vec![r], &[1, H]);
9149                let y = mk(&mut g, Op::Add, vec![n2, x], &[1, H]);
9150                for id in [n1, s, p, r, n2, y] {
9151                    g.set_target_backend(id, BackendId::Cuda);
9152                }
9153                (x, y)
9154            };
9155            (graph, x, y)
9156        };
9157        let up = |v: &[f32]| -> Arc<RwLock<Storage>> {
9158            let cb = CudaStorageBytes::from_cpu_bytes(&dev, bytemuck::cast_slice(v)).expect("h2d");
9159            Arc::new(RwLock::new(Storage::new(
9160                BackendStorage::Cuda(cb),
9161                DType::F32,
9162            )))
9163        };
9164        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9165            let g = arc.read().unwrap();
9166            let BackendStorage::Cuda(c) = &g.inner else {
9167                panic!("not cuda")
9168            };
9169            bytemuck::cast_slice(&c.to_cpu_bytes().expect("d2h")).to_vec()
9170        };
9171        let realize_ref = |xv: &[f32]| -> Vec<f32> {
9172            let (g, xr, yr) = build();
9173            let mut ins = StorageCache::new();
9174            ins.insert(xr, up(xv));
9175            let (arc, _) = PipelinedExecutor::realize(g, yr, ins).expect("ref realize");
9176            read(&arc)
9177        };
9178
9179        // 5 distinct "tokens" (distinct per-token input value-sets).
9180        let tokens: Vec<Vec<f32>> = (0..5)
9181            .map(|t| {
9182                (0..H)
9183                    .map(|c| 0.1 * (t as f32 + 1.0) * (c as f32 + 1.0))
9184                    .collect()
9185            })
9186            .collect();
9187
9188        // Capture ONCE against token 0's fixed input buffer.
9189        let x_arc = up(&tokens[0]);
9190        let (graph, x, y) = build();
9191        let mut inputs = StorageCache::new();
9192        inputs.insert(x, x_arc.clone());
9193        let session =
9194            CapturedDecodeSession::capture(Arc::clone(&graph), y, inputs, &[x], SymEnv::default())
9195                .expect("capture session");
9196
9197        // Warm result (token 0) already sits in the output buffer.
9198        assert_eq!(
9199            read(session.output()),
9200            realize_ref(&tokens[0]),
9201            "warm token 0"
9202        );
9203
9204        // The decode loop: replay every token (incl. re-replaying token 0) via
9205        // in-place H2D update of the fixed input + one graph launch.
9206        for (t, tok) in tokens.iter().enumerate() {
9207            let out = session
9208                .replay_token(&[(x, bytemuck::cast_slice(tok))])
9209                .expect("replay_token");
9210            assert_eq!(
9211                read(&out),
9212                realize_ref(tok),
9213                "replayed token {t} matches uncaptured realize"
9214            );
9215        }
9216        // Distinct tokens must give distinct outputs (live recompute, not stale).
9217        assert_ne!(
9218            realize_ref(&tokens[0]),
9219            realize_ref(&tokens[1]),
9220            "tokens must differ"
9221        );
9222    }
9223
9224    /// PR-C1 behavior contract: `realize_with_optimized_route` with an
9225    /// **empty** route (the no-pressure / no-telemetry case) is
9226    /// byte-identical to `realize_with_optimized` (arm-0). On a branchless
9227    /// graph the route has no branches to resolve, so both must produce
9228    /// the same bytes — realize is unchanged from Phase B.
9229    #[test]
9230    fn realize_with_optimized_route_empty_equals_arm0() {
9231        use crate::optimize::OptimizedGraph;
9232
9233        let build = || {
9234            let graph = Arc::new(RwLock::new(Graph::new()));
9235            let (lhs_id, rhs_id, add_id) = {
9236                let mut g = graph.write().unwrap();
9237                let lhs_id = g.push(Node {
9238                    op: Op::Const,
9239                    inputs: vec![],
9240                    shape: Shape::from_dims(&[3]),
9241                    dtype: DType::F32,
9242                });
9243                let rhs_id = g.push(Node {
9244                    op: Op::Const,
9245                    inputs: vec![],
9246                    shape: Shape::from_dims(&[3]),
9247                    dtype: DType::F32,
9248                });
9249                let add_id = g.push(Node {
9250                    op: Op::Add,
9251                    inputs: vec![lhs_id, rhs_id],
9252                    shape: Shape::from_dims(&[3]),
9253                    dtype: DType::F32,
9254                });
9255                g.set_target_backend(add_id, BackendId::Cpu);
9256                (lhs_id, rhs_id, add_id)
9257            };
9258            let mut inputs = StorageCache::new();
9259            inputs.insert(
9260                lhs_id,
9261                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9262                    1.0_f32, 2.0, 3.0,
9263                ]))),
9264            );
9265            inputs.insert(
9266                rhs_id,
9267                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9268                    10.0_f32, 20.0, 30.0,
9269                ]))),
9270            );
9271            (graph, add_id, inputs)
9272        };
9273
9274        let read_bytes = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9275            let guard = arc.read().unwrap();
9276            match &guard.inner {
9277                fuel_memory::BackendStorage::Cpu(c) => {
9278                    c.as_slice::<f32>().expect("f32 cast").to_vec()
9279                }
9280                _ => panic!("expected CPU output"),
9281            }
9282        };
9283
9284        // Stamp the fixture with the LIVE topology generation rather than a
9285        // hard-coded 0. The executor's chunk-boundary check compares the plan's
9286        // stamped generation against `topology_generation()`; a real
9287        // `OptimizedGraph` carries the generation snapshotted at optimize time
9288        // (`plan.rs` `compile_plan`, which reads it *after* the bindings table
9289        // is warm), so it already reflects every registered backend. Force
9290        // `global_bindings()` init here so any feature-gated auto-registration
9291        // has run and settled the counter before we read it — otherwise a stale
9292        // read would be bumped out from under us the first time realize warms
9293        // the bindings. Under default features this is 0; under
9294        // `--features vulkan`, `register_derived_gpu_caps` bumps it to 1.
9295        drop(global_bindings());
9296        let live_gen = crate::dispatch::topology_generation();
9297
9298        // Arm-0 path.
9299        let (g_a, add_a, in_a) = build();
9300        let opt_a = OptimizedGraph {
9301            roots: vec![add_a],
9302            generation: live_gen,
9303            placements: None,
9304            eviction: None,
9305        };
9306        let (arm0_arc, _) = PipelinedExecutor::realize_with_optimized(g_a, add_a, in_a, &opt_a)
9307            .expect("arm-0 realize");
9308        let arm0 = read_bytes(&arm0_arc);
9309
9310        // Empty-route path — must match arm-0 exactly.
9311        let (g_r, add_r, in_r) = build();
9312        let opt_r = OptimizedGraph {
9313            roots: vec![add_r],
9314            generation: live_gen,
9315            placements: None,
9316            eviction: None,
9317        };
9318        let empty_route = PickedRoute::new();
9319        let (route_arc, _) =
9320            PipelinedExecutor::realize_with_optimized_route(g_r, add_r, in_r, &opt_r, &empty_route)
9321                .expect("empty-route realize");
9322        let routed = read_bytes(&route_arc);
9323
9324        assert_eq!(arm0, vec![11.0, 22.0, 33.0]);
9325        assert_eq!(
9326            routed, arm0,
9327            "an empty route realizes byte-identically to arm-0 (Phase B contract)",
9328        );
9329    }
9330
9331    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
9332    /// §5): [`PipelinedExecutor::realize_with_optimized_picking_cached_env`]
9333    /// over a shared `order_cache` must (a) realize byte-identically to the
9334    /// uncached arm-0 path, on both the cold (empty cache) and warm
9335    /// (populated cache) call, and (b) actually populate the cache on the
9336    /// first call rather than silently never using it.
9337    #[test]
9338    fn realize_with_optimized_picking_cached_env_matches_arm0_cold_and_warm() {
9339        use crate::optimize::OptimizedGraph;
9340        use std::sync::OnceLock;
9341
9342        let build = || {
9343            let graph = Arc::new(RwLock::new(Graph::new()));
9344            let (lhs_id, rhs_id, add_id) = {
9345                let mut g = graph.write().unwrap();
9346                let lhs_id = g.push(Node {
9347                    op: Op::Const,
9348                    inputs: vec![],
9349                    shape: Shape::from_dims(&[3]),
9350                    dtype: DType::F32,
9351                });
9352                let rhs_id = g.push(Node {
9353                    op: Op::Const,
9354                    inputs: vec![],
9355                    shape: Shape::from_dims(&[3]),
9356                    dtype: DType::F32,
9357                });
9358                let add_id = g.push(Node {
9359                    op: Op::Add,
9360                    inputs: vec![lhs_id, rhs_id],
9361                    shape: Shape::from_dims(&[3]),
9362                    dtype: DType::F32,
9363                });
9364                g.set_target_backend(add_id, BackendId::Cpu);
9365                (lhs_id, rhs_id, add_id)
9366            };
9367            let mut inputs = StorageCache::new();
9368            inputs.insert(
9369                lhs_id,
9370                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9371                    1.0_f32, 2.0, 3.0,
9372                ]))),
9373            );
9374            inputs.insert(
9375                rhs_id,
9376                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9377                    10.0_f32, 20.0, 30.0,
9378                ]))),
9379            );
9380            (graph, add_id, inputs)
9381        };
9382        let read_bytes = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9383            let guard = arc.read().unwrap();
9384            match &guard.inner {
9385                fuel_memory::BackendStorage::Cpu(c) => {
9386                    c.as_slice::<f32>().expect("f32 cast").to_vec()
9387                }
9388                _ => panic!("expected CPU output"),
9389            }
9390        };
9391
9392        drop(global_bindings());
9393        let live_gen = crate::dispatch::topology_generation();
9394
9395        let (g, add, inputs) = build();
9396        let optimized = OptimizedGraph {
9397            roots: vec![add],
9398            generation: live_gen,
9399            placements: None,
9400            eviction: None,
9401        };
9402        let order_cache: OnceLock<Vec<NodeId>> = OnceLock::new();
9403        assert!(order_cache.get().is_none(), "sanity: cache starts empty");
9404
9405        // Cold call: cache miss, must compute AND populate.
9406        let (cold_arc, _) = PipelinedExecutor::realize_with_optimized_picking_cached_env(
9407            g.clone(),
9408            add,
9409            inputs,
9410            &optimized,
9411            &order_cache,
9412            None,
9413            None,
9414            SymEnv::default(),
9415        )
9416        .expect("cold cached realize");
9417        assert_eq!(read_bytes(&cold_arc), vec![11.0, 22.0, 33.0]);
9418        assert!(
9419            order_cache.get().is_some(),
9420            "the cold call must populate order_cache, not leave it empty"
9421        );
9422        let cached_order_after_cold = order_cache.get().unwrap().clone();
9423
9424        // Warm call: cache hit. Fresh inputs (same graph, new values) so the
9425        // realized OUTPUT differs from the cold call while the dispatch
9426        // ORDER (what's cached) must not change.
9427        let mut warm_inputs = StorageCache::new();
9428        warm_inputs.insert(
9429            g.read().unwrap().node(add).inputs[0],
9430            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9431                100.0_f32, 200.0, 300.0,
9432            ]))),
9433        );
9434        warm_inputs.insert(
9435            g.read().unwrap().node(add).inputs[1],
9436            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9437                1.0_f32, 2.0, 3.0,
9438            ]))),
9439        );
9440        let (warm_arc, _) = PipelinedExecutor::realize_with_optimized_picking_cached_env(
9441            g,
9442            add,
9443            warm_inputs,
9444            &optimized,
9445            &order_cache,
9446            None,
9447            None,
9448            SymEnv::default(),
9449        )
9450        .expect("warm cached realize");
9451        assert_eq!(
9452            read_bytes(&warm_arc),
9453            vec![101.0, 202.0, 303.0],
9454            "warm call must realize its OWN rebound inputs, not replay stale output",
9455        );
9456        assert_eq!(
9457            order_cache.get().unwrap(),
9458            &cached_order_after_cold,
9459            "the warm call must reuse the SAME cached order, not recompute a different one",
9460        );
9461    }
9462
9463    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
9464    /// §5), PM review question: does `OrderSource::Cached` weaken the
9465    /// existing `TopologyChanged` chunk-boundary check? No — proven at the
9466    /// unit level (not a live topology-bump integration test, deliberately:
9467    /// `bump_topology_generation()` mutates a process-wide atomic shared by
9468    /// every concurrently-running test in this binary, including the cold/
9469    /// warm cache test above, which reads it into a local at the start of
9470    /// ITS OWN body and would flake if another test's bump landed mid-call;
9471    /// introducing that cross-test hazard isn't worth it when the two arms'
9472    /// `generation_for` expressions are provably identical). `generation_for`
9473    /// is private to this module, so it's tested directly here: given the
9474    /// SAME `&OptimizedGraph`, `Cached` and `Optimized` must report the
9475    /// IDENTICAL generation — the chunk-boundary check that compares this
9476    /// value against the LIVE `topology_generation()` fires exactly the
9477    /// same way for both, so caching cannot silently skip or weaken it.
9478    #[test]
9479    fn cached_generation_for_matches_optimized_generation_for() {
9480        let optimized = OptimizedGraph {
9481            roots: vec![NodeId(0)],
9482            generation: 42,
9483            placements: None,
9484            eviction: None,
9485        };
9486        let order_cache: std::sync::OnceLock<Vec<NodeId>> = std::sync::OnceLock::new();
9487
9488        let optimized_gen = generation_for(&OrderSource::Optimized {
9489            optimized: &optimized,
9490            route: None,
9491        });
9492        let cached_gen = generation_for(&OrderSource::Cached {
9493            optimized: &optimized,
9494            order_cache: &order_cache,
9495        });
9496        assert_eq!(
9497            optimized_gen,
9498            Some(42),
9499            "sanity: Optimized reports the OptimizedGraph's own generation",
9500        );
9501        assert_eq!(
9502            cached_gen, optimized_gen,
9503            "Cached must report the SAME generation as Optimized for the same \
9504             OptimizedGraph -- the TopologyChanged check cannot tell the two apart, \
9505             by construction, so caching cannot silently weaken it",
9506        );
9507    }
9508
9509    /// **PR-C3 reorder-invariance gate (CPU, runnable — ORDERING level).**
9510    /// The auto-overlap reorder is a HINT: it changes only *which order*
9511    /// independent device runs dispatch in, never *which* nodes run nor the
9512    /// result. The byte-identical-OUTPUT proof is necessarily LIVE (the
9513    /// reorder fires only on a ≥2-device graph, which needs ≥2 real backends
9514    /// to realize — see `cuda_vulkan_multidevice_realize_live`'s
9515    /// `[22,86,192,340]` oracle, which now flows through this reorder, plus
9516    /// the dual-GPU `cuda_vulkan_overlap_bench_live` arbitrary-graph
9517    /// auto-overlap gate). THIS test proves the ordering-level invariant on a
9518    /// CPU-only path: the C3 reorder of a two-device graph is a valid
9519    /// topological **permutation** of the un-reordered topo order — same node
9520    /// multiset, every node still after its inputs — that genuinely DIFFERS
9521    /// from the un-reordered order (so the reorder fired). Because the
9522    /// executor caches each node's result and every op is deterministic,
9523    /// realizing any valid topological order yields identical bytes; this
9524    /// test guards the precondition (a valid permutation) that makes that so.
9525    #[test]
9526    fn c3_reorder_is_a_valid_topo_permutation() {
9527        // Two INDEPENDENT device sub-chains over distinct consts reconverging
9528        // at a final CUDA add, the Vulkan root bridged to CUDA by an explicit
9529        // Op::Copy (a residency seam = its own run). Reconverge inputs in the
9530        // "wrong" (cuda-first) order, the order the un-reordered topo DFS pops
9531        // CUDA-last — exactly the arbitrary-graph shape the auto-overlap pass
9532        // must fix. The chains are UNARY (Relu) so each stays a single
9533        // contiguous run (no const-re-read fan-in fragmenting them), exactly
9534        // like the live benchmark's `relu(mul·add)` chains; the CUDA chain is
9535        // HEAVIER (4 vs 2) so the critical-path reorder emits it first.
9536        // (Stamps only; not realized here — the ordering proof, CPU-runnable.)
9537        let n = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9538            g.push(Node {
9539                op,
9540                inputs,
9541                shape: Shape::from_dims(&[3]),
9542                dtype: DType::F32,
9543            })
9544        };
9545        let mut g = Graph::new();
9546        let ca = n(&mut g, Op::Const, vec![]);
9547        let cb = n(&mut g, Op::Const, vec![]);
9548        // CUDA chain — HEAVIER (4 unary stages, one contiguous run).
9549        let mut cprev = ca;
9550        for _ in 0..4 {
9551            cprev = n(&mut g, Op::Relu, vec![cprev]);
9552            g.set_target_backend(cprev, BackendId::Cuda);
9553        }
9554        let c2 = cprev; // CUDA chunk root
9555        // Vulkan chain — lighter (2 unary stages).
9556        let mut vprev = cb;
9557        for _ in 0..2 {
9558            vprev = n(&mut g, Op::Relu, vec![vprev]);
9559            g.set_target_backend(vprev, BackendId::Vulkan);
9560        }
9561        let v2 = vprev; // Vulkan chunk root
9562        // Vulkan -> CUDA copy (residency seam), then reconverge on CUDA with
9563        // inputs [cuda_root, copy] (cuda-first).
9564        let copy = g.push(Node {
9565            op: Op::Copy {
9566                target: DeviceLocation::Cuda { gpu_id: 0 },
9567            },
9568            inputs: vec![v2],
9569            shape: Shape::from_dims(&[3]),
9570            dtype: DType::F32,
9571        });
9572        g.set_target_backend(copy, BackendId::Cuda);
9573        let out = n(&mut g, Op::Add, vec![c2, copy]);
9574        g.set_target_backend(out, BackendId::Cuda);
9575
9576        let unreordered = execution_plan(&g, &[out]);
9577        let reordered = fuel_graph::lower_runs_arm0(&g, &[out]);
9578
9579        // (1) The reorder FIRED — the order changed (else the test is
9580        //     vacuous + auto-overlap did nothing on an arbitrary graph).
9581        assert_ne!(
9582            reordered, unreordered,
9583            "the C3 reorder must change the order on a two-device graph; \
9584             reordered={reordered:?} unreordered={unreordered:?}",
9585        );
9586
9587        // (2) Same node multiset — a permutation, no add/drop.
9588        let mut a = unreordered.clone();
9589        let mut b = reordered.clone();
9590        a.sort();
9591        b.sort();
9592        assert_eq!(a, b, "the reorder is a permutation of the same node set");
9593
9594        // (3) The reordered order is a VALID topological order: every node
9595        //     appears after all of its inputs that are in the order.
9596        let pos: std::collections::HashMap<NodeId, usize> = reordered
9597            .iter()
9598            .enumerate()
9599            .map(|(i, &node)| (node, i))
9600            .collect();
9601        for (i, &node) in reordered.iter().enumerate() {
9602            for &inp in &g.node(node).inputs {
9603                if let Some(&j) = pos.get(&inp) {
9604                    assert!(
9605                        j < i,
9606                        "input {inp:?} of {node:?} must precede it in the reordered \
9607                         order; reordered={reordered:?}",
9608                    );
9609                }
9610            }
9611        }
9612
9613        // (4) The overlap-relevant property: BOTH device producer chunks
9614        //     (the CUDA root c2, the Vulkan root v2) are emitted BEFORE the
9615        //     host-blocking cross-device copy — the A4b overlap topology the
9616        //     un-reordered cuda-last DFS violates — AND the HEAVIER CUDA chunk
9617        //     is emitted first (critical-path: the auto-submit device runs
9618        //     earliest, the live-overlap regression guard).
9619        let p = |node: NodeId| pos[&node];
9620        assert!(p(c2) < p(copy), "CUDA chunk before the cross-device copy");
9621        assert!(p(v2) < p(copy), "Vulkan chunk before the cross-device copy");
9622        assert!(
9623            p(c2) < p(v2),
9624            "the heavier CUDA chunk is emitted before the lighter Vulkan chunk \
9625             (critical-path heavy-first); reordered={reordered:?}",
9626        );
9627    }
9628
9629    /// **C3 follow-on — the OPERAND-ORDER-INVARIANCE gate (CPU, runnable —
9630    /// the reliable operand-independence proof).** The residual the live
9631    /// `cuda_vulkan_overlap_bench_live` benchmark targets is whether the
9632    /// reconverge OPERAND order (`xc.add(&xv)` vs `xv.add(&xc)`) changes the
9633    /// wall-clock overlap. Wall-clock is thermally noisy on a heterogeneous
9634    /// dev box; the DETERMINISTIC root guarantee is this: the C3-reordered
9635    /// dispatch order the executor consumes is **byte-identical for both
9636    /// operand orders**. If the lowered order is the same, the executor
9637    /// processes the SAME WorkItem stream with the SAME cross-device
9638    /// submit/wait timing, so overlap cannot depend on the operand order.
9639    ///
9640    /// This builds the SAME two-device reconverge as
9641    /// `c3_reorder_is_a_valid_topo_permutation` but TWICE — once cuda-first
9642    /// (`add(cuda_root, copy)`), once vulkan-first (`add(copy, cuda_root)`)
9643    /// — over structurally identical graphs (same node ids, only the
9644    /// reconverge's two inputs swapped) and asserts `lower_runs_arm0` emits
9645    /// the identical op/device run sequence. The live executor trace confirms
9646    /// the same: both operand orders produce the identical WorkItem stream
9647    /// (the eager-submit/drain/wait sequence at every cross-device copy is the
9648    /// same, and the CUDA chunk is enqueued first in both).
9649    #[test]
9650    fn c3_reorder_is_operand_order_invariant() {
9651        // Build the two-device reconverge with the reconverge inputs in the
9652        // given order; return (graph, out) over a FRESH graph so node ids line
9653        // up 1:1 between the two builds (only the add's input order differs).
9654        let build = |cuda_first: bool| -> (Graph, NodeId) {
9655            let n = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9656                g.push(Node {
9657                    op,
9658                    inputs,
9659                    shape: Shape::from_dims(&[3]),
9660                    dtype: DType::F32,
9661                })
9662            };
9663            let mut g = Graph::new();
9664            let ca = n(&mut g, Op::Const, vec![]);
9665            let cb = n(&mut g, Op::Const, vec![]);
9666            let mut cprev = ca;
9667            for _ in 0..4 {
9668                cprev = n(&mut g, Op::Relu, vec![cprev]);
9669                g.set_target_backend(cprev, BackendId::Cuda);
9670            }
9671            let c2 = cprev;
9672            let mut vprev = cb;
9673            for _ in 0..2 {
9674                vprev = n(&mut g, Op::Relu, vec![vprev]);
9675                g.set_target_backend(vprev, BackendId::Vulkan);
9676            }
9677            let v2 = vprev;
9678            let copy = g.push(Node {
9679                op: Op::Copy {
9680                    target: DeviceLocation::Cuda { gpu_id: 0 },
9681                },
9682                inputs: vec![v2],
9683                shape: Shape::from_dims(&[3]),
9684                dtype: DType::F32,
9685            });
9686            g.set_target_backend(copy, BackendId::Cuda);
9687            // The ONE knob: the reconverge's two inputs, swapped.
9688            let inputs = if cuda_first {
9689                vec![c2, copy]
9690            } else {
9691                vec![copy, c2]
9692            };
9693            let out = n(&mut g, Op::Add, inputs);
9694            g.set_target_backend(out, BackendId::Cuda);
9695            (g, out)
9696        };
9697
9698        let (g_cf, out_cf) = build(true);
9699        let (g_vf, out_vf) = build(false);
9700
9701        // Lower both via the production path (dispatch_order → lower_runs_arm0
9702        // → device_alternating_order, the C3 reorder).
9703        let order_cf = fuel_graph::lower_runs_arm0(&g_cf, &[out_cf]);
9704        let order_vf = fuel_graph::lower_runs_arm0(&g_vf, &[out_vf]);
9705
9706        // The decisive guarantee: the lowered dispatch order — as an
9707        // (op, device) sequence — is IDENTICAL for both operand orders. (Node
9708        // ids can differ if the build assigned them differently, but here the
9709        // builds are structurally identical so even the ids match; compare the
9710        // op/device sequence to be robust + descriptive on failure.)
9711        let tag = |g: &Graph, ids: &[NodeId]| -> Vec<(String, Option<BackendId>)> {
9712            ids.iter()
9713                .map(|&id| (format!("{:?}", g.node(id).op), g.target_backend(id)))
9714                .collect()
9715        };
9716        let seq_cf = tag(&g_cf, &order_cf);
9717        let seq_vf = tag(&g_vf, &order_vf);
9718        assert_eq!(
9719            seq_cf, seq_vf,
9720            "the C3-reordered dispatch order MUST be identical for both \
9721             reconverge operand orders (operand-order-invariance — the \
9722             executor then sees the same WorkItem stream regardless of \
9723             operand order, so overlap is operand-insensitive).\n\
9724             cuda-first = {seq_cf:?}\nvulkan-first = {seq_vf:?}",
9725        );
9726    }
9727
9728    /// A selector that always takes the LAST arm (arm 1) so a non-arm-0
9729    /// pick is observable (a `WinnerSelector` picks arm-0 ⇒ empty route).
9730    #[cfg(test)]
9731    #[derive(Debug)]
9732    struct PickLast;
9733    #[cfg(test)]
9734    impl RuntimeSelector for PickLast {
9735        fn select<'a>(
9736            &self,
9737            set: &'a crate::ranker::AlternativeSet,
9738        ) -> Option<&'a crate::ranker::Candidate> {
9739            set.alternatives().last()
9740        }
9741    }
9742
9743    /// Build the 2-arm diamond (mirrors `route_picker::tests::diamond`):
9744    /// arm-0 on CUDA, arm-1 on CPU; the arm exits carry their
9745    /// `target_backend` so the picker reads each arm's placement. Returns
9746    /// `(graph_arc, branch, post)`.
9747    #[cfg(test)]
9748    fn picking_diamond() -> (Arc<RwLock<Graph>>, NodeId, NodeId) {
9749        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9750            g.push(Node {
9751                op,
9752                inputs,
9753                shape: Shape::from_dims(&[2]),
9754                dtype: DType::F32,
9755            })
9756        };
9757        let mut g = Graph::new();
9758        let pre = node(&mut g, Op::Const, vec![]);
9759        let diverge = node(&mut g, Op::Relu, vec![pre]);
9760        let arm0 = node(&mut g, Op::Silu, vec![diverge]);
9761        let arm1 = node(&mut g, Op::GeluTanh, vec![diverge]);
9762        g.set_target_backend(arm0, BackendId::Cuda);
9763        g.set_target_backend(arm1, BackendId::Cpu);
9764        let reconverge = node(&mut g, Op::Relu, vec![arm0]);
9765        let mut b = g.open_branch(diverge);
9766        b.add_arm(arm0);
9767        b.add_arm(arm1);
9768        let branch = b
9769            .finalize_branches(&mut g, reconverge)
9770            .expect("well-formed 2-arm branch")
9771            .expect("2 arms survive");
9772        let post = node(&mut g, Op::Tanh, vec![reconverge]);
9773        (Arc::new(RwLock::new(g)), branch, post)
9774    }
9775
9776    /// Step E Phase C, PR C1: the streaming picking entry's gate.
9777    /// `streaming_pick_for` (the streaming successor of the old one-shot
9778    /// `pick_route_for`) must (1) return `Some(pick)` when a selector + a
9779    /// branch are present (⇒ the `OrderSource::Streaming` walk), (2) return
9780    /// `None` with no selector (the `runtime_selector_disabled` opt-out ⇒
9781    /// arm-0), and (3) short-circuit to `None` on a branchless graph (the
9782    /// fast-path ⇒ the untouched `dispatch_order` lowering).
9783    #[test]
9784    fn streaming_pick_for_gates() {
9785        let (graph, _branch, post) = picking_diamond();
9786        let _ = post;
9787
9788        // (1) selector + branch ⇒ Some(pick).
9789        let sel: Arc<dyn RuntimeSelector> = Arc::new(PickLast);
9790        assert!(
9791            PipelinedExecutor::streaming_pick_for(&graph, Some(sel.clone()), None)
9792                .expect("ok")
9793                .is_some(),
9794            "selector + branch ⇒ a streaming pick",
9795        );
9796
9797        // (2) no selector ⇒ None (arm-0 lowering).
9798        assert!(
9799            PipelinedExecutor::streaming_pick_for(&graph, None, None)
9800                .expect("ok")
9801                .is_none(),
9802            "no selector ⇒ no streaming pick (arm-0 lowering)",
9803        );
9804
9805        // (3) branchless graph + selector ⇒ None (the fast-path).
9806        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9807            g.push(Node {
9808                op,
9809                inputs,
9810                shape: Shape::from_dims(&[2]),
9811                dtype: DType::F32,
9812            })
9813        };
9814        let bl_graph = {
9815            let mut g = Graph::new();
9816            let c1 = node(&mut g, Op::Const, vec![]);
9817            let c2 = node(&mut g, Op::Const, vec![]);
9818            let add = node(&mut g, Op::Add, vec![c1, c2]);
9819            g.set_target_backend(add, BackendId::Cpu);
9820            Arc::new(RwLock::new(g))
9821        };
9822        assert!(
9823            PipelinedExecutor::streaming_pick_for(&bl_graph, Some(sel), None)
9824                .expect("ok")
9825                .is_none(),
9826            "branchless graph ⇒ no branches ⇒ no streaming pick (fast-path)",
9827        );
9828    }
9829
9830    /// **C1 byte-identity gate (executor layer).** The STREAMED dispatch
9831    /// order — produced by the compiler thread's lazy per-branch resolution
9832    /// (`walk_picked_route_streaming` over `resolve_branch`, the same path
9833    /// `order_for(OrderSource::Streaming)` collects) — equals the ONE-SHOT
9834    /// order (`lower_picked_route` over the route the eager `pick_route`
9835    /// resolves) on the branched diamond, for both arm-0 (WinnerSelector)
9836    /// and arm-1 (PickLast). This is the proof that C1 changes *when* a
9837    /// branch resolves, not *which* arm — the same selector, the same
9838    /// `resolve_branch`, the same emitted order.
9839    #[test]
9840    fn streamed_order_equals_one_shot() {
9841        let (graph, _branch, post) = picking_diamond();
9842        let g = graph.read().unwrap();
9843        let bindings = global_bindings();
9844
9845        for sel in [
9846            Arc::new(crate::ranker::WinnerSelector) as Arc<dyn RuntimeSelector>,
9847            Arc::new(PickLast) as Arc<dyn RuntimeSelector>,
9848        ] {
9849            // One-shot: resolve the whole route, then lower.
9850            let one_shot_route = pick_route(&g, &[post], &bindings, sel.as_ref(), None);
9851            let one_shot = fuel_graph::lower_picked_route(&g, &[post], &one_shot_route);
9852
9853            // Streamed: resolve each branch lazily at the frontier via the
9854            // SAME `resolve_branch` the compiler thread uses.
9855            let streamed = fuel_graph::lower_picked_route_streaming(&g, &[post], |branch| {
9856                resolve_branch(&g, branch, &bindings, sel.as_ref())
9857            });
9858
9859            assert_eq!(
9860                streamed, one_shot,
9861                "streamed order must equal one-shot for selector {sel:?}",
9862            );
9863        }
9864    }
9865
9866    /// Realizing a node whose target_backend isn't set surfaces a
9867    /// typed error (no panic).
9868    #[test]
9869    fn pipelined_errors_on_unset_target_backend() {
9870        let graph = Arc::new(RwLock::new(Graph::new()));
9871        let (lhs_id, rhs_id, add_id) = {
9872            let mut g = graph.write().unwrap();
9873            let lhs = g.push(Node {
9874                op: Op::Const,
9875                inputs: vec![],
9876                shape: Shape::from_dims(&[2]),
9877                dtype: DType::F32,
9878            });
9879            let rhs = g.push(Node {
9880                op: Op::Const,
9881                inputs: vec![],
9882                shape: Shape::from_dims(&[2]),
9883                dtype: DType::F32,
9884            });
9885            // Deliberately do NOT call set_target_backend on the Add.
9886            let add = g.push(Node {
9887                op: Op::Add,
9888                inputs: vec![lhs, rhs],
9889                shape: Shape::from_dims(&[2]),
9890                dtype: DType::F32,
9891            });
9892            (lhs, rhs, add)
9893        };
9894
9895        let mut inputs = StorageCache::new();
9896        inputs.insert(
9897            lhs_id,
9898            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]))),
9899        );
9900        inputs.insert(
9901            rhs_id,
9902            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[3.0_f32, 4.0]))),
9903        );
9904
9905        let result = PipelinedExecutor::realize(graph, add_id, inputs);
9906        assert!(result.is_err(), "missing target_backend must error");
9907        let msg = result.unwrap_err().to_string();
9908        assert!(
9909            msg.contains("target_backend"),
9910            "error names the unmet precondition: {msg}"
9911        );
9912    }
9913
9914    /// Realizing a Const-only graph adopts the pre-seeded input
9915    /// without calling any kernel.
9916    #[test]
9917    fn pipelined_realize_const_only() {
9918        let storage = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0, 7.0]);
9919
9920        let graph = Arc::new(RwLock::new(Graph::new()));
9921        let const_id = {
9922            let mut g = graph.write().unwrap();
9923            g.push(Node {
9924                op: Op::Const,
9925                inputs: vec![],
9926                shape: Shape::from_dims(&[3]),
9927                dtype: DType::F32,
9928            })
9929        };
9930
9931        let mut inputs = StorageCache::new();
9932        inputs.insert(const_id, Arc::new(RwLock::new(storage)));
9933
9934        let (result_arc, _) =
9935            PipelinedExecutor::realize(graph, const_id, inputs).expect("realize const");
9936        let guard = result_arc.read().unwrap();
9937        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
9938            let typed: &[f32] = c.as_slice().unwrap();
9939            assert_eq!(typed, &[5.0, 6.0, 7.0]);
9940        }
9941    }
9942
9943    /// Missing input-cache entry for a Const surfaces a typed error.
9944    #[test]
9945    fn pipelined_errors_on_missing_const_input() {
9946        let graph = Arc::new(RwLock::new(Graph::new()));
9947        let const_id = {
9948            let mut g = graph.write().unwrap();
9949            g.push(Node {
9950                op: Op::Const,
9951                inputs: vec![],
9952                shape: Shape::from_dims(&[2]),
9953                dtype: DType::F32,
9954            })
9955        };
9956        // Deliberately empty input cache.
9957        let inputs = StorageCache::new();
9958        let result = PipelinedExecutor::realize(graph, const_id, inputs);
9959        assert!(result.is_err());
9960    }
9961
9962    /// E2E: 2-node graph (Const + Relu) — exercises the unary
9963    /// dispatch wrapper + kernel through the pipelined executor.
9964    #[test]
9965    fn pipelined_realize_const_relu() {
9966        let storage = fuel_memory::from_slice_cpu(&[-1.0_f32, 0.0, 0.5, -3.5, 7.25]);
9967        let graph = Arc::new(RwLock::new(Graph::new()));
9968        let (in_id, relu_id) = {
9969            let mut g = graph.write().unwrap();
9970            let in_id = g.push(Node {
9971                op: Op::Const,
9972                inputs: vec![],
9973                shape: Shape::from_dims(&[5]),
9974                dtype: DType::F32,
9975            });
9976            let relu_id = g.push(Node {
9977                op: Op::Relu,
9978                inputs: vec![in_id],
9979                shape: Shape::from_dims(&[5]),
9980                dtype: DType::F32,
9981            });
9982            g.set_target_backend(relu_id, BackendId::Cpu);
9983            (in_id, relu_id)
9984        };
9985        let mut inputs = StorageCache::new();
9986        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
9987
9988        let (result_arc, _) = PipelinedExecutor::realize(graph, relu_id, inputs).expect("realize");
9989        let guard = result_arc.read().unwrap();
9990        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
9991            let typed: &[f32] = c.as_slice().expect("f32 cast");
9992            assert_eq!(typed, &[0.0, 0.0, 0.5, 0.0, 7.25]);
9993        }
9994    }
9995
9996    /// E2E: Const + Const + Sub + Mul + Div — exercises three more
9997    /// of the freshly-migrated binary kernels in one graph. Verifies
9998    /// that intermediates flow through the cache as expected.
9999    #[test]
10000    fn pipelined_realize_chained_binary_ops() {
10001        let a_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
10002        let b_storage = fuel_memory::from_slice_cpu(&[3.0_f32, 5.0]);
10003        let c_storage = fuel_memory::from_slice_cpu(&[2.0_f32, 4.0]);
10004
10005        let graph = Arc::new(RwLock::new(Graph::new()));
10006        let (a_id, b_id, c_id, sub_id, mul_id, div_id) = {
10007            let mut g = graph.write().unwrap();
10008            let a = g.push(Node {
10009                op: Op::Const,
10010                inputs: vec![],
10011                shape: Shape::from_dims(&[2]),
10012                dtype: DType::F32,
10013            });
10014            let b = g.push(Node {
10015                op: Op::Const,
10016                inputs: vec![],
10017                shape: Shape::from_dims(&[2]),
10018                dtype: DType::F32,
10019            });
10020            let c = g.push(Node {
10021                op: Op::Const,
10022                inputs: vec![],
10023                shape: Shape::from_dims(&[2]),
10024                dtype: DType::F32,
10025            });
10026            // (a - b)         = [7, 15]
10027            let sub = g.push(Node {
10028                op: Op::Sub,
10029                inputs: vec![a, b],
10030                shape: Shape::from_dims(&[2]),
10031                dtype: DType::F32,
10032            });
10033            // (a - b) * c     = [14, 60]
10034            let mul = g.push(Node {
10035                op: Op::Mul,
10036                inputs: vec![sub, c],
10037                shape: Shape::from_dims(&[2]),
10038                dtype: DType::F32,
10039            });
10040            // ((a-b)*c) / b   = [14/3, 12]
10041            let div = g.push(Node {
10042                op: Op::Div,
10043                inputs: vec![mul, b],
10044                shape: Shape::from_dims(&[2]),
10045                dtype: DType::F32,
10046            });
10047            g.set_target_backend(sub, BackendId::Cpu);
10048            g.set_target_backend(mul, BackendId::Cpu);
10049            g.set_target_backend(div, BackendId::Cpu);
10050            (a, b, c, sub, mul, div)
10051        };
10052
10053        let _ = (sub_id, mul_id);
10054        let mut inputs = StorageCache::new();
10055        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
10056        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
10057        inputs.insert(c_id, Arc::new(RwLock::new(c_storage)));
10058
10059        let (result_arc, _) = PipelinedExecutor::realize(graph, div_id, inputs).expect("realize");
10060        let guard = result_arc.read().unwrap();
10061        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
10062            let typed: &[f32] = c.as_slice().unwrap();
10063            assert!((typed[0] - (14.0_f32 / 3.0)).abs() < 1e-6);
10064            assert!((typed[1] - 12.0).abs() < 1e-6);
10065        }
10066    }
10067
10068    /// E2E: Const + Transpose — verifies metadata-only view ops
10069    /// share the input's Storage Arc and produce a strided Layout.
10070    /// Stage 3 of Layout-on-Node.
10071    #[test]
10072    fn pipelined_realize_transpose_is_metadata_only() {
10073        // shape [2, 3]; transpose → shape [3, 2], strided
10074        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
10075        let graph = Arc::new(RwLock::new(Graph::new()));
10076        let (in_id, t_id) = {
10077            let mut g = graph.write().unwrap();
10078            let in_id = g.push(Node {
10079                op: Op::Const,
10080                inputs: vec![],
10081                shape: Shape::from_dims(&[2, 3]),
10082                dtype: DType::F32,
10083            });
10084            let t_id = g.push(Node {
10085                op: Op::Transpose,
10086                inputs: vec![in_id],
10087                shape: Shape::from_dims(&[3, 2]),
10088                dtype: DType::F32,
10089            });
10090            // Note: NO set_target_backend — transpose is metadata-only
10091            // and doesn't run on a backend.
10092            (in_id, t_id)
10093        };
10094        let mut inputs = StorageCache::new();
10095        let in_arc = Arc::new(RwLock::new(storage));
10096        inputs.insert(in_id, Arc::clone(&in_arc));
10097
10098        let (result_arc, result_layout) =
10099            PipelinedExecutor::realize(graph, t_id, inputs).expect("realize");
10100
10101        // The output Storage Arc is the SAME Arc as the input —
10102        // metadata-only adoption shares bytes.
10103        assert!(
10104            Arc::ptr_eq(&result_arc, &in_arc),
10105            "transpose must share input bytes"
10106        );
10107
10108        // The output Layout is the transposed view.
10109        assert_eq!(result_layout.shape().dims(), &[3, 2]);
10110        assert_eq!(result_layout.stride(), &[1, 3]);
10111        assert!(!result_layout.is_contiguous());
10112    }
10113
10114    /// E2E: Const + Flip(dim=0) — verifies Op::Flip is metadata-only.
10115    /// The output Storage Arc must be the SAME Arc (no copy);
10116    /// the output Layout has a negated stride at dim 0 and a
10117    /// shifted start_offset.
10118    #[test]
10119    fn pipelined_realize_flip_is_metadata_only() {
10120        // shape [3, 4]; flip dim 0 → shape [3, 4], stride [-4, 1], offset 8.
10121        let data: Vec<f32> = (1..=12).map(|x| x as f32).collect();
10122        let storage = fuel_memory::from_slice_cpu(&data);
10123        let graph = Arc::new(RwLock::new(Graph::new()));
10124        let (in_id, f_id) = {
10125            let mut g = graph.write().unwrap();
10126            let in_id = g.push(Node {
10127                op: Op::Const,
10128                inputs: vec![],
10129                shape: Shape::from_dims(&[3, 4]),
10130                dtype: DType::F32,
10131            });
10132            let f_id = g.push(Node {
10133                op: Op::Flip { dim: 0 },
10134                inputs: vec![in_id],
10135                shape: Shape::from_dims(&[3, 4]),
10136                dtype: DType::F32,
10137            });
10138            (in_id, f_id)
10139        };
10140        let mut inputs = StorageCache::new();
10141        let in_arc = Arc::new(RwLock::new(storage));
10142        inputs.insert(in_id, Arc::clone(&in_arc));
10143
10144        let (result_arc, result_layout) =
10145            PipelinedExecutor::realize(graph, f_id, inputs).expect("realize");
10146
10147        assert!(
10148            Arc::ptr_eq(&result_arc, &in_arc),
10149            "flip must share input bytes"
10150        );
10151        assert_eq!(result_layout.shape().dims(), &[3, 4]);
10152        assert_eq!(result_layout.stride(), &[-4_isize, 1]);
10153        assert_eq!(result_layout.start_offset(), 8);
10154        assert!(!result_layout.is_contiguous());
10155    }
10156
10157    /// E2E: Const + Permute(rank-3 axes [2, 0, 1]) — verifies the
10158    /// general permute path through metadata-only adoption.
10159    #[test]
10160    fn pipelined_realize_permute_is_metadata_only() {
10161        // shape [2, 3, 4]; permute axes [2, 0, 1] → shape [4, 2, 3]
10162        let data: Vec<f32> = (1..=24).map(|x| x as f32).collect();
10163        let storage = fuel_memory::from_slice_cpu(&data);
10164        let graph = Arc::new(RwLock::new(Graph::new()));
10165        let (in_id, p_id) = {
10166            let mut g = graph.write().unwrap();
10167            let in_id = g.push(Node {
10168                op: Op::Const,
10169                inputs: vec![],
10170                shape: Shape::from_dims(&[2, 3, 4]),
10171                dtype: DType::F32,
10172            });
10173            let p_id = g.push(Node {
10174                op: Op::Permute(vec![2, 0, 1]),
10175                inputs: vec![in_id],
10176                shape: Shape::from_dims(&[4, 2, 3]),
10177                dtype: DType::F32,
10178            });
10179            (in_id, p_id)
10180        };
10181        let mut inputs = StorageCache::new();
10182        let in_arc = Arc::new(RwLock::new(storage));
10183        inputs.insert(in_id, Arc::clone(&in_arc));
10184
10185        let (result_arc, result_layout) =
10186            PipelinedExecutor::realize(graph, p_id, inputs).expect("realize");
10187
10188        assert!(Arc::ptr_eq(&result_arc, &in_arc));
10189        assert_eq!(result_layout.shape().dims(), &[4, 2, 3]);
10190        // Original strides for shape [2, 3, 4] are [12, 4, 1].
10191        // After permute axes [2, 0, 1]: [strides[2], strides[0], strides[1]] = [1, 12, 4].
10192        assert_eq!(result_layout.stride(), &[1, 12, 4]);
10193    }
10194
10195    /// E2E: Const + Cast(f32→f64) — verifies cast through the
10196    /// pipelined executor. Output Storage has the target dtype;
10197    /// bytes encode the widened values.
10198    #[test]
10199    fn pipelined_realize_cast_f32_to_f64() {
10200        let storage = fuel_memory::from_slice_cpu(&[1.5_f32, -2.25, 100.0]);
10201        let graph = Arc::new(RwLock::new(Graph::new()));
10202        let (in_id, c_id) = {
10203            let mut g = graph.write().unwrap();
10204            let in_id = g.push(Node {
10205                op: Op::Const,
10206                inputs: vec![],
10207                shape: Shape::from_dims(&[3]),
10208                dtype: DType::F32,
10209            });
10210            let c_id = g.push(Node {
10211                op: Op::Cast(DType::F64),
10212                inputs: vec![in_id],
10213                shape: Shape::from_dims(&[3]),
10214                dtype: DType::F64,
10215            });
10216            g.set_target_backend(c_id, BackendId::Cpu);
10217            (in_id, c_id)
10218        };
10219        let mut inputs = StorageCache::new();
10220        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10221
10222        let (result_arc, result_layout) =
10223            PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
10224        assert_eq!(result_layout.shape().dims(), &[3]);
10225
10226        let guard = result_arc.read().unwrap();
10227        assert_eq!(guard.dtype, DType::F64);
10228        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10229            panic!("expected Cpu storage");
10230        };
10231        assert_eq!(c.as_slice::<f64>().unwrap(), &[1.5_f64, -2.25, 100.0]);
10232    }
10233
10234    /// E2E: Const + Cast(f32→bf16) + Cast(bf16→f32) — round trip
10235    /// through bf16; verifies the Cast wrapper's source-dtype
10236    /// dispatch (different sources hit different match arms).
10237    /// Inputs chosen to round-trip exactly through bf16.
10238    #[test]
10239    fn pipelined_realize_cast_round_trip_via_bf16() {
10240        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, -3.0, 0.5]);
10241        let graph = Arc::new(RwLock::new(Graph::new()));
10242        let (in_id, c1_id, c2_id) = {
10243            let mut g = graph.write().unwrap();
10244            let in_id = g.push(Node {
10245                op: Op::Const,
10246                inputs: vec![],
10247                shape: Shape::from_dims(&[4]),
10248                dtype: DType::F32,
10249            });
10250            let c1_id = g.push(Node {
10251                op: Op::Cast(DType::BF16),
10252                inputs: vec![in_id],
10253                shape: Shape::from_dims(&[4]),
10254                dtype: DType::BF16,
10255            });
10256            let c2_id = g.push(Node {
10257                op: Op::Cast(DType::F32),
10258                inputs: vec![c1_id],
10259                shape: Shape::from_dims(&[4]),
10260                dtype: DType::F32,
10261            });
10262            g.set_target_backend(c1_id, BackendId::Cpu);
10263            g.set_target_backend(c2_id, BackendId::Cpu);
10264            (in_id, c1_id, c2_id)
10265        };
10266        let _ = c1_id;
10267        let mut inputs = StorageCache::new();
10268        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10269
10270        let (result_arc, _) = PipelinedExecutor::realize(graph, c2_id, inputs).expect("realize");
10271        let guard = result_arc.read().unwrap();
10272        assert_eq!(guard.dtype, DType::F32);
10273        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10274            panic!("expected Cpu storage");
10275        };
10276        assert_eq!(c.as_slice::<f32>().unwrap(), &[1.0_f32, 2.0, -3.0, 0.5]);
10277    }
10278
10279    /// E2E: Const + Slice — slice is metadata-only; the output Arc
10280    /// shares bytes with the input, and the Layout's start_offset
10281    /// + narrowed shape reflect the slice. Stage 3 of Layout-on-Node
10282    ///
10283    /// extended to cover Op::Slice via Layout::narrow.
10284    #[test]
10285    fn pipelined_realize_slice_is_metadata_only() {
10286        // shape [5]; slice dim 0 from index 1 with len 3 → shape [3]
10287        // Source: [10, 20, 30, 40, 50]; slice → [20, 30, 40]
10288        let storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0]);
10289        let graph = Arc::new(RwLock::new(Graph::new()));
10290        let (in_id, s_id) = {
10291            let mut g = graph.write().unwrap();
10292            let in_id = g.push(Node {
10293                op: Op::Const,
10294                inputs: vec![],
10295                shape: Shape::from_dims(&[5]),
10296                dtype: DType::F32,
10297            });
10298            let s_id = g.push(Node {
10299                op: Op::Slice {
10300                    dim: 0,
10301                    start: 1,
10302                    len: 3,
10303                },
10304                inputs: vec![in_id],
10305                shape: Shape::from_dims(&[3]),
10306                dtype: DType::F32,
10307            });
10308            (in_id, s_id)
10309        };
10310        let mut inputs = StorageCache::new();
10311        let in_arc = Arc::new(RwLock::new(storage));
10312        inputs.insert(in_id, Arc::clone(&in_arc));
10313
10314        let (result_arc, result_layout) =
10315            PipelinedExecutor::realize(graph, s_id, inputs).expect("realize");
10316
10317        // Bytes shared with the input.
10318        assert!(Arc::ptr_eq(&result_arc, &in_arc));
10319        assert_eq!(result_layout.shape().dims(), &[3]);
10320        // Slice into a contiguous source: the resulting layout has
10321        // start_offset = original_stride[0] * start = 1 * 1 = 1,
10322        // and stride [1] (still contiguous within the narrowed dim).
10323        assert_eq!(result_layout.start_offset(), 1);
10324        assert_eq!(result_layout.stride(), &[1]);
10325    }
10326
10327    /// E2E: Const + Slice + SumAll — slice is metadata-only, but
10328    /// sum needs contiguous bytes, so auto-Contiguize materializes
10329    /// the slice before reduce. Tests the stage 3+4 integration
10330    /// through Op::Slice. Sum of `[20, 30, 40]` is 90.
10331    #[test]
10332    fn pipelined_realize_slice_then_sum_all() {
10333        let storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0]);
10334        let graph = Arc::new(RwLock::new(Graph::new()));
10335        let (in_id, s_id, sum_id) = {
10336            let mut g = graph.write().unwrap();
10337            let in_id = g.push(Node {
10338                op: Op::Const,
10339                inputs: vec![],
10340                shape: Shape::from_dims(&[5]),
10341                dtype: DType::F32,
10342            });
10343            let s_id = g.push(Node {
10344                op: Op::Slice {
10345                    dim: 0,
10346                    start: 1,
10347                    len: 3,
10348                },
10349                inputs: vec![in_id],
10350                shape: Shape::from_dims(&[3]),
10351                dtype: DType::F32,
10352            });
10353            let sum_id = g.push(Node {
10354                op: Op::SumAll,
10355                inputs: vec![s_id],
10356                shape: Shape::from_dims(&[]),
10357                dtype: DType::F32,
10358            });
10359            g.set_target_backend(sum_id, BackendId::Cpu);
10360            (in_id, s_id, sum_id)
10361        };
10362        let _ = s_id;
10363        let mut inputs = StorageCache::new();
10364        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10365
10366        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
10367        let guard = result_arc.read().unwrap();
10368        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10369            panic!("expected Cpu storage");
10370        };
10371        assert_eq!(c.as_slice::<f32>().unwrap(), &[90.0]);
10372    }
10373
10374    /// E2E: Const + Flip + ReluElementwise — Flip is metadata-only,
10375    /// then a kernel that doesn't yet handle negative strides forces
10376    /// auto-Contiguize to materialize through StridedIndex (which
10377    /// handles signed strides natively). Verifies the post-flip
10378    /// data ordering ([4, 3, 2, 1]) is correctly seen by the kernel.
10379    #[test]
10380    fn pipelined_realize_flip_then_relu_materializes_in_reverse() {
10381        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
10382        let graph = Arc::new(RwLock::new(Graph::new()));
10383        let (in_id, _f_id, r_id) = {
10384            let mut g = graph.write().unwrap();
10385            let in_id = g.push(Node {
10386                op: Op::Const,
10387                inputs: vec![],
10388                shape: Shape::from_dims(&[4]),
10389                dtype: DType::F32,
10390            });
10391            let f_id = g.push(Node {
10392                op: Op::Flip { dim: 0 },
10393                inputs: vec![in_id],
10394                shape: Shape::from_dims(&[4]),
10395                dtype: DType::F32,
10396            });
10397            let r_id = g.push(Node {
10398                op: Op::Relu,
10399                inputs: vec![f_id],
10400                shape: Shape::from_dims(&[4]),
10401                dtype: DType::F32,
10402            });
10403            g.set_target_backend(r_id, BackendId::Cpu);
10404            (in_id, f_id, r_id)
10405        };
10406        let mut inputs = StorageCache::new();
10407        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10408
10409        let (result_arc, result_layout) =
10410            PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
10411        let guard = result_arc.read().unwrap();
10412        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10413            panic!("expected Cpu storage");
10414        };
10415        assert_eq!(c.as_slice::<f32>().unwrap(), &[4.0, 3.0, 2.0, 1.0]);
10416        assert_eq!(result_layout.shape().dims(), &[4]);
10417        assert!(result_layout.is_contiguous(), "relu output is contiguous");
10418    }
10419
10420    /// E2E: Const + BroadcastTo — verifies that broadcast layouts
10421    /// have stride 0 on the broadcast dim while sharing the input's
10422    /// bytes. Stage 3 of Layout-on-Node.
10423    #[test]
10424    fn pipelined_realize_broadcast_is_metadata_only() {
10425        // shape [3]; broadcast to [4, 3] — leading dim is 0-stride
10426        let storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
10427        let graph = Arc::new(RwLock::new(Graph::new()));
10428        let (in_id, b_id) = {
10429            let mut g = graph.write().unwrap();
10430            let in_id = g.push(Node {
10431                op: Op::Const,
10432                inputs: vec![],
10433                shape: Shape::from_dims(&[3]),
10434                dtype: DType::F32,
10435            });
10436            let b_id = g.push(Node {
10437                op: Op::BroadcastTo(Shape::from_dims(&[4, 3])),
10438                inputs: vec![in_id],
10439                shape: Shape::from_dims(&[4, 3]),
10440                dtype: DType::F32,
10441            });
10442            (in_id, b_id)
10443        };
10444        let mut inputs = StorageCache::new();
10445        let in_arc = Arc::new(RwLock::new(storage));
10446        inputs.insert(in_id, Arc::clone(&in_arc));
10447
10448        let (result_arc, result_layout) =
10449            PipelinedExecutor::realize(graph, b_id, inputs).expect("realize");
10450
10451        assert!(Arc::ptr_eq(&result_arc, &in_arc));
10452        assert_eq!(result_layout.shape().dims(), &[4, 3]);
10453        // Broadcasted leading dim has stride 0.
10454        assert_eq!(result_layout.stride(), &[0, 1]);
10455    }
10456
10457    /// E2E: Const + Const + MatMul — exercises rank-2 matmul
10458    /// through the pipelined executor. Inputs are contiguous (no
10459    /// auto-Contiguize needed); the kernel walks them via the
10460    /// (m, n, k) carried in OpParams::Matmul.
10461    #[test]
10462    fn pipelined_realize_matmul_2x3_times_3x2() {
10463        // [[1, 2, 3], [4, 5, 6]] @ [[7, 8], [9, 10], [11, 12]]
10464        //   = [[58, 64], [139, 154]]
10465        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
10466        let rhs_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0, 9.0, 10.0, 11.0, 12.0]);
10467
10468        let graph = Arc::new(RwLock::new(Graph::new()));
10469        let (lhs_id, rhs_id, mm_id) = {
10470            let mut g = graph.write().unwrap();
10471            let lhs = g.push(Node {
10472                op: Op::Const,
10473                inputs: vec![],
10474                shape: Shape::from_dims(&[2, 3]),
10475                dtype: DType::F32,
10476            });
10477            let rhs = g.push(Node {
10478                op: Op::Const,
10479                inputs: vec![],
10480                shape: Shape::from_dims(&[3, 2]),
10481                dtype: DType::F32,
10482            });
10483            let mm = g.push(Node {
10484                op: Op::MatMul,
10485                inputs: vec![lhs, rhs],
10486                shape: Shape::from_dims(&[2, 2]),
10487                dtype: DType::F32,
10488            });
10489            g.set_target_backend(mm, BackendId::Cpu);
10490            (lhs, rhs, mm)
10491        };
10492        let mut inputs = StorageCache::new();
10493        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
10494        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
10495
10496        let (result_arc, result_layout) =
10497            PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
10498        assert_eq!(result_layout.shape().dims(), &[2, 2]);
10499        assert!(result_layout.is_contiguous());
10500
10501        let guard = result_arc.read().unwrap();
10502        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10503            panic!("expected Cpu storage");
10504        };
10505        assert_eq!(c.as_slice::<f32>().unwrap(), &[58.0, 64.0, 139.0, 154.0]);
10506    }
10507
10508    /// E2E: batched matmul through the pipelined executor. Two
10509    /// batches of [2, 2] @ [2, 2]; the kernel iterates over
10510    /// `batch_count` and produces concatenated outputs.
10511    #[test]
10512    fn pipelined_realize_matmul_batched_2x_2x2_times_2x2() {
10513        let lhs_storage = fuel_memory::from_slice_cpu(&[
10514            1.0_f32, 2.0, 3.0, 4.0, // batch 0
10515            1.0, 0.0, 0.0, 1.0, // batch 1 (identity)
10516        ]);
10517        let rhs_storage = fuel_memory::from_slice_cpu(&[
10518            5.0_f32, 6.0, 7.0, 8.0, // batch 0
10519            10.0, 20.0, 30.0, 40.0, // batch 1
10520        ]);
10521
10522        let graph = Arc::new(RwLock::new(Graph::new()));
10523        let (lhs_id, rhs_id, mm_id) = {
10524            let mut g = graph.write().unwrap();
10525            let lhs = g.push(Node {
10526                op: Op::Const,
10527                inputs: vec![],
10528                shape: Shape::from_dims(&[2, 2, 2]),
10529                dtype: DType::F32,
10530            });
10531            let rhs = g.push(Node {
10532                op: Op::Const,
10533                inputs: vec![],
10534                shape: Shape::from_dims(&[2, 2, 2]),
10535                dtype: DType::F32,
10536            });
10537            let mm = g.push(Node {
10538                op: Op::MatMul,
10539                inputs: vec![lhs, rhs],
10540                shape: Shape::from_dims(&[2, 2, 2]),
10541                dtype: DType::F32,
10542            });
10543            g.set_target_backend(mm, BackendId::Cpu);
10544            (lhs, rhs, mm)
10545        };
10546        let mut inputs = StorageCache::new();
10547        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
10548        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
10549
10550        let (result_arc, result_layout) =
10551            PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
10552        assert_eq!(result_layout.shape().dims(), &[2, 2, 2]);
10553        assert!(result_layout.is_contiguous());
10554
10555        let guard = result_arc.read().unwrap();
10556        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10557            panic!("expected Cpu storage");
10558        };
10559        // batch 0: [[1,2],[3,4]] @ [[5,6],[7,8]] = [[19,22],[43,50]]
10560        // batch 1: identity @ [[10,20],[30,40]]   = [[10,20],[30,40]]
10561        assert_eq!(
10562            c.as_slice::<f32>().unwrap(),
10563            &[19.0, 22.0, 43.0, 50.0, 10.0, 20.0, 30.0, 40.0]
10564        );
10565    }
10566
10567    /// E2E: F64 elementwise add through the pipelined executor.
10568    /// Verifies that capability-driven dispatch correctly routes
10569    /// (AddElementwise, F64) to the f64 wrapper/kernel.
10570    #[test]
10571    fn pipelined_realize_add_f64() {
10572        let lhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0]);
10573        let rhs = fuel_memory::from_slice_cpu(&[10.0_f64, 20.0, 30.0]);
10574        let graph = Arc::new(RwLock::new(Graph::new()));
10575        let (l_id, r_id, op_id) = {
10576            let mut g = graph.write().unwrap();
10577            let l = g.push(Node {
10578                op: Op::Const,
10579                inputs: vec![],
10580                shape: Shape::from_dims(&[3]),
10581                dtype: DType::F64,
10582            });
10583            let r = g.push(Node {
10584                op: Op::Const,
10585                inputs: vec![],
10586                shape: Shape::from_dims(&[3]),
10587                dtype: DType::F64,
10588            });
10589            let op = g.push(Node {
10590                op: Op::Add,
10591                inputs: vec![l, r],
10592                shape: Shape::from_dims(&[3]),
10593                dtype: DType::F64,
10594            });
10595            g.set_target_backend(op, BackendId::Cpu);
10596            (l, r, op)
10597        };
10598        let mut inputs = StorageCache::new();
10599        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10600        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10601        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
10602        let guard = result_arc.read().unwrap();
10603        assert_eq!(guard.dtype, DType::F64);
10604        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10605            panic!("expected Cpu storage");
10606        };
10607        assert_eq!(c.as_slice::<f64>().unwrap(), &[11.0_f64, 22.0, 33.0]);
10608    }
10609
10610    /// E2E: Op::Equal F32 → Bool mask through the pipelined executor (GAP-168c).
10611    /// Verifies (a) the binding-table key `(EqualElementwise, [F32, F32, U8],
10612    /// Cpu)` resolves, (b) the executor allocates a U8-sized output
10613    /// buffer (1 byte per element, not 4), (c) the kernel writes the
10614    /// expected mask bits including IEEE-754 NaN handling
10615    /// (`NaN == NaN` is false).
10616    #[test]
10617    fn pipelined_realize_eq_f32_to_bool_mask() {
10618        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, f32::NAN, 0.0]);
10619        let rhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -0.0]);
10620        let graph = Arc::new(RwLock::new(Graph::new()));
10621        let (l_id, r_id, eq_id) = {
10622            let mut g = graph.write().unwrap();
10623            let l = g.push(Node {
10624                op: Op::Const,
10625                inputs: vec![],
10626                shape: Shape::from_dims(&[5]),
10627                dtype: DType::F32,
10628            });
10629            let r = g.push(Node {
10630                op: Op::Const,
10631                inputs: vec![],
10632                shape: Shape::from_dims(&[5]),
10633                dtype: DType::F32,
10634            });
10635            let eq = g.push(Node {
10636                op: Op::Equal,
10637                inputs: vec![l, r],
10638                shape: Shape::from_dims(&[5]),
10639                dtype: DType::Bool,
10640            });
10641            g.set_target_backend(eq, BackendId::Cpu);
10642            (l, r, eq)
10643        };
10644        let mut inputs = StorageCache::new();
10645        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10646        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10647        let (result_arc, _) = PipelinedExecutor::realize(graph, eq_id, inputs).expect("realize");
10648        let guard = result_arc.read().unwrap();
10649        assert_eq!(guard.dtype, DType::Bool);
10650        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10651            panic!("expected Cpu storage");
10652        };
10653        let mask: &[u8] = c.as_slice().expect("u8 view");
10654        // Index 0: 1.0 == 1.0 → 1.
10655        // Index 1: 2.0 != 5.0 → 0.
10656        // Index 2: 3.0 == 3.0 → 1.
10657        // Index 3: NaN == NaN → 0 (IEEE-754).
10658        // Index 4: 0.0 == -0.0 → 1 (IEEE-754 zero equality).
10659        assert_eq!(mask, &[1, 0, 1, 0, 1]);
10660    }
10661
10662    /// E2E: Op::Ne F32 → Bool mask. Mirrors the Eq F32 test with
10663    /// inverted predicate; NaN-vs-NaN slot now yields `1` (since
10664    /// `NaN != NaN` per IEEE-754).
10665    #[test]
10666    fn pipelined_realize_ne_f32_to_bool_mask() {
10667        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, f32::NAN, 0.0]);
10668        let rhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -0.0]);
10669        let graph = Arc::new(RwLock::new(Graph::new()));
10670        let (l_id, r_id, ne_id) = {
10671            let mut g = graph.write().unwrap();
10672            let l = g.push(Node {
10673                op: Op::Const,
10674                inputs: vec![],
10675                shape: Shape::from_dims(&[5]),
10676                dtype: DType::F32,
10677            });
10678            let r = g.push(Node {
10679                op: Op::Const,
10680                inputs: vec![],
10681                shape: Shape::from_dims(&[5]),
10682                dtype: DType::F32,
10683            });
10684            let ne = g.push(Node {
10685                op: Op::Ne,
10686                inputs: vec![l, r],
10687                shape: Shape::from_dims(&[5]),
10688                dtype: DType::Bool,
10689            });
10690            g.set_target_backend(ne, BackendId::Cpu);
10691            (l, r, ne)
10692        };
10693        let mut inputs = StorageCache::new();
10694        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10695        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10696        let (result_arc, _) = PipelinedExecutor::realize(graph, ne_id, inputs).expect("realize");
10697        let guard = result_arc.read().unwrap();
10698        assert_eq!(guard.dtype, DType::Bool);
10699        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10700            panic!("expected Cpu storage");
10701        };
10702        let mask: &[u8] = c.as_slice().expect("u8 view");
10703        // Inverse of the Eq test:
10704        // 1.0 != 1.0 → 0;  2.0 != 5.0 → 1;  3.0 != 3.0 → 0;
10705        // NaN != NaN → 1 (IEEE-754);  0.0 != -0.0 → 0 (IEEE-754).
10706        assert_eq!(mask, &[0, 1, 0, 1, 0]);
10707    }
10708
10709    /// E2E: Op::Lt F32 → Bool mask. Confirms strict-less-than semantics
10710    /// + IEEE-754 NaN handling (any comparison with NaN is unordered →
10711    ///
10712    /// `0`).
10713    #[test]
10714    fn pipelined_realize_lt_f32_to_bool_mask() {
10715        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -1.0]);
10716        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 3.0, 0.0, 0.0]);
10717        let graph = Arc::new(RwLock::new(Graph::new()));
10718        let (l_id, r_id, lt_id) = {
10719            let mut g = graph.write().unwrap();
10720            let l = g.push(Node {
10721                op: Op::Const,
10722                inputs: vec![],
10723                shape: Shape::from_dims(&[5]),
10724                dtype: DType::F32,
10725            });
10726            let r = g.push(Node {
10727                op: Op::Const,
10728                inputs: vec![],
10729                shape: Shape::from_dims(&[5]),
10730                dtype: DType::F32,
10731            });
10732            let lt = g.push(Node {
10733                op: Op::Lt,
10734                inputs: vec![l, r],
10735                shape: Shape::from_dims(&[5]),
10736                dtype: DType::Bool,
10737            });
10738            g.set_target_backend(lt, BackendId::Cpu);
10739            (l, r, lt)
10740        };
10741        let mut inputs = StorageCache::new();
10742        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10743        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10744        let (result_arc, _) = PipelinedExecutor::realize(graph, lt_id, inputs).expect("realize");
10745        let guard = result_arc.read().unwrap();
10746        assert_eq!(guard.dtype, DType::Bool);
10747        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10748            panic!("expected Cpu storage");
10749        };
10750        let mask: &[u8] = c.as_slice().expect("u8 view");
10751        // 1.0 < 2.0 → 1;  5.0 < 5.0 → 0 (strict);  3.0 < 3.0 → 0;
10752        // NaN < 0.0 → 0 (unordered);  -1.0 < 0.0 → 1.
10753        assert_eq!(mask, &[1, 0, 0, 0, 1]);
10754    }
10755
10756    /// E2E: Op::Le F32 → Bool mask. Distinct from Lt at the equal slot
10757    /// (`5.0 <= 5.0` = 1, vs Lt's `5.0 < 5.0` = 0). NaN unordered → 0.
10758    #[test]
10759    fn pipelined_realize_le_f32_to_bool_mask() {
10760        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -1.0]);
10761        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 2.0, 0.0, 0.0]);
10762        let graph = Arc::new(RwLock::new(Graph::new()));
10763        let (l_id, r_id, le_id) = {
10764            let mut g = graph.write().unwrap();
10765            let l = g.push(Node {
10766                op: Op::Const,
10767                inputs: vec![],
10768                shape: Shape::from_dims(&[5]),
10769                dtype: DType::F32,
10770            });
10771            let r = g.push(Node {
10772                op: Op::Const,
10773                inputs: vec![],
10774                shape: Shape::from_dims(&[5]),
10775                dtype: DType::F32,
10776            });
10777            let le = g.push(Node {
10778                op: Op::Le,
10779                inputs: vec![l, r],
10780                shape: Shape::from_dims(&[5]),
10781                dtype: DType::Bool,
10782            });
10783            g.set_target_backend(le, BackendId::Cpu);
10784            (l, r, le)
10785        };
10786        let mut inputs = StorageCache::new();
10787        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10788        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10789        let (result_arc, _) = PipelinedExecutor::realize(graph, le_id, inputs).expect("realize");
10790        let guard = result_arc.read().unwrap();
10791        assert_eq!(guard.dtype, DType::Bool);
10792        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10793            panic!("expected Cpu storage");
10794        };
10795        let mask: &[u8] = c.as_slice().expect("u8 view");
10796        // 1.0 <= 2.0 → 1;  5.0 <= 5.0 → 1 (key Lt difference);
10797        // 3.0 <= 2.0 → 0;  NaN <= 0.0 → 0 (unordered);  -1.0 <= 0.0 → 1.
10798        assert_eq!(mask, &[1, 1, 0, 0, 1]);
10799    }
10800
10801    /// E2E: Op::Gt F32 → Bool mask. Strict-greater: equality slot is
10802    /// `0`. NaN unordered → `0`.
10803    #[test]
10804    fn pipelined_realize_gt_f32_to_bool_mask() {
10805        let lhs = fuel_memory::from_slice_cpu(&[3.0_f32, 5.0, 2.0, f32::NAN, 1.0]);
10806        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 3.0, 0.0, 0.0]);
10807        let graph = Arc::new(RwLock::new(Graph::new()));
10808        let (l_id, r_id, gt_id) = {
10809            let mut g = graph.write().unwrap();
10810            let l = g.push(Node {
10811                op: Op::Const,
10812                inputs: vec![],
10813                shape: Shape::from_dims(&[5]),
10814                dtype: DType::F32,
10815            });
10816            let r = g.push(Node {
10817                op: Op::Const,
10818                inputs: vec![],
10819                shape: Shape::from_dims(&[5]),
10820                dtype: DType::F32,
10821            });
10822            let gt = g.push(Node {
10823                op: Op::Gt,
10824                inputs: vec![l, r],
10825                shape: Shape::from_dims(&[5]),
10826                dtype: DType::Bool,
10827            });
10828            g.set_target_backend(gt, BackendId::Cpu);
10829            (l, r, gt)
10830        };
10831        let mut inputs = StorageCache::new();
10832        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10833        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10834        let (result_arc, _) = PipelinedExecutor::realize(graph, gt_id, inputs).expect("realize");
10835        let guard = result_arc.read().unwrap();
10836        assert_eq!(guard.dtype, DType::Bool);
10837        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10838            panic!("expected Cpu storage");
10839        };
10840        let mask: &[u8] = c.as_slice().expect("u8 view");
10841        // 3.0 > 2.0 → 1;  5.0 > 5.0 → 0 (strict);  2.0 > 3.0 → 0;
10842        // NaN > 0.0 → 0 (unordered);  1.0 > 0.0 → 1.
10843        assert_eq!(mask, &[1, 0, 0, 0, 1]);
10844    }
10845
10846    /// E2E: Op::Ge F32 → Bool mask. Greater-or-equal: equality slot
10847    /// is `1` (distinguishes from Gt). NaN unordered → `0`. Closes
10848    /// the comparison family with full `[Eq, Ne, Lt, Le, Gt, Ge]`
10849    /// coverage.
10850    #[test]
10851    fn pipelined_realize_ge_f32_to_bool_mask() {
10852        let lhs = fuel_memory::from_slice_cpu(&[3.0_f32, 5.0, 2.0, f32::NAN, 0.0]);
10853        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 3.0, 0.0, 0.0]);
10854        let graph = Arc::new(RwLock::new(Graph::new()));
10855        let (l_id, r_id, ge_id) = {
10856            let mut g = graph.write().unwrap();
10857            let l = g.push(Node {
10858                op: Op::Const,
10859                inputs: vec![],
10860                shape: Shape::from_dims(&[5]),
10861                dtype: DType::F32,
10862            });
10863            let r = g.push(Node {
10864                op: Op::Const,
10865                inputs: vec![],
10866                shape: Shape::from_dims(&[5]),
10867                dtype: DType::F32,
10868            });
10869            let ge = g.push(Node {
10870                op: Op::Ge,
10871                inputs: vec![l, r],
10872                shape: Shape::from_dims(&[5]),
10873                dtype: DType::Bool,
10874            });
10875            g.set_target_backend(ge, BackendId::Cpu);
10876            (l, r, ge)
10877        };
10878        let mut inputs = StorageCache::new();
10879        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10880        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10881        let (result_arc, _) = PipelinedExecutor::realize(graph, ge_id, inputs).expect("realize");
10882        let guard = result_arc.read().unwrap();
10883        assert_eq!(guard.dtype, DType::Bool);
10884        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10885            panic!("expected Cpu storage");
10886        };
10887        let mask: &[u8] = c.as_slice().expect("u8 view");
10888        // 3.0 >= 2.0 → 1;  5.0 >= 5.0 → 1 (key Gt difference);
10889        // 2.0 >= 3.0 → 0;  NaN >= 0.0 → 0 (unordered);  0.0 >= 0.0 → 1.
10890        assert_eq!(mask, &[1, 1, 0, 0, 1]);
10891    }
10892
10893    /// E2E: Op::Equal F64 → Bool mask. Confirms the F64 wrapper is
10894    /// independently registered and routed (binding-table key
10895    /// `(EqualElementwise, [F64, F64, U8], Cpu)`).
10896    #[test]
10897    fn pipelined_realize_eq_f64_to_bool_mask() {
10898        let lhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0]);
10899        let rhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 4.0]);
10900        let graph = Arc::new(RwLock::new(Graph::new()));
10901        let (l_id, r_id, eq_id) = {
10902            let mut g = graph.write().unwrap();
10903            let l = g.push(Node {
10904                op: Op::Const,
10905                inputs: vec![],
10906                shape: Shape::from_dims(&[3]),
10907                dtype: DType::F64,
10908            });
10909            let r = g.push(Node {
10910                op: Op::Const,
10911                inputs: vec![],
10912                shape: Shape::from_dims(&[3]),
10913                dtype: DType::F64,
10914            });
10915            let eq = g.push(Node {
10916                op: Op::Equal,
10917                inputs: vec![l, r],
10918                shape: Shape::from_dims(&[3]),
10919                dtype: DType::Bool,
10920            });
10921            g.set_target_backend(eq, BackendId::Cpu);
10922            (l, r, eq)
10923        };
10924        let mut inputs = StorageCache::new();
10925        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10926        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10927        let (result_arc, _) = PipelinedExecutor::realize(graph, eq_id, inputs).expect("realize");
10928        let guard = result_arc.read().unwrap();
10929        assert_eq!(guard.dtype, DType::Bool);
10930        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10931            panic!("expected Cpu storage");
10932        };
10933        let mask: &[u8] = c.as_slice().expect("u8 view");
10934        assert_eq!(mask, &[1, 1, 0]);
10935    }
10936
10937    /// E2E: Op::Where ternary select — `out[i] = if cond[i] != 0 { a[i] } else { b[i] }`.
10938    /// Validates (a) the binding-table key `(Where, [Bool, F32, F32, F32], Cpu)`
10939    /// resolves to the where_f32 wrapper, (b) the Bool cond input drives
10940    /// the per-slot pick, (c) outputs preserve the input dtype.
10941    ///
10942    /// GAP-168(c): the cond STORAGE is tagged Bool, not merely the graph node.
10943    /// Bool and U8 are byte-identical, so leaving the storage U8 under a Bool
10944    /// node is exactly the mismatch this cut exists to make visible.
10945    #[test]
10946    fn pipelined_realize_where_f32_picks_per_slot_from_bool_mask() {
10947        // cond = [1, 0, 1, 0, 1]; a = [1, 2, 3, 4, 5]; b = [10, 20, 30, 40, 50]
10948        // expected = [1, 20, 3, 40, 5]
10949        let mut cond_storage = fuel_memory::from_slice_cpu(&[1u8, 0, 1, 0, 1]);
10950        cond_storage.dtype = DType::Bool; // GAP-168(c): a Bool mask, not U8 bytes
10951        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0]);
10952        let b_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0]);
10953        let graph = Arc::new(RwLock::new(Graph::new()));
10954        let (cond_id, a_id, b_id, where_id) = {
10955            let mut g = graph.write().unwrap();
10956            let cond = g.push(Node {
10957                op: Op::Const,
10958                inputs: vec![],
10959                shape: Shape::from_dims(&[5]),
10960                dtype: DType::Bool,
10961            });
10962            let a = g.push(Node {
10963                op: Op::Const,
10964                inputs: vec![],
10965                shape: Shape::from_dims(&[5]),
10966                dtype: DType::F32,
10967            });
10968            let b = g.push(Node {
10969                op: Op::Const,
10970                inputs: vec![],
10971                shape: Shape::from_dims(&[5]),
10972                dtype: DType::F32,
10973            });
10974            let w = g.push(Node {
10975                op: Op::Where,
10976                inputs: vec![cond, a, b],
10977                shape: Shape::from_dims(&[5]),
10978                dtype: DType::F32,
10979            });
10980            g.set_target_backend(w, BackendId::Cpu);
10981            (cond, a, b, w)
10982        };
10983        let mut inputs = StorageCache::new();
10984        inputs.insert(cond_id, Arc::new(RwLock::new(cond_storage)));
10985        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
10986        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
10987        let (result_arc, _) = PipelinedExecutor::realize(graph, where_id, inputs).expect("realize");
10988        let guard = result_arc.read().unwrap();
10989        assert_eq!(guard.dtype, DType::F32);
10990        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10991            panic!("expected Cpu storage");
10992        };
10993        let out: &[f32] = c.as_slice().expect("f32 view");
10994        assert_eq!(out, &[1.0, 20.0, 3.0, 40.0, 5.0]);
10995    }
10996
10997    /// E2E: full chain `eq → where`. Compares two f32 vectors, then
10998    /// uses the resulting Bool mask to pick from a third tensor (or a
10999    /// fallback). Validates the comparison-family + Where ops compose
11000    /// end-to-end.
11001    #[test]
11002    fn pipelined_realize_eq_then_where_full_chain() {
11003        // a = [1, 2, 3]; b = [1, 5, 3] → eq = [1, 0, 1]
11004        // pick = [10, 20, 30]; fallback = [99, 99, 99]
11005        // result = [10, 99, 30]
11006        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
11007        let b_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0]);
11008        let pick_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
11009        let fb_storage = fuel_memory::from_slice_cpu(&[99.0_f32, 99.0, 99.0]);
11010        let graph = Arc::new(RwLock::new(Graph::new()));
11011        let (a_id, b_id, pick_id, fb_id, where_id) = {
11012            let mut g = graph.write().unwrap();
11013            let a = g.push(Node {
11014                op: Op::Const,
11015                inputs: vec![],
11016                shape: Shape::from_dims(&[3]),
11017                dtype: DType::F32,
11018            });
11019            let b = g.push(Node {
11020                op: Op::Const,
11021                inputs: vec![],
11022                shape: Shape::from_dims(&[3]),
11023                dtype: DType::F32,
11024            });
11025            let pick = g.push(Node {
11026                op: Op::Const,
11027                inputs: vec![],
11028                shape: Shape::from_dims(&[3]),
11029                dtype: DType::F32,
11030            });
11031            let fb = g.push(Node {
11032                op: Op::Const,
11033                inputs: vec![],
11034                shape: Shape::from_dims(&[3]),
11035                dtype: DType::F32,
11036            });
11037            let eq = g.push(Node {
11038                op: Op::Equal,
11039                inputs: vec![a, b],
11040                shape: Shape::from_dims(&[3]),
11041                dtype: DType::Bool,
11042            });
11043            let w = g.push(Node {
11044                op: Op::Where,
11045                inputs: vec![eq, pick, fb],
11046                shape: Shape::from_dims(&[3]),
11047                dtype: DType::F32,
11048            });
11049            g.set_target_backend(eq, BackendId::Cpu);
11050            g.set_target_backend(w, BackendId::Cpu);
11051            (a, b, pick, fb, w)
11052        };
11053        let mut inputs = StorageCache::new();
11054        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
11055        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
11056        inputs.insert(pick_id, Arc::new(RwLock::new(pick_storage)));
11057        inputs.insert(fb_id, Arc::new(RwLock::new(fb_storage)));
11058        let (result_arc, _) = PipelinedExecutor::realize(graph, where_id, inputs).expect("realize");
11059        let guard = result_arc.read().unwrap();
11060        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11061            panic!("expected Cpu storage");
11062        };
11063        let out: &[f32] = c.as_slice().expect("f32 view");
11064        assert_eq!(out, &[10.0, 99.0, 30.0]);
11065    }
11066
11067    /// E2E: Q4_0 QMatMul through the pipelined executor — proves
11068    /// quantized weights can flow into the unified path. Activations
11069    /// are F32, weights are U32-typed (raw block bytes).
11070    /// Construct a Q4_0 weight tensor where every weight = 1.0
11071    /// (d=1.0, every nibble=9 → 1*(9-8)=1), so A @ W^T computes
11072    /// the per-row sum of activations.
11073    #[test]
11074    fn pipelined_realize_qmatmul_q4_0_unit_weight_sums_activations() {
11075        use fuel_graph::QuantType;
11076        use half::f16;
11077        let block_size = std::mem::size_of::<fuel_quantized::BlockQ4_0>();
11078        let mut w_bytes = vec![0u8; 2 * block_size];
11079        for block_idx in 0..2 {
11080            let off = block_idx * block_size;
11081            let d_bytes = f16::from_f32(1.0).to_le_bytes();
11082            w_bytes[off..off + 2].copy_from_slice(&d_bytes);
11083            for i in 0..16 {
11084                w_bytes[off + 2 + i] = 0x99;
11085            }
11086        }
11087        // Weight tensor is U32-typed (rank-1, length = bytes/4)
11088        let w_storage = fuel_memory::Storage::new(
11089            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
11090                &w_bytes,
11091            )),
11092            DType::U32,
11093        );
11094
11095        let act_vec: Vec<f32> = (1..=32).map(|x| x as f32).collect();
11096        let act_storage = fuel_memory::from_slice_cpu(&act_vec);
11097
11098        let graph = Arc::new(RwLock::new(Graph::new()));
11099        let (act_id, w_id, mm_id) = {
11100            let mut g = graph.write().unwrap();
11101            let act = g.push(Node {
11102                op: Op::Const,
11103                inputs: vec![],
11104                shape: Shape::from_dims(&[1, 32]),
11105                dtype: DType::F32,
11106            });
11107            let w = g.push(Node {
11108                op: Op::Const,
11109                inputs: vec![],
11110                shape: Shape::from_dims(&[w_bytes.len() / 4]),
11111                dtype: DType::U32,
11112            });
11113            let mm = g.push(Node {
11114                op: Op::Fused(
11115                    fuel_graph::registry::FusedOps::QMATMUL,
11116                    fuel_graph::registry::FusedOpParams::QMatMul {
11117                        quant_type: QuantType::Q4_0,
11118                        k: 32,
11119                        n: 2,
11120                    },
11121                ),
11122                inputs: vec![act, w],
11123                shape: Shape::from_dims(&[1, 2]),
11124                dtype: DType::F32,
11125            });
11126            g.set_target_backend(mm, BackendId::Cpu);
11127            (act, w, mm)
11128        };
11129        let mut inputs = StorageCache::new();
11130        inputs.insert(act_id, Arc::new(RwLock::new(act_storage)));
11131        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
11132        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11133        let guard = result_arc.read().unwrap();
11134        assert_eq!(guard.dtype, DType::F32);
11135        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11136            panic!("expected Cpu storage");
11137        };
11138        let r: &[f32] = c.as_slice().unwrap();
11139        // Both rows = sum(1..=32) = 528, within Q8_1 round-trip
11140        // tolerance.
11141        assert!((r[0] - 528.0).abs() < 0.5, "got {}, want 528", r[0]);
11142        assert!((r[1] - 528.0).abs() < 0.5, "got {}, want 528", r[1]);
11143    }
11144
11145    /// E2E: QMatMul with Q5_0 weights — verifies the new quant
11146    /// dispatch arm picks `qmatmul_q5_0_f32`. We build weights by
11147    /// quantizing all-ones via `BlockQ5_0::from_float`, then
11148    /// compare pipelined output against the direct fuel_quantized
11149    /// matmul on the same blocks.
11150    #[test]
11151    fn pipelined_realize_qmatmul_q5_0_against_reference() {
11152        use fuel_graph::QuantType;
11153        use fuel_quantized::{BlockQ5_0, GgmlType};
11154        let n = 2;
11155        let k = 64; // 2 blocks per row
11156        // Quantize an all-ones [n, k] weight matrix.
11157        let w_f32 = vec![1.0_f32; n * k];
11158        let blocks_per_row = k / BlockQ5_0::BLCK_SIZE;
11159        let mut w_blocks = vec![BlockQ5_0::zeros(); n * blocks_per_row];
11160        BlockQ5_0::from_float(&w_f32, &mut w_blocks);
11161        // Reinterpret block slice as bytes (BlockQ5_0 is #[repr(C)]).
11162        let bytes_per_block = std::mem::size_of::<BlockQ5_0>();
11163        let w_bytes: Vec<u8> = unsafe {
11164            std::slice::from_raw_parts(
11165                w_blocks.as_ptr() as *const u8,
11166                w_blocks.len() * bytes_per_block,
11167            )
11168        }
11169        .to_vec();
11170        let w_storage = fuel_memory::Storage::new(
11171            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
11172                &w_bytes,
11173            )),
11174            DType::U32,
11175        );
11176        let act_vec: Vec<f32> = (1..=k).map(|x| x as f32).collect();
11177        let act_storage = fuel_memory::from_slice_cpu(&act_vec);
11178        // Reference: direct matmul through fuel_quantized.
11179        let mut ref_out = vec![0.0_f32; n];
11180        fuel_quantized::matmul::<BlockQ5_0>((1, k, n), &act_vec, &w_blocks, &mut ref_out)
11181            .expect("ref matmul");
11182
11183        let graph = Arc::new(RwLock::new(Graph::new()));
11184        let (act_id, w_id, mm_id) = {
11185            let mut g = graph.write().unwrap();
11186            let act = g.push(Node {
11187                op: Op::Const,
11188                inputs: vec![],
11189                shape: Shape::from_dims(&[1, k]),
11190                dtype: DType::F32,
11191            });
11192            let w = g.push(Node {
11193                op: Op::Const,
11194                inputs: vec![],
11195                shape: Shape::from_dims(&[w_bytes.len() / 4]),
11196                dtype: DType::U32,
11197            });
11198            let mm = g.push(Node {
11199                op: Op::Fused(
11200                    fuel_graph::registry::FusedOps::QMATMUL,
11201                    fuel_graph::registry::FusedOpParams::QMatMul {
11202                        quant_type: QuantType::Q5_0,
11203                        k,
11204                        n,
11205                    },
11206                ),
11207                inputs: vec![act, w],
11208                shape: Shape::from_dims(&[1, n]),
11209                dtype: DType::F32,
11210            });
11211            g.set_target_backend(mm, BackendId::Cpu);
11212            (act, w, mm)
11213        };
11214        let mut inputs = StorageCache::new();
11215        inputs.insert(act_id, Arc::new(RwLock::new(act_storage)));
11216        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
11217        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11218        let guard = result_arc.read().unwrap();
11219        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11220            panic!("expected Cpu storage");
11221        };
11222        let r: &[f32] = c.as_slice().unwrap();
11223        // Bit-exact against same kernel via the trait, since both
11224        // paths run fuel_quantized::matmul<BlockQ5_0>.
11225        assert_eq!(
11226            r,
11227            ref_out.as_slice(),
11228            "pipelined Q5_0 differs from reference: got {r:?}, want {ref_out:?}"
11229        );
11230    }
11231
11232    /// E2E: QMatMul with Q6K (256-element super-block k-quant).
11233    /// Same idea as the Q5_0 test — bit-exact against the
11234    /// reference fuel_quantized::matmul<BlockQ6K>. Confirms the
11235    /// dispatch arm wires `qmatmul_q6k_f32` correctly.
11236    #[test]
11237    fn pipelined_realize_qmatmul_q6k_against_reference() {
11238        use fuel_graph::QuantType;
11239        use fuel_quantized::{BlockQ6K, GgmlType};
11240        let n = 2;
11241        let k = 256; // 1 super-block per row
11242        let w_f32 = vec![1.0_f32; n * k];
11243        let blocks_per_row = k / BlockQ6K::BLCK_SIZE;
11244        let mut w_blocks = vec![BlockQ6K::zeros(); n * blocks_per_row];
11245        BlockQ6K::from_float(&w_f32, &mut w_blocks);
11246        let bytes_per_block = std::mem::size_of::<BlockQ6K>();
11247        let w_bytes: Vec<u8> = unsafe {
11248            std::slice::from_raw_parts(
11249                w_blocks.as_ptr() as *const u8,
11250                w_blocks.len() * bytes_per_block,
11251            )
11252        }
11253        .to_vec();
11254        let w_storage = fuel_memory::Storage::new(
11255            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
11256                &w_bytes,
11257            )),
11258            DType::U32,
11259        );
11260        let act_vec: Vec<f32> = (1..=k).map(|x| x as f32 / 100.0).collect();
11261        let act_storage = fuel_memory::from_slice_cpu(&act_vec);
11262        let mut ref_out = vec![0.0_f32; n];
11263        fuel_quantized::matmul::<BlockQ6K>((1, k, n), &act_vec, &w_blocks, &mut ref_out)
11264            .expect("ref matmul");
11265
11266        let graph = Arc::new(RwLock::new(Graph::new()));
11267        let (act_id, w_id, mm_id) = {
11268            let mut g = graph.write().unwrap();
11269            let act = g.push(Node {
11270                op: Op::Const,
11271                inputs: vec![],
11272                shape: Shape::from_dims(&[1, k]),
11273                dtype: DType::F32,
11274            });
11275            let w = g.push(Node {
11276                op: Op::Const,
11277                inputs: vec![],
11278                shape: Shape::from_dims(&[w_bytes.len() / 4]),
11279                dtype: DType::U32,
11280            });
11281            let mm = g.push(Node {
11282                op: Op::Fused(
11283                    fuel_graph::registry::FusedOps::QMATMUL,
11284                    fuel_graph::registry::FusedOpParams::QMatMul {
11285                        quant_type: QuantType::Q6K,
11286                        k,
11287                        n,
11288                    },
11289                ),
11290                inputs: vec![act, w],
11291                shape: Shape::from_dims(&[1, n]),
11292                dtype: DType::F32,
11293            });
11294            g.set_target_backend(mm, BackendId::Cpu);
11295            (act, w, mm)
11296        };
11297        let mut inputs = StorageCache::new();
11298        inputs.insert(act_id, Arc::new(RwLock::new(act_storage)));
11299        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
11300        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11301        let guard = result_arc.read().unwrap();
11302        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11303            panic!("expected Cpu storage");
11304        };
11305        let r: &[f32] = c.as_slice().unwrap();
11306        assert_eq!(
11307            r,
11308            ref_out.as_slice(),
11309            "pipelined Q6K differs from reference: got {r:?}, want {ref_out:?}"
11310        );
11311    }
11312
11313    /// E2E: BF16 RmsNormLastDim through the pipelined executor.
11314    /// Verifies that capability-driven dispatch routes the
11315    /// half-float norm op to the bf16-specific kernel (which
11316    /// accumulates in f32 internally).
11317    #[test]
11318    fn pipelined_realize_rms_norm_bf16() {
11319        let v: Vec<half::bf16> = [3.0_f32, 4.0]
11320            .iter()
11321            .map(|&x| half::bf16::from_f32(x))
11322            .collect();
11323        let storage = fuel_memory::from_slice_cpu(&v);
11324        let graph = Arc::new(RwLock::new(Graph::new()));
11325        let (in_id, op_id) = {
11326            let mut g = graph.write().unwrap();
11327            let in_id = g.push(Node {
11328                op: Op::Const,
11329                inputs: vec![],
11330                shape: Shape::from_dims(&[1, 2]),
11331                dtype: DType::BF16,
11332            });
11333            let op_id = g.push(Node {
11334                op: Op::Fused(
11335                    fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM,
11336                    fuel_graph::registry::FusedOpParams::RmsNormLastDim { eps: 0.0 },
11337                ),
11338                inputs: vec![in_id],
11339                shape: Shape::from_dims(&[1, 2]),
11340                dtype: DType::BF16,
11341            });
11342            g.set_target_backend(op_id, BackendId::Cpu);
11343            (in_id, op_id)
11344        };
11345        let mut inputs = StorageCache::new();
11346        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11347        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
11348        let guard = result_arc.read().unwrap();
11349        assert_eq!(guard.dtype, DType::BF16);
11350        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11351            panic!("expected Cpu storage");
11352        };
11353        let r: &[half::bf16] = c.as_slice().unwrap();
11354        let rms = (12.5_f32).sqrt();
11355        // bf16's ~3-digit mantissa absorbs the divisor; allow ~5%.
11356        assert!((r[0].to_f32() - 3.0 / rms).abs() < 0.05);
11357        assert!((r[1].to_f32() - 4.0 / rms).abs() < 0.05);
11358    }
11359
11360    /// E2E: BF16 matmul through the pipelined executor — proves
11361    /// the LLM forward-pass blocker (every transformer layer
11362    /// is dominated by matmul). Identity matmul on bf16 round-
11363    /// trips small integers exactly.
11364    #[test]
11365    fn pipelined_realize_matmul_bf16_identity() {
11366        let lhs_v: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0]
11367            .iter()
11368            .map(|&x| half::bf16::from_f32(x))
11369            .collect();
11370        let rhs_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0]
11371            .iter()
11372            .map(|&x| half::bf16::from_f32(x))
11373            .collect();
11374        let lhs = fuel_memory::from_slice_cpu(&lhs_v);
11375        let rhs = fuel_memory::from_slice_cpu(&rhs_v);
11376        let graph = Arc::new(RwLock::new(Graph::new()));
11377        let (l_id, r_id, mm_id) = {
11378            let mut g = graph.write().unwrap();
11379            let l = g.push(Node {
11380                op: Op::Const,
11381                inputs: vec![],
11382                shape: Shape::from_dims(&[2, 2]),
11383                dtype: DType::BF16,
11384            });
11385            let r = g.push(Node {
11386                op: Op::Const,
11387                inputs: vec![],
11388                shape: Shape::from_dims(&[2, 2]),
11389                dtype: DType::BF16,
11390            });
11391            let mm = g.push(Node {
11392                op: Op::MatMul,
11393                inputs: vec![l, r],
11394                shape: Shape::from_dims(&[2, 2]),
11395                dtype: DType::BF16,
11396            });
11397            g.set_target_backend(mm, BackendId::Cpu);
11398            (l, r, mm)
11399        };
11400        let mut inputs = StorageCache::new();
11401        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11402        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11403        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11404        let guard = result_arc.read().unwrap();
11405        assert_eq!(guard.dtype, DType::BF16);
11406        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11407            panic!("expected Cpu storage");
11408        };
11409        let r: &[half::bf16] = c.as_slice().unwrap();
11410        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
11411        assert_eq!(result_f32, vec![1.0, 2.0, 3.0, 4.0]);
11412    }
11413
11414    /// E2E (ROADMAP row 34): a mixed `[F32, W, F32]` matmul (f32 activation, half weight) runs on
11415    /// the CPU through the NATIVE kernel, with the weight left half-width: the output is f32 and
11416    /// equals the f64 matmul over the widened weights to f32 accumulation error. The weight is
11417    /// rounded to its stored half type first.
11418    fn mixed_cpu_matmul_matches_f64(weight_dtype: DType) {
11419        let (m, n, k) = (3_usize, 5_usize, 7_usize);
11420        let a: Vec<f32> = (0..m * k)
11421            .map(|i| ((i * 37 % 19) as f32 - 9.0) / 8.0)
11422            .collect();
11423        let w_f32: Vec<f32> = (0..k * n)
11424            .map(|i| ((i * 53 % 23) as f32 - 11.0) / 10.0)
11425            .collect();
11426        let (w_storage, widened): (_, Vec<f32>) = if weight_dtype == DType::BF16 {
11427            let h: Vec<half::bf16> = w_f32.iter().map(|&x| half::bf16::from_f32(x)).collect();
11428            let wide = h.iter().map(|x| x.to_f32()).collect();
11429            (fuel_memory::from_slice_cpu(&h), wide)
11430        } else {
11431            let h: Vec<half::f16> = w_f32.iter().map(|&x| half::f16::from_f32(x)).collect();
11432            let wide = h.iter().map(|x| x.to_f32()).collect();
11433            (fuel_memory::from_slice_cpu(&h), wide)
11434        };
11435        let graph = Arc::new(RwLock::new(Graph::new()));
11436        let (l_id, r_id, mm_id) = {
11437            let mut g = graph.write().unwrap();
11438            let l = g.push(Node {
11439                op: Op::Const,
11440                inputs: vec![],
11441                shape: Shape::from_dims(&[m, k]),
11442                dtype: DType::F32,
11443            });
11444            let r = g.push(Node {
11445                op: Op::Const,
11446                inputs: vec![],
11447                shape: Shape::from_dims(&[k, n]),
11448                dtype: weight_dtype,
11449            });
11450            let mm = g.push(Node {
11451                op: Op::MatMul,
11452                inputs: vec![l, r],
11453                shape: Shape::from_dims(&[m, n]),
11454                dtype: DType::F32,
11455            });
11456            g.set_target_backend(mm, BackendId::Cpu);
11457            (l, r, mm)
11458        };
11459        let mut inputs = StorageCache::new();
11460        inputs.insert(l_id, Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&a))));
11461        inputs.insert(r_id, Arc::new(RwLock::new(w_storage)));
11462        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11463        let guard = result_arc.read().unwrap();
11464        assert_eq!(guard.dtype, DType::F32);
11465        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11466            panic!("expected Cpu storage");
11467        };
11468        let got: &[f32] = c.as_slice().unwrap();
11469        for i in 0..m {
11470            for j in 0..n {
11471                let want: f64 = (0..k)
11472                    .map(|kk| a[i * k + kk] as f64 * widened[kk * n + j] as f64)
11473                    .sum();
11474                let err = (got[i * n + j] as f64 - want).abs();
11475                assert!(
11476                    err < 1e-5,
11477                    "{weight_dtype:?} [{i},{j}]: got {}, want {want}",
11478                    got[i * n + j]
11479                );
11480            }
11481        }
11482    }
11483
11484    #[test]
11485    fn pipelined_realize_mixed_f32_bf16_matmul_is_native_on_cpu() {
11486        mixed_cpu_matmul_matches_f64(DType::BF16);
11487    }
11488
11489    #[test]
11490    fn pipelined_realize_mixed_f32_f16_matmul_is_native_on_cpu() {
11491        mixed_cpu_matmul_matches_f64(DType::F16);
11492    }
11493
11494    /// E2E: F16 sum-reduce — verifies bf16/f16 reduction dispatch
11495    /// works through the executor.
11496    #[test]
11497    fn pipelined_realize_sum_dim_f16() {
11498        let v: Vec<half::f16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]
11499            .iter()
11500            .map(|&x| half::f16::from_f32(x))
11501            .collect();
11502        let storage = fuel_memory::from_slice_cpu(&v);
11503        let graph = Arc::new(RwLock::new(Graph::new()));
11504        let (in_id, sum_id) = {
11505            let mut g = graph.write().unwrap();
11506            let in_id = g.push(Node {
11507                op: Op::Const,
11508                inputs: vec![],
11509                shape: Shape::from_dims(&[2, 3]),
11510                dtype: DType::F16,
11511            });
11512            let sum_id = g.push(Node {
11513                op: Op::SumDim(1),
11514                inputs: vec![in_id],
11515                shape: Shape::from_dims(&[2]),
11516                dtype: DType::F16,
11517            });
11518            g.set_target_backend(sum_id, BackendId::Cpu);
11519            (in_id, sum_id)
11520        };
11521        let mut inputs = StorageCache::new();
11522        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11523        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
11524        let guard = result_arc.read().unwrap();
11525        assert_eq!(guard.dtype, DType::F16);
11526        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11527            panic!("expected Cpu storage");
11528        };
11529        let r: &[half::f16] = c.as_slice().unwrap();
11530        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
11531        assert_eq!(result_f32, vec![6.0, 15.0]);
11532    }
11533
11534    /// E2E: BF16 elementwise add through the pipelined executor.
11535    #[test]
11536    fn pipelined_realize_add_bf16() {
11537        let lhs_vec: Vec<half::bf16> = [1.0_f32, 2.0, 3.0]
11538            .iter()
11539            .map(|&x| half::bf16::from_f32(x))
11540            .collect();
11541        let rhs_vec: Vec<half::bf16> = [10.0_f32, 20.0, 30.0]
11542            .iter()
11543            .map(|&x| half::bf16::from_f32(x))
11544            .collect();
11545        let lhs = fuel_memory::from_slice_cpu(&lhs_vec);
11546        let rhs = fuel_memory::from_slice_cpu(&rhs_vec);
11547        let graph = Arc::new(RwLock::new(Graph::new()));
11548        let (l_id, r_id, op_id) = {
11549            let mut g = graph.write().unwrap();
11550            let l = g.push(Node {
11551                op: Op::Const,
11552                inputs: vec![],
11553                shape: Shape::from_dims(&[3]),
11554                dtype: DType::BF16,
11555            });
11556            let r = g.push(Node {
11557                op: Op::Const,
11558                inputs: vec![],
11559                shape: Shape::from_dims(&[3]),
11560                dtype: DType::BF16,
11561            });
11562            let op = g.push(Node {
11563                op: Op::Add,
11564                inputs: vec![l, r],
11565                shape: Shape::from_dims(&[3]),
11566                dtype: DType::BF16,
11567            });
11568            g.set_target_backend(op, BackendId::Cpu);
11569            (l, r, op)
11570        };
11571        let mut inputs = StorageCache::new();
11572        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11573        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11574        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
11575        let guard = result_arc.read().unwrap();
11576        assert_eq!(guard.dtype, DType::BF16);
11577        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11578            panic!("expected Cpu storage");
11579        };
11580        let r: &[half::bf16] = c.as_slice().unwrap();
11581        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
11582        assert_eq!(result_f32, vec![11.0, 22.0, 33.0]);
11583    }
11584
11585    /// E2E: F16 unary chain — Const + Sqr + Sqrt — verifies F16
11586    /// dispatch works and the via-f32 round-trip kernels behave
11587    /// correctly through the executor.
11588    #[test]
11589    fn pipelined_realize_sqr_then_sqrt_f16() {
11590        let v: Vec<half::f16> = [1.0_f32, 4.0, 9.0]
11591            .iter()
11592            .map(|&x| half::f16::from_f32(x))
11593            .collect();
11594        let storage = fuel_memory::from_slice_cpu(&v);
11595        let graph = Arc::new(RwLock::new(Graph::new()));
11596        let (in_id, sqrt_id) = {
11597            let mut g = graph.write().unwrap();
11598            let in_id = g.push(Node {
11599                op: Op::Const,
11600                inputs: vec![],
11601                shape: Shape::from_dims(&[3]),
11602                dtype: DType::F16,
11603            });
11604            let sqr_id = g.push(Node {
11605                op: Op::Sqr,
11606                inputs: vec![in_id],
11607                shape: Shape::from_dims(&[3]),
11608                dtype: DType::F16,
11609            });
11610            let sqrt_id = g.push(Node {
11611                op: Op::Sqrt,
11612                inputs: vec![sqr_id],
11613                shape: Shape::from_dims(&[3]),
11614                dtype: DType::F16,
11615            });
11616            g.set_target_backend(sqr_id, BackendId::Cpu);
11617            g.set_target_backend(sqrt_id, BackendId::Cpu);
11618            (in_id, sqrt_id)
11619        };
11620        let mut inputs = StorageCache::new();
11621        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11622        let (result_arc, _) = PipelinedExecutor::realize(graph, sqrt_id, inputs).expect("realize");
11623        let guard = result_arc.read().unwrap();
11624        assert_eq!(guard.dtype, DType::F16);
11625        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11626            panic!("expected Cpu storage");
11627        };
11628        let r: &[half::f16] = c.as_slice().unwrap();
11629        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
11630        // f16 has ~3 decimal digits; sqrt(sqr(x)) = |x| within rounding.
11631        for (got, want) in result_f32.iter().zip(&[1.0_f32, 4.0, 9.0]) {
11632            assert!((got - want).abs() < 0.05, "got {got}, want {want}");
11633        }
11634    }
11635
11636    /// E2E: F64 sum-reduce along one dim through the pipelined
11637    /// executor.
11638    #[test]
11639    fn pipelined_realize_sum_dim_f64() {
11640        let storage = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
11641        let graph = Arc::new(RwLock::new(Graph::new()));
11642        let (in_id, sum_id) = {
11643            let mut g = graph.write().unwrap();
11644            let in_id = g.push(Node {
11645                op: Op::Const,
11646                inputs: vec![],
11647                shape: Shape::from_dims(&[2, 3]),
11648                dtype: DType::F64,
11649            });
11650            let sum_id = g.push(Node {
11651                op: Op::SumDim(1),
11652                inputs: vec![in_id],
11653                shape: Shape::from_dims(&[2]),
11654                dtype: DType::F64,
11655            });
11656            g.set_target_backend(sum_id, BackendId::Cpu);
11657            (in_id, sum_id)
11658        };
11659        let mut inputs = StorageCache::new();
11660        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11661        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
11662        let guard = result_arc.read().unwrap();
11663        assert_eq!(guard.dtype, DType::F64);
11664        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11665            panic!("expected Cpu storage");
11666        };
11667        assert_eq!(c.as_slice::<f64>().unwrap(), &[6.0_f64, 15.0]);
11668    }
11669
11670    /// E2E: F64 matmul through the pipelined executor.
11671    #[test]
11672    fn pipelined_realize_matmul_2x3_times_3x2_f64() {
11673        let lhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
11674        let rhs = fuel_memory::from_slice_cpu(&[7.0_f64, 8.0, 9.0, 10.0, 11.0, 12.0]);
11675        let graph = Arc::new(RwLock::new(Graph::new()));
11676        let (l_id, r_id, mm_id) = {
11677            let mut g = graph.write().unwrap();
11678            let l = g.push(Node {
11679                op: Op::Const,
11680                inputs: vec![],
11681                shape: Shape::from_dims(&[2, 3]),
11682                dtype: DType::F64,
11683            });
11684            let r = g.push(Node {
11685                op: Op::Const,
11686                inputs: vec![],
11687                shape: Shape::from_dims(&[3, 2]),
11688                dtype: DType::F64,
11689            });
11690            let mm = g.push(Node {
11691                op: Op::MatMul,
11692                inputs: vec![l, r],
11693                shape: Shape::from_dims(&[2, 2]),
11694                dtype: DType::F64,
11695            });
11696            g.set_target_backend(mm, BackendId::Cpu);
11697            (l, r, mm)
11698        };
11699        let mut inputs = StorageCache::new();
11700        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11701        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11702        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11703        let guard = result_arc.read().unwrap();
11704        assert_eq!(guard.dtype, DType::F64);
11705        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11706            panic!("expected Cpu storage");
11707        };
11708        assert_eq!(
11709            c.as_slice::<f64>().unwrap(),
11710            &[58.0_f64, 64.0, 139.0, 154.0]
11711        );
11712    }
11713
11714    /// E2E: F64 unary chain — Const + Sqr + Sqrt — verifies that
11715    /// the kernel-binding lookup picks the f64 entries when the
11716    /// graph nodes carry DType::F64.
11717    #[test]
11718    fn pipelined_realize_sqr_then_sqrt_f64() {
11719        let storage = fuel_memory::from_slice_cpu(&[1.0_f64, 4.0, 9.0]);
11720        let graph = Arc::new(RwLock::new(Graph::new()));
11721        let (in_id, sqrt_id) = {
11722            let mut g = graph.write().unwrap();
11723            let in_id = g.push(Node {
11724                op: Op::Const,
11725                inputs: vec![],
11726                shape: Shape::from_dims(&[3]),
11727                dtype: DType::F64,
11728            });
11729            let sqr_id = g.push(Node {
11730                op: Op::Sqr,
11731                inputs: vec![in_id],
11732                shape: Shape::from_dims(&[3]),
11733                dtype: DType::F64,
11734            });
11735            let sqrt_id = g.push(Node {
11736                op: Op::Sqrt,
11737                inputs: vec![sqr_id],
11738                shape: Shape::from_dims(&[3]),
11739                dtype: DType::F64,
11740            });
11741            g.set_target_backend(sqr_id, BackendId::Cpu);
11742            g.set_target_backend(sqrt_id, BackendId::Cpu);
11743            (in_id, sqrt_id)
11744        };
11745        let mut inputs = StorageCache::new();
11746        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11747        let (result_arc, _) = PipelinedExecutor::realize(graph, sqrt_id, inputs).expect("realize");
11748        let guard = result_arc.read().unwrap();
11749        assert_eq!(guard.dtype, DType::F64);
11750        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11751            panic!("expected Cpu storage");
11752        };
11753        assert_eq!(c.as_slice::<f64>().unwrap(), &[1.0_f64, 4.0, 9.0]);
11754    }
11755
11756    /// E2E: ArgMaxDim — produces U32 output indices.
11757    #[test]
11758    fn pipelined_realize_argmax_dim() {
11759        // input [2, 3] = [[1, 5, 2], [9, 0, 4]]
11760        // argmax dim=1 → [1, 0]
11761        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 2.0, 9.0, 0.0, 4.0]);
11762        let graph = Arc::new(RwLock::new(Graph::new()));
11763        let (in_id, op_id) = {
11764            let mut g = graph.write().unwrap();
11765            let in_id = g.push(Node {
11766                op: Op::Const,
11767                inputs: vec![],
11768                shape: Shape::from_dims(&[2, 3]),
11769                dtype: DType::F32,
11770            });
11771            let op_id = g.push(Node {
11772                op: Op::ArgMaxDim(1),
11773                inputs: vec![in_id],
11774                shape: Shape::from_dims(&[2]),
11775                dtype: DType::U32,
11776            });
11777            g.set_target_backend(op_id, BackendId::Cpu);
11778            (in_id, op_id)
11779        };
11780        let mut inputs = StorageCache::new();
11781        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11782        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
11783        let guard = result_arc.read().unwrap();
11784        assert_eq!(guard.dtype, DType::U32);
11785        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11786            panic!("expected Cpu storage");
11787        };
11788        assert_eq!(c.as_slice::<u32>().unwrap(), &[1u32, 0]);
11789    }
11790
11791    /// E2E: IndexAdd along outer dim — accumulate updates into a
11792    /// rank-1 base tensor at indexed positions.
11793    #[test]
11794    fn pipelined_realize_index_add_simple() {
11795        let base = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
11796        let indices = fuel_memory::from_slice_cpu(&[0u32, 0]);
11797        let src = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
11798        let graph = Arc::new(RwLock::new(Graph::new()));
11799        let (b_id, i_id, s_id, op_id) = {
11800            let mut g = graph.write().unwrap();
11801            let b = g.push(Node {
11802                op: Op::Const,
11803                inputs: vec![],
11804                shape: Shape::from_dims(&[3]),
11805                dtype: DType::F32,
11806            });
11807            let i = g.push(Node {
11808                op: Op::Const,
11809                inputs: vec![],
11810                shape: Shape::from_dims(&[2]),
11811                dtype: DType::U32,
11812            });
11813            let s = g.push(Node {
11814                op: Op::Const,
11815                inputs: vec![],
11816                shape: Shape::from_dims(&[2]),
11817                dtype: DType::F32,
11818            });
11819            let op = g.push(Node {
11820                op: Op::IndexAdd { dim: 0 },
11821                inputs: vec![b, i, s],
11822                shape: Shape::from_dims(&[3]),
11823                dtype: DType::F32,
11824            });
11825            g.set_target_backend(op, BackendId::Cpu);
11826            (b, i, s, op)
11827        };
11828        let mut inputs = StorageCache::new();
11829        inputs.insert(b_id, Arc::new(RwLock::new(base)));
11830        inputs.insert(i_id, Arc::new(RwLock::new(indices)));
11831        inputs.insert(s_id, Arc::new(RwLock::new(src)));
11832        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
11833        let guard = result_arc.read().unwrap();
11834        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11835            panic!("expected Cpu storage");
11836        };
11837        // 10 + 1 + 2 = 13; 20 untouched; 30 untouched.
11838        assert_eq!(c.as_slice::<f32>().unwrap(), &[13.0, 20.0, 30.0]);
11839    }
11840
11841    /// E2E: ScatterAdd along outer dim — same-rank indices, base
11842    /// starts as zeros, src adds values at scatter positions.
11843    #[test]
11844    fn pipelined_realize_scatter_add_outer_dim() {
11845        // base [3, 2] = zeros; indices [2, 2] = [[0, 1], [2, 0]];
11846        // src [2, 2] = [[1, 2], [3, 4]]; dim=0
11847        // → out = [[1, 4], [0, 2], [3, 0]]
11848        let base = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
11849        let indices = fuel_memory::from_slice_cpu(&[0u32, 1, 2, 0]);
11850        let src = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
11851        let graph = Arc::new(RwLock::new(Graph::new()));
11852        let (b_id, i_id, s_id, op_id) = {
11853            let mut g = graph.write().unwrap();
11854            let b = g.push(Node {
11855                op: Op::Const,
11856                inputs: vec![],
11857                shape: Shape::from_dims(&[3, 2]),
11858                dtype: DType::F32,
11859            });
11860            let i = g.push(Node {
11861                op: Op::Const,
11862                inputs: vec![],
11863                shape: Shape::from_dims(&[2, 2]),
11864                dtype: DType::U32,
11865            });
11866            let s = g.push(Node {
11867                op: Op::Const,
11868                inputs: vec![],
11869                shape: Shape::from_dims(&[2, 2]),
11870                dtype: DType::F32,
11871            });
11872            let op = g.push(Node {
11873                op: Op::ScatterAdd { dim: 0 },
11874                inputs: vec![b, i, s],
11875                shape: Shape::from_dims(&[3, 2]),
11876                dtype: DType::F32,
11877            });
11878            g.set_target_backend(op, BackendId::Cpu);
11879            (b, i, s, op)
11880        };
11881        let mut inputs = StorageCache::new();
11882        inputs.insert(b_id, Arc::new(RwLock::new(base)));
11883        inputs.insert(i_id, Arc::new(RwLock::new(indices)));
11884        inputs.insert(s_id, Arc::new(RwLock::new(src)));
11885        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
11886        let guard = result_arc.read().unwrap();
11887        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11888            panic!("expected Cpu storage");
11889        };
11890        assert_eq!(
11891            c.as_slice::<f32>().unwrap(),
11892            &[1.0, 4.0, 0.0, 2.0, 3.0, 0.0]
11893        );
11894    }
11895
11896    /// E2E: Rope through the pipelined executor. cos=0, sin=1
11897    /// rotates the head_dim halves with sign per the rotate_half
11898    /// convention.
11899    #[test]
11900    fn pipelined_realize_rope_pi_over_two() {
11901        // x [1, 1, 4] = [1, 2, 3, 4]. cos=[0,0,0,0], sin=[1,1,1,1].
11902        // Expected: [-3, -4, 1, 2].
11903        let x = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
11904        let cos = fuel_memory::from_slice_cpu(&[0.0_f32, 0.0, 0.0, 0.0]);
11905        let sin = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
11906        let graph = Arc::new(RwLock::new(Graph::new()));
11907        let (x_id, cos_id, sin_id, r_id) = {
11908            let mut g = graph.write().unwrap();
11909            let x = g.push(Node {
11910                op: Op::Const,
11911                inputs: vec![],
11912                shape: Shape::from_dims(&[1, 1, 4]),
11913                dtype: DType::F32,
11914            });
11915            let c = g.push(Node {
11916                op: Op::Const,
11917                inputs: vec![],
11918                shape: Shape::from_dims(&[1, 4]),
11919                dtype: DType::F32,
11920            });
11921            let s = g.push(Node {
11922                op: Op::Const,
11923                inputs: vec![],
11924                shape: Shape::from_dims(&[1, 4]),
11925                dtype: DType::F32,
11926            });
11927            let r = g.push(Node {
11928                op: Op::Fused(
11929                    fuel_graph::registry::FusedOps::ROPE,
11930                    fuel_graph::registry::FusedOpParams::Rope,
11931                ),
11932                inputs: vec![x, c, s],
11933                shape: Shape::from_dims(&[1, 1, 4]),
11934                dtype: DType::F32,
11935            });
11936            g.set_target_backend(r, BackendId::Cpu);
11937            (x, c, s, r)
11938        };
11939        let mut inputs = StorageCache::new();
11940        inputs.insert(x_id, Arc::new(RwLock::new(x)));
11941        inputs.insert(cos_id, Arc::new(RwLock::new(cos)));
11942        inputs.insert(sin_id, Arc::new(RwLock::new(sin)));
11943        let (result_arc, _) = PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
11944        let guard = result_arc.read().unwrap();
11945        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11946            panic!("expected Cpu storage");
11947        };
11948        assert_eq!(c.as_slice::<f32>().unwrap(), &[-3.0, -4.0, 1.0, 2.0]);
11949    }
11950
11951    /// E2E: Gather along inner dim. Source [2, 4]; indices [2, 3];
11952    /// output [2, 3] = picks from each row by per-row indices.
11953    #[test]
11954    fn pipelined_realize_gather_inner_dim() {
11955        let source =
11956            fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0]);
11957        let indices = fuel_memory::from_slice_cpu(&[0u32, 2, 1, 3, 0, 0]);
11958        let graph = Arc::new(RwLock::new(Graph::new()));
11959        let (src_id, idx_id, g_id) = {
11960            let mut g = graph.write().unwrap();
11961            let s = g.push(Node {
11962                op: Op::Const,
11963                inputs: vec![],
11964                shape: Shape::from_dims(&[2, 4]),
11965                dtype: DType::F32,
11966            });
11967            let i = g.push(Node {
11968                op: Op::Const,
11969                inputs: vec![],
11970                shape: Shape::from_dims(&[2, 3]),
11971                dtype: DType::U32,
11972            });
11973            let g_id = g.push(Node {
11974                op: Op::Gather { dim: 1 },
11975                inputs: vec![s, i],
11976                shape: Shape::from_dims(&[2, 3]),
11977                dtype: DType::F32,
11978            });
11979            g.set_target_backend(g_id, BackendId::Cpu);
11980            (s, i, g_id)
11981        };
11982        let mut inputs = StorageCache::new();
11983        inputs.insert(src_id, Arc::new(RwLock::new(source)));
11984        inputs.insert(idx_id, Arc::new(RwLock::new(indices)));
11985        let (result_arc, _) = PipelinedExecutor::realize(graph, g_id, inputs).expect("realize");
11986        let guard = result_arc.read().unwrap();
11987        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11988            panic!("expected Cpu storage");
11989        };
11990        assert_eq!(
11991            c.as_slice::<f32>().unwrap(),
11992            &[10.0, 30.0, 20.0, 80.0, 50.0, 50.0]
11993        );
11994    }
11995
11996    /// E2E: IndexSelect — embedding-table lookup. Source is a
11997    /// `[vocab=4, d_model=3]` table; indices are token IDs;
11998    /// output is `[seq=3, d_model=3]` with the picked rows.
11999    #[test]
12000    fn pipelined_realize_index_select_embedding_lookup() {
12001        let table = fuel_memory::from_slice_cpu(&[
12002            10.0_f32, 11.0, 12.0, // row 0
12003            20.0, 21.0, 22.0, // row 1
12004            30.0, 31.0, 32.0, // row 2
12005            40.0, 41.0, 42.0, // row 3
12006        ]);
12007        let indices = fuel_memory::from_slice_cpu(&[2u32, 0, 2]);
12008        let graph = Arc::new(RwLock::new(Graph::new()));
12009        let (table_id, idx_id, sel_id) = {
12010            let mut g = graph.write().unwrap();
12011            let t = g.push(Node {
12012                op: Op::Const,
12013                inputs: vec![],
12014                shape: Shape::from_dims(&[4, 3]),
12015                dtype: DType::F32,
12016            });
12017            let i = g.push(Node {
12018                op: Op::Const,
12019                inputs: vec![],
12020                shape: Shape::from_dims(&[3]),
12021                dtype: DType::U32,
12022            });
12023            let s = g.push(Node {
12024                op: Op::IndexSelect { dim: 0 },
12025                inputs: vec![t, i],
12026                shape: Shape::from_dims(&[3, 3]),
12027                dtype: DType::F32,
12028            });
12029            g.set_target_backend(s, BackendId::Cpu);
12030            (t, i, s)
12031        };
12032        let mut inputs = StorageCache::new();
12033        inputs.insert(table_id, Arc::new(RwLock::new(table)));
12034        inputs.insert(idx_id, Arc::new(RwLock::new(indices)));
12035        let (result_arc, result_layout) =
12036            PipelinedExecutor::realize(graph, sel_id, inputs).expect("realize");
12037        assert_eq!(result_layout.shape().dims(), &[3, 3]);
12038        let guard = result_arc.read().unwrap();
12039        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12040            panic!("expected Cpu storage");
12041        };
12042        assert_eq!(
12043            c.as_slice::<f32>().unwrap(),
12044            &[30.0, 31.0, 32.0, 10.0, 11.0, 12.0, 30.0, 31.0, 32.0]
12045        );
12046    }
12047
12048    /// E2E: RmsNormLastDim on a 2-row input. Each row's output
12049    /// has unit RMS up to the eps-induced bias.
12050    #[test]
12051    fn pipelined_realize_rms_norm_last_dim() {
12052        let storage = fuel_memory::from_slice_cpu(&[
12053            3.0_f32, 4.0, // row 0: rms = sqrt(12.5)
12054            6.0, 8.0, // row 1: rms = sqrt(50.0) = 5*sqrt(2)
12055        ]);
12056        let graph = Arc::new(RwLock::new(Graph::new()));
12057        let (in_id, op_id) = {
12058            let mut g = graph.write().unwrap();
12059            let in_id = g.push(Node {
12060                op: Op::Const,
12061                inputs: vec![],
12062                shape: Shape::from_dims(&[2, 2]),
12063                dtype: DType::F32,
12064            });
12065            let op_id = g.push(Node {
12066                op: Op::Fused(
12067                    fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM,
12068                    fuel_graph::registry::FusedOpParams::RmsNormLastDim { eps: 0.0 },
12069                ),
12070                inputs: vec![in_id],
12071                shape: Shape::from_dims(&[2, 2]),
12072                dtype: DType::F32,
12073            });
12074            g.set_target_backend(op_id, BackendId::Cpu);
12075            (in_id, op_id)
12076        };
12077        let mut inputs = StorageCache::new();
12078        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12079        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12080        let guard = result_arc.read().unwrap();
12081        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12082            panic!("expected Cpu storage");
12083        };
12084        let result: &[f32] = c.as_slice().unwrap();
12085        // Row 0: rms = sqrt(12.5). Output = [3, 4] / sqrt(12.5).
12086        let rms0 = (12.5_f32).sqrt();
12087        assert!((result[0] - 3.0 / rms0).abs() < 1e-6);
12088        assert!((result[1] - 4.0 / rms0).abs() < 1e-6);
12089        // Row 1: rms = sqrt(50). Output = [6, 8] / sqrt(50).
12090        let rms1 = (50.0_f32).sqrt();
12091        assert!((result[2] - 6.0 / rms1).abs() < 1e-6);
12092        assert!((result[3] - 8.0 / rms1).abs() < 1e-6);
12093    }
12094
12095    /// E2E: LayerNormLastDim — each row's output has zero mean and
12096    /// unit variance.
12097    #[test]
12098    fn pipelined_realize_layer_norm_last_dim() {
12099        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 10.0, 20.0, 30.0]);
12100        let graph = Arc::new(RwLock::new(Graph::new()));
12101        let (in_id, op_id) = {
12102            let mut g = graph.write().unwrap();
12103            let in_id = g.push(Node {
12104                op: Op::Const,
12105                inputs: vec![],
12106                shape: Shape::from_dims(&[2, 3]),
12107                dtype: DType::F32,
12108            });
12109            let op_id = g.push(Node {
12110                op: Op::Fused(
12111                    fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM,
12112                    fuel_graph::registry::FusedOpParams::LayerNormLastDim { eps: 0.0 },
12113                ),
12114                inputs: vec![in_id],
12115                shape: Shape::from_dims(&[2, 3]),
12116                dtype: DType::F32,
12117            });
12118            g.set_target_backend(op_id, BackendId::Cpu);
12119            (in_id, op_id)
12120        };
12121        let mut inputs = StorageCache::new();
12122        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12123        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12124        let guard = result_arc.read().unwrap();
12125        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12126            panic!("expected Cpu storage");
12127        };
12128        let result: &[f32] = c.as_slice().unwrap();
12129        // Each row should have mean ~0 and var ~1.
12130        for row in 0..2 {
12131            let off = row * 3;
12132            let sum: f32 = result[off..off + 3].iter().sum();
12133            let mean = sum / 3.0;
12134            assert!(mean.abs() < 1e-6, "row {row} mean should be 0, got {mean}");
12135            let var: f32 = result[off..off + 3]
12136                .iter()
12137                .map(|v| (v - mean).powi(2))
12138                .sum::<f32>()
12139                / 3.0;
12140            assert!(
12141                (var - 1.0).abs() < 1e-6,
12142                "row {row} var should be 1, got {var}"
12143            );
12144        }
12145    }
12146
12147    /// E2E: SoftmaxLastDim on a 2-row input. Each row should sum
12148    /// to 1; uniform row gives uniform output.
12149    #[test]
12150    fn pipelined_realize_softmax_last_dim() {
12151        // Row 0: [1, 1, 1, 1] → uniform 0.25 each
12152        // Row 1: [0, 0, 0, 100] → effectively a one-hot at position 3
12153        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 100.0]);
12154        let graph = Arc::new(RwLock::new(Graph::new()));
12155        let (in_id, op_id) = {
12156            let mut g = graph.write().unwrap();
12157            let in_id = g.push(Node {
12158                op: Op::Const,
12159                inputs: vec![],
12160                shape: Shape::from_dims(&[2, 4]),
12161                dtype: DType::F32,
12162            });
12163            let op_id = g.push(Node {
12164                op: Op::Fused(
12165                    fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM,
12166                    fuel_graph::registry::FusedOpParams::SoftmaxLastDim,
12167                ),
12168                inputs: vec![in_id],
12169                shape: Shape::from_dims(&[2, 4]),
12170                dtype: DType::F32,
12171            });
12172            g.set_target_backend(op_id, BackendId::Cpu);
12173            (in_id, op_id)
12174        };
12175        let mut inputs = StorageCache::new();
12176        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12177        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12178        let guard = result_arc.read().unwrap();
12179        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12180            panic!("expected Cpu storage");
12181        };
12182        let result: &[f32] = c.as_slice().unwrap();
12183
12184        // Row 0: uniform 0.25
12185        for v in &result[..4] {
12186            assert!((v - 0.25).abs() < 1e-7);
12187        }
12188        // Row 1: positions 0..3 ≈ 0, position 4 (= last column) ≈ 1
12189        // (e^100 dominates).
12190        for v in &result[4..7] {
12191            assert!(
12192                *v < 1e-30,
12193                "row-1 leading positions should be near 0, got {v}"
12194            );
12195        }
12196        assert!(
12197            result[7] > 0.999,
12198            "row-1 last position should dominate, got {}",
12199            result[7]
12200        );
12201        // Each row sums to 1.
12202        let row0_sum: f32 = result[..4].iter().sum();
12203        let row1_sum: f32 = result[4..].iter().sum();
12204        assert!((row0_sum - 1.0).abs() < 1e-6);
12205        assert!((row1_sum - 1.0).abs() < 1e-6);
12206    }
12207
12208    /// E2E: Concat along inner dim — two [2, 3] tensors → [2, 6].
12209    #[test]
12210    fn pipelined_realize_concat_inner_dim() {
12211        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
12212        let b = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0, 9.0, 10.0, 11.0, 12.0]);
12213        let graph = Arc::new(RwLock::new(Graph::new()));
12214        let (a_id, b_id, c_id) = {
12215            let mut g = graph.write().unwrap();
12216            let a = g.push(Node {
12217                op: Op::Const,
12218                inputs: vec![],
12219                shape: Shape::from_dims(&[2, 3]),
12220                dtype: DType::F32,
12221            });
12222            let b = g.push(Node {
12223                op: Op::Const,
12224                inputs: vec![],
12225                shape: Shape::from_dims(&[2, 3]),
12226                dtype: DType::F32,
12227            });
12228            let c = g.push(Node {
12229                op: Op::Concat { dim: 1 },
12230                inputs: vec![a, b],
12231                shape: Shape::from_dims(&[2, 6]),
12232                dtype: DType::F32,
12233            });
12234            g.set_target_backend(c, BackendId::Cpu);
12235            (a, b, c)
12236        };
12237        let mut inputs = StorageCache::new();
12238        inputs.insert(a_id, Arc::new(RwLock::new(a)));
12239        inputs.insert(b_id, Arc::new(RwLock::new(b)));
12240        let (result_arc, result_layout) =
12241            PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12242        assert_eq!(result_layout.shape().dims(), &[2, 6]);
12243        let guard = result_arc.read().unwrap();
12244        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12245            panic!("expected Cpu storage");
12246        };
12247        assert_eq!(
12248            c.as_slice::<f32>().unwrap(),
12249            &[
12250                1.0, 2.0, 3.0, 7.0, 8.0, 9.0, 4.0, 5.0, 6.0, 10.0, 11.0, 12.0
12251            ]
12252        );
12253    }
12254
12255    /// E2E: Concat with three inputs along outer dim — verifies
12256    /// variable-arity input handling through the executor.
12257    #[test]
12258    fn pipelined_realize_concat_three_inputs_outer() {
12259        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
12260        let b = fuel_memory::from_slice_cpu(&[3.0_f32, 4.0]);
12261        let c = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0]);
12262        let graph = Arc::new(RwLock::new(Graph::new()));
12263        let (a_id, b_id, c_id, cat_id) = {
12264            let mut g = graph.write().unwrap();
12265            let a = g.push(Node {
12266                op: Op::Const,
12267                inputs: vec![],
12268                shape: Shape::from_dims(&[2]),
12269                dtype: DType::F32,
12270            });
12271            let b = g.push(Node {
12272                op: Op::Const,
12273                inputs: vec![],
12274                shape: Shape::from_dims(&[2]),
12275                dtype: DType::F32,
12276            });
12277            let c = g.push(Node {
12278                op: Op::Const,
12279                inputs: vec![],
12280                shape: Shape::from_dims(&[2]),
12281                dtype: DType::F32,
12282            });
12283            let cat = g.push(Node {
12284                op: Op::Concat { dim: 0 },
12285                inputs: vec![a, b, c],
12286                shape: Shape::from_dims(&[6]),
12287                dtype: DType::F32,
12288            });
12289            g.set_target_backend(cat, BackendId::Cpu);
12290            (a, b, c, cat)
12291        };
12292        let mut inputs = StorageCache::new();
12293        inputs.insert(a_id, Arc::new(RwLock::new(a)));
12294        inputs.insert(b_id, Arc::new(RwLock::new(b)));
12295        inputs.insert(c_id, Arc::new(RwLock::new(c)));
12296        let (result_arc, _) = PipelinedExecutor::realize(graph, cat_id, inputs).expect("realize");
12297        let guard = result_arc.read().unwrap();
12298        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12299            panic!("expected Cpu storage");
12300        };
12301        assert_eq!(
12302            c.as_slice::<f32>().unwrap(),
12303            &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
12304        );
12305    }
12306
12307    /// E2E: AddScalar — graph emits Op::AddScalar; the executor
12308    /// maps it to OpKind::Affine with mul=1, add=c.
12309    #[test]
12310    fn pipelined_realize_add_scalar() {
12311        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
12312        let graph = Arc::new(RwLock::new(Graph::new()));
12313        let (in_id, op_id) = {
12314            let mut g = graph.write().unwrap();
12315            let in_id = g.push(Node {
12316                op: Op::Const,
12317                inputs: vec![],
12318                shape: Shape::from_dims(&[3]),
12319                dtype: DType::F32,
12320            });
12321            let op_id = g.push(Node {
12322                op: Op::AddScalar(10.0),
12323                inputs: vec![in_id],
12324                shape: Shape::from_dims(&[3]),
12325                dtype: DType::F32,
12326            });
12327            g.set_target_backend(op_id, BackendId::Cpu);
12328            (in_id, op_id)
12329        };
12330        let mut inputs = StorageCache::new();
12331        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12332        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12333        let guard = result_arc.read().unwrap();
12334        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12335            panic!("expected Cpu storage");
12336        };
12337        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 12.0, 13.0]);
12338    }
12339
12340    /// E2E: Clamp — clamp values to [-2, 2].
12341    #[test]
12342    fn pipelined_realize_clamp() {
12343        let storage = fuel_memory::from_slice_cpu(&[-5.0_f32, 0.5, 100.0]);
12344        let graph = Arc::new(RwLock::new(Graph::new()));
12345        let (in_id, op_id) = {
12346            let mut g = graph.write().unwrap();
12347            let in_id = g.push(Node {
12348                op: Op::Const,
12349                inputs: vec![],
12350                shape: Shape::from_dims(&[3]),
12351                dtype: DType::F32,
12352            });
12353            let op_id = g.push(Node {
12354                op: Op::Clamp {
12355                    min: -2.0,
12356                    max: 2.0,
12357                },
12358                inputs: vec![in_id],
12359                shape: Shape::from_dims(&[3]),
12360                dtype: DType::F32,
12361            });
12362            g.set_target_backend(op_id, BackendId::Cpu);
12363            (in_id, op_id)
12364        };
12365        let mut inputs = StorageCache::new();
12366        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12367        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12368        let guard = result_arc.read().unwrap();
12369        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12370            panic!("expected Cpu storage");
12371        };
12372        assert_eq!(c.as_slice::<f32>().unwrap(), &[-2.0, 0.5, 2.0]);
12373    }
12374
12375    /// E2E: Maximum — elementwise tensor max.
12376    #[test]
12377    fn pipelined_realize_maximum_elementwise() {
12378        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, -3.0]);
12379        let rhs_storage = fuel_memory::from_slice_cpu(&[2.0_f32, 1.0, -1.0]);
12380        let graph = Arc::new(RwLock::new(Graph::new()));
12381        let (lhs_id, rhs_id, op_id) = {
12382            let mut g = graph.write().unwrap();
12383            let lhs = g.push(Node {
12384                op: Op::Const,
12385                inputs: vec![],
12386                shape: Shape::from_dims(&[3]),
12387                dtype: DType::F32,
12388            });
12389            let rhs = g.push(Node {
12390                op: Op::Const,
12391                inputs: vec![],
12392                shape: Shape::from_dims(&[3]),
12393                dtype: DType::F32,
12394            });
12395            let op = g.push(Node {
12396                op: Op::Maximum,
12397                inputs: vec![lhs, rhs],
12398                shape: Shape::from_dims(&[3]),
12399                dtype: DType::F32,
12400            });
12401            g.set_target_backend(op, BackendId::Cpu);
12402            (lhs, rhs, op)
12403        };
12404        let mut inputs = StorageCache::new();
12405        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
12406        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
12407        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12408        let guard = result_arc.read().unwrap();
12409        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12410            panic!("expected Cpu storage");
12411        };
12412        assert_eq!(c.as_slice::<f32>().unwrap(), &[2.0, 5.0, -1.0]);
12413    }
12414
12415    /// E2E: Const + Const + Conv2D — the 2×2 sum-kernel test from
12416    /// byte_kernels driven through the pipelined executor.
12417    #[test]
12418    fn pipelined_realize_conv2d_2x2_sum_kernel() {
12419        // x [1, 1, 3, 3]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
12420        // weight [1, 1, 2, 2]: all-ones
12421        // → out [1, 1, 2, 2]: [[12, 16], [24, 28]]
12422        let x_storage =
12423            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
12424        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
12425
12426        let graph = Arc::new(RwLock::new(Graph::new()));
12427        let (x_id, w_id, c_id) = {
12428            let mut g = graph.write().unwrap();
12429            let x = g.push(Node {
12430                op: Op::Const,
12431                inputs: vec![],
12432                shape: Shape::from_dims(&[1, 1, 3, 3]),
12433                dtype: DType::F32,
12434            });
12435            let w = g.push(Node {
12436                op: Op::Const,
12437                inputs: vec![],
12438                shape: Shape::from_dims(&[1, 1, 2, 2]),
12439                dtype: DType::F32,
12440            });
12441            let c = g.push(Node {
12442                op: Op::Fused(
12443                    fuel_graph::registry::FusedOps::CONV2D,
12444                    fuel_graph::registry::FusedOpParams::Conv2D {
12445                        stride: (1, 1),
12446                        padding: (0, 0),
12447                        groups: 1,
12448                    },
12449                ),
12450                inputs: vec![x, w],
12451                shape: Shape::from_dims(&[1, 1, 2, 2]),
12452                dtype: DType::F32,
12453            });
12454            g.set_target_backend(c, BackendId::Cpu);
12455            (x, w, c)
12456        };
12457        let mut inputs = StorageCache::new();
12458        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12459        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12460
12461        let (result_arc, result_layout) =
12462            PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12463        assert_eq!(result_layout.shape().dims(), &[1, 1, 2, 2]);
12464
12465        let guard = result_arc.read().unwrap();
12466        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12467            panic!("expected Cpu storage");
12468        };
12469        assert_eq!(c.as_slice::<f32>().unwrap(), &[12.0, 16.0, 24.0, 28.0]);
12470    }
12471
12472    /// E2E: Conv2D with bias (3 inputs).
12473    #[test]
12474    fn pipelined_realize_conv2d_with_bias() {
12475        let x_storage =
12476            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
12477        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
12478        let bias_storage = fuel_memory::from_slice_cpu(&[100.0_f32]);
12479
12480        let graph = Arc::new(RwLock::new(Graph::new()));
12481        let (x_id, w_id, b_id, c_id) = {
12482            let mut g = graph.write().unwrap();
12483            let x = g.push(Node {
12484                op: Op::Const,
12485                inputs: vec![],
12486                shape: Shape::from_dims(&[1, 1, 3, 3]),
12487                dtype: DType::F32,
12488            });
12489            let w = g.push(Node {
12490                op: Op::Const,
12491                inputs: vec![],
12492                shape: Shape::from_dims(&[1, 1, 2, 2]),
12493                dtype: DType::F32,
12494            });
12495            let b = g.push(Node {
12496                op: Op::Const,
12497                inputs: vec![],
12498                shape: Shape::from_dims(&[1]),
12499                dtype: DType::F32,
12500            });
12501            let c = g.push(Node {
12502                op: Op::Fused(
12503                    fuel_graph::registry::FusedOps::CONV2D,
12504                    fuel_graph::registry::FusedOpParams::Conv2D {
12505                        stride: (1, 1),
12506                        padding: (0, 0),
12507                        groups: 1,
12508                    },
12509                ),
12510                inputs: vec![x, w, b],
12511                shape: Shape::from_dims(&[1, 1, 2, 2]),
12512                dtype: DType::F32,
12513            });
12514            g.set_target_backend(c, BackendId::Cpu);
12515            (x, w, b, c)
12516        };
12517        let mut inputs = StorageCache::new();
12518        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12519        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12520        inputs.insert(b_id, Arc::new(RwLock::new(bias_storage)));
12521
12522        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12523        let guard = result_arc.read().unwrap();
12524        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12525            panic!("expected Cpu storage");
12526        };
12527        assert_eq!(c.as_slice::<f32>().unwrap(), &[112.0, 116.0, 124.0, 128.0]);
12528    }
12529
12530    /// E2E: Conv2D in F64 — same 2x2 sum-kernel test as F32, on doubles.
12531    #[test]
12532    fn pipelined_realize_conv2d_f64() {
12533        let x_storage =
12534            fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
12535        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f64, 1.0, 1.0, 1.0]);
12536
12537        let graph = Arc::new(RwLock::new(Graph::new()));
12538        let (x_id, w_id, c_id) = {
12539            let mut g = graph.write().unwrap();
12540            let x = g.push(Node {
12541                op: Op::Const,
12542                inputs: vec![],
12543                shape: Shape::from_dims(&[1, 1, 3, 3]),
12544                dtype: DType::F64,
12545            });
12546            let w = g.push(Node {
12547                op: Op::Const,
12548                inputs: vec![],
12549                shape: Shape::from_dims(&[1, 1, 2, 2]),
12550                dtype: DType::F64,
12551            });
12552            let c = g.push(Node {
12553                op: Op::Fused(
12554                    fuel_graph::registry::FusedOps::CONV2D,
12555                    fuel_graph::registry::FusedOpParams::Conv2D {
12556                        stride: (1, 1),
12557                        padding: (0, 0),
12558                        groups: 1,
12559                    },
12560                ),
12561                inputs: vec![x, w],
12562                shape: Shape::from_dims(&[1, 1, 2, 2]),
12563                dtype: DType::F64,
12564            });
12565            g.set_target_backend(c, BackendId::Cpu);
12566            (x, w, c)
12567        };
12568        let mut inputs = StorageCache::new();
12569        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12570        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12571        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12572        let guard = result_arc.read().unwrap();
12573        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12574            panic!("expected Cpu storage");
12575        };
12576        assert_eq!(c.as_slice::<f64>().unwrap(), &[12.0, 16.0, 24.0, 28.0]);
12577    }
12578
12579    /// E2E: Conv2D in BF16 — f32-accumulator path. Tolerant compare.
12580    #[test]
12581    fn pipelined_realize_conv2d_bf16() {
12582        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]
12583            .iter()
12584            .map(|v| half::bf16::from_f32(*v))
12585            .collect();
12586        let w_data: Vec<half::bf16> = [1.0_f32, 1.0, 1.0, 1.0]
12587            .iter()
12588            .map(|v| half::bf16::from_f32(*v))
12589            .collect();
12590        let x_storage = fuel_memory::from_slice_cpu(&x_data);
12591        let w_storage = fuel_memory::from_slice_cpu(&w_data);
12592
12593        let graph = Arc::new(RwLock::new(Graph::new()));
12594        let (x_id, w_id, c_id) = {
12595            let mut g = graph.write().unwrap();
12596            let x = g.push(Node {
12597                op: Op::Const,
12598                inputs: vec![],
12599                shape: Shape::from_dims(&[1, 1, 3, 3]),
12600                dtype: DType::BF16,
12601            });
12602            let w = g.push(Node {
12603                op: Op::Const,
12604                inputs: vec![],
12605                shape: Shape::from_dims(&[1, 1, 2, 2]),
12606                dtype: DType::BF16,
12607            });
12608            let c = g.push(Node {
12609                op: Op::Fused(
12610                    fuel_graph::registry::FusedOps::CONV2D,
12611                    fuel_graph::registry::FusedOpParams::Conv2D {
12612                        stride: (1, 1),
12613                        padding: (0, 0),
12614                        groups: 1,
12615                    },
12616                ),
12617                inputs: vec![x, w],
12618                shape: Shape::from_dims(&[1, 1, 2, 2]),
12619                dtype: DType::BF16,
12620            });
12621            g.set_target_backend(c, BackendId::Cpu);
12622            (x, w, c)
12623        };
12624        let mut inputs = StorageCache::new();
12625        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12626        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12627        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12628        let guard = result_arc.read().unwrap();
12629        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12630            panic!("expected Cpu storage");
12631        };
12632        let got: Vec<f32> = c
12633            .as_slice::<half::bf16>()
12634            .unwrap()
12635            .iter()
12636            .map(|v| v.to_f32())
12637            .collect();
12638        let want = [12.0_f32, 16.0, 24.0, 28.0];
12639        for (g, w) in got.iter().zip(want.iter()) {
12640            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
12641        }
12642    }
12643
12644    /// E2E: Conv2D in F16 — f32-accumulator path. Tolerant compare.
12645    #[test]
12646    fn pipelined_realize_conv2d_f16() {
12647        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]
12648            .iter()
12649            .map(|v| half::f16::from_f32(*v))
12650            .collect();
12651        let w_data: Vec<half::f16> = [1.0_f32, 1.0, 1.0, 1.0]
12652            .iter()
12653            .map(|v| half::f16::from_f32(*v))
12654            .collect();
12655        let x_storage = fuel_memory::from_slice_cpu(&x_data);
12656        let w_storage = fuel_memory::from_slice_cpu(&w_data);
12657
12658        let graph = Arc::new(RwLock::new(Graph::new()));
12659        let (x_id, w_id, c_id) = {
12660            let mut g = graph.write().unwrap();
12661            let x = g.push(Node {
12662                op: Op::Const,
12663                inputs: vec![],
12664                shape: Shape::from_dims(&[1, 1, 3, 3]),
12665                dtype: DType::F16,
12666            });
12667            let w = g.push(Node {
12668                op: Op::Const,
12669                inputs: vec![],
12670                shape: Shape::from_dims(&[1, 1, 2, 2]),
12671                dtype: DType::F16,
12672            });
12673            let c = g.push(Node {
12674                op: Op::Fused(
12675                    fuel_graph::registry::FusedOps::CONV2D,
12676                    fuel_graph::registry::FusedOpParams::Conv2D {
12677                        stride: (1, 1),
12678                        padding: (0, 0),
12679                        groups: 1,
12680                    },
12681                ),
12682                inputs: vec![x, w],
12683                shape: Shape::from_dims(&[1, 1, 2, 2]),
12684                dtype: DType::F16,
12685            });
12686            g.set_target_backend(c, BackendId::Cpu);
12687            (x, w, c)
12688        };
12689        let mut inputs = StorageCache::new();
12690        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12691        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12692        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12693        let guard = result_arc.read().unwrap();
12694        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12695            panic!("expected Cpu storage");
12696        };
12697        let got: Vec<f32> = c
12698            .as_slice::<half::f16>()
12699            .unwrap()
12700            .iter()
12701            .map(|v| v.to_f32())
12702            .collect();
12703        let want = [12.0_f32, 16.0, 24.0, 28.0];
12704        for (g, w) in got.iter().zip(want.iter()) {
12705            assert!((g - w).abs() < 0.05, "got {got:?} want {want:?}");
12706        }
12707    }
12708
12709    /// E2E: Op::PagedAttn — F32, single-head, B=1, Sq=1.
12710    /// Same setup as the FlashAttn smoke test, but the K/V live in a
12711    /// paged cache that we look up via block_table.
12712    /// Layout:
12713    ///   block_size=2, num_blocks=1, max_blocks_per_seq=1.
12714    ///   k_cache shape [1, 2, 1, 2] = num_blocks × block_size × Hkv × D.
12715    ///   k_cache[block 0, slot 0, h 0] = [1, 0]
12716    ///   k_cache[block 0, slot 1, h 0] = [0, 1]
12717    ///   v_cache values: [10, 0] / [0, 10]
12718    ///   block_table[b=0, logical_block 0] = 0 (physical)
12719    ///   context_lens[0] = 2
12720    ///   q[0, 0, 0] = [2, 0]
12721    /// Causal is implicit (q_pos = ctx_len - Sq + sq = 2 - 1 + 0 = 1, both keys admissible).
12722    /// Same softmax math as FlashAttn → ~[8.808, 1.192].
12723    #[test]
12724    fn pipelined_realize_paged_attn_f32() {
12725        let q = fuel_memory::from_slice_cpu(&[2.0_f32, 0.0]);
12726        let k_cache = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
12727        let v_cache = fuel_memory::from_slice_cpu(&[10.0_f32, 0.0, 0.0, 10.0]);
12728        let block_table_u32 = fuel_memory::Storage::new(
12729            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
12730                0_u32,
12731            ])),
12732            DType::U32,
12733        );
12734        let context_lens_u32 = fuel_memory::Storage::new(
12735            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
12736                2_u32,
12737            ])),
12738            DType::U32,
12739        );
12740        let graph = Arc::new(RwLock::new(Graph::new()));
12741        let (q_id, kc_id, vc_id, bt_id, cl_id, op_id) = {
12742            let mut g = graph.write().unwrap();
12743            let q = g.push(Node {
12744                op: Op::Const,
12745                inputs: vec![],
12746                shape: Shape::from_dims(&[1, 1, 1, 2]),
12747                dtype: DType::F32,
12748            });
12749            let kc = g.push(Node {
12750                op: Op::Const,
12751                inputs: vec![],
12752                shape: Shape::from_dims(&[1, 2, 1, 2]),
12753                dtype: DType::F32,
12754            });
12755            let vc = g.push(Node {
12756                op: Op::Const,
12757                inputs: vec![],
12758                shape: Shape::from_dims(&[1, 2, 1, 2]),
12759                dtype: DType::F32,
12760            });
12761            let bt = g.push(Node {
12762                op: Op::Const,
12763                inputs: vec![],
12764                shape: Shape::from_dims(&[1, 1]),
12765                dtype: DType::U32,
12766            });
12767            let cl = g.push(Node {
12768                op: Op::Const,
12769                inputs: vec![],
12770                shape: Shape::from_dims(&[1]),
12771                dtype: DType::U32,
12772            });
12773            let op = g.push(Node {
12774                op: Op::Fused(
12775                    fuel_graph::registry::FusedOps::PAGED_ATTN,
12776                    fuel_graph::registry::FusedOpParams::PagedAttn {
12777                        softmax_scale: 1.0,
12778                        block_size: 2,
12779                        softcap: None,
12780                    },
12781                ),
12782                inputs: vec![q, kc, vc, bt, cl],
12783                shape: Shape::from_dims(&[1, 1, 1, 2]),
12784                dtype: DType::F32,
12785            });
12786            g.set_target_backend(op, BackendId::Cpu);
12787            (q, kc, vc, bt, cl, op)
12788        };
12789        let mut inputs = StorageCache::new();
12790        inputs.insert(q_id, Arc::new(RwLock::new(q)));
12791        inputs.insert(kc_id, Arc::new(RwLock::new(k_cache)));
12792        inputs.insert(vc_id, Arc::new(RwLock::new(v_cache)));
12793        inputs.insert(bt_id, Arc::new(RwLock::new(block_table_u32)));
12794        inputs.insert(cl_id, Arc::new(RwLock::new(context_lens_u32)));
12795        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12796        let guard = result_arc.read().unwrap();
12797        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12798            panic!("expected Cpu storage");
12799        };
12800        let r = c.as_slice::<f32>().unwrap();
12801        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
12802        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
12803        assert!(
12804            (r[0] - 10.0 * expected_p0).abs() < 1e-5,
12805            "row[0]: got {} expected {}",
12806            r[0],
12807            10.0 * expected_p0
12808        );
12809        assert!(
12810            (r[1] - 10.0 * expected_p1).abs() < 1e-5,
12811            "row[1]: got {} expected {}",
12812            r[1],
12813            10.0 * expected_p1
12814        );
12815    }
12816
12817    /// E2E: PagedAttn BF16 — same single-row test, tolerant.
12818    #[test]
12819    fn pipelined_realize_paged_attn_bf16() {
12820        let q_v: Vec<half::bf16> = [2.0_f32, 0.0]
12821            .iter()
12822            .map(|x| half::bf16::from_f32(*x))
12823            .collect();
12824        let kc_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0]
12825            .iter()
12826            .map(|x| half::bf16::from_f32(*x))
12827            .collect();
12828        let vc_v: Vec<half::bf16> = [10.0_f32, 0.0, 0.0, 10.0]
12829            .iter()
12830            .map(|x| half::bf16::from_f32(*x))
12831            .collect();
12832        let q = fuel_memory::from_slice_cpu(&q_v);
12833        let k_cache = fuel_memory::from_slice_cpu(&kc_v);
12834        let v_cache = fuel_memory::from_slice_cpu(&vc_v);
12835        let bt = fuel_memory::Storage::new(
12836            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
12837                0_u32,
12838            ])),
12839            DType::U32,
12840        );
12841        let cl = fuel_memory::Storage::new(
12842            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
12843                2_u32,
12844            ])),
12845            DType::U32,
12846        );
12847        let graph = Arc::new(RwLock::new(Graph::new()));
12848        let (q_id, kc_id, vc_id, bt_id, cl_id, op_id) = {
12849            let mut g = graph.write().unwrap();
12850            let q = g.push(Node {
12851                op: Op::Const,
12852                inputs: vec![],
12853                shape: Shape::from_dims(&[1, 1, 1, 2]),
12854                dtype: DType::BF16,
12855            });
12856            let kc = g.push(Node {
12857                op: Op::Const,
12858                inputs: vec![],
12859                shape: Shape::from_dims(&[1, 2, 1, 2]),
12860                dtype: DType::BF16,
12861            });
12862            let vc = g.push(Node {
12863                op: Op::Const,
12864                inputs: vec![],
12865                shape: Shape::from_dims(&[1, 2, 1, 2]),
12866                dtype: DType::BF16,
12867            });
12868            let bt = g.push(Node {
12869                op: Op::Const,
12870                inputs: vec![],
12871                shape: Shape::from_dims(&[1, 1]),
12872                dtype: DType::U32,
12873            });
12874            let cl = g.push(Node {
12875                op: Op::Const,
12876                inputs: vec![],
12877                shape: Shape::from_dims(&[1]),
12878                dtype: DType::U32,
12879            });
12880            let op = g.push(Node {
12881                op: Op::Fused(
12882                    fuel_graph::registry::FusedOps::PAGED_ATTN,
12883                    fuel_graph::registry::FusedOpParams::PagedAttn {
12884                        softmax_scale: 1.0,
12885                        block_size: 2,
12886                        softcap: None,
12887                    },
12888                ),
12889                inputs: vec![q, kc, vc, bt, cl],
12890                shape: Shape::from_dims(&[1, 1, 1, 2]),
12891                dtype: DType::BF16,
12892            });
12893            g.set_target_backend(op, BackendId::Cpu);
12894            (q, kc, vc, bt, cl, op)
12895        };
12896        let mut inputs = StorageCache::new();
12897        inputs.insert(q_id, Arc::new(RwLock::new(q)));
12898        inputs.insert(kc_id, Arc::new(RwLock::new(k_cache)));
12899        inputs.insert(vc_id, Arc::new(RwLock::new(v_cache)));
12900        inputs.insert(bt_id, Arc::new(RwLock::new(bt)));
12901        inputs.insert(cl_id, Arc::new(RwLock::new(cl)));
12902        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12903        let guard = result_arc.read().unwrap();
12904        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12905            panic!("expected Cpu storage");
12906        };
12907        let got: Vec<f32> = c
12908            .as_slice::<half::bf16>()
12909            .unwrap()
12910            .iter()
12911            .map(|v| v.to_f32())
12912            .collect();
12913        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
12914        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
12915        let want = [10.0 * expected_p0, 10.0 * expected_p1];
12916        for (g, w) in got.iter().zip(want.iter()) {
12917            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
12918        }
12919    }
12920
12921    /// E2E: Op::FlashAttn — F32 single-head, single-batch, no mask.
12922    /// q = [[2.0, 0.0]], k = [[1.0, 0.0], [0.0, 1.0]], v = [[10, 0], [0, 10]]
12923    /// scale = 1.0
12924    /// scores = q · kᵀ = [2.0, 0.0]
12925    /// softmax = [e^2/(e^2+1), 1/(e^2+1)] ≈ [0.8808, 0.1192]
12926    /// out = softmax @ v = [10*0.8808, 10*0.1192] ≈ [8.808, 1.192]
12927    #[test]
12928    fn pipelined_realize_flash_attn_f32() {
12929        // [B=1, H=1, S=1or2, D=2]
12930        let q = fuel_memory::from_slice_cpu(&[2.0_f32, 0.0]);
12931        let k = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
12932        let v = fuel_memory::from_slice_cpu(&[10.0_f32, 0.0, 0.0, 10.0]);
12933        let graph = Arc::new(RwLock::new(Graph::new()));
12934        let (q_id, k_id, v_id, op_id) = {
12935            let mut g = graph.write().unwrap();
12936            let q = g.push(Node {
12937                op: Op::Const,
12938                inputs: vec![],
12939                shape: Shape::from_dims(&[1, 1, 1, 2]),
12940                dtype: DType::F32,
12941            });
12942            let k = g.push(Node {
12943                op: Op::Const,
12944                inputs: vec![],
12945                shape: Shape::from_dims(&[1, 1, 2, 2]),
12946                dtype: DType::F32,
12947            });
12948            let v = g.push(Node {
12949                op: Op::Const,
12950                inputs: vec![],
12951                shape: Shape::from_dims(&[1, 1, 2, 2]),
12952                dtype: DType::F32,
12953            });
12954            let op = g.push(Node {
12955                op: Op::Fused(
12956                    fuel_graph::registry::FusedOps::FLASH_ATTN,
12957                    fuel_graph::registry::FusedOpParams::FlashAttn {
12958                        softmax_scale: 1.0,
12959                        causal: false,
12960                        window_size_left: None,
12961                        window_size_right: None,
12962                        softcap: None,
12963                        k_len: None,
12964                    },
12965                ),
12966                inputs: vec![q, k, v],
12967                shape: Shape::from_dims(&[1, 1, 1, 2]),
12968                dtype: DType::F32,
12969            });
12970            g.set_target_backend(op, BackendId::Cpu);
12971            (q, k, v, op)
12972        };
12973        let mut inputs = StorageCache::new();
12974        inputs.insert(q_id, Arc::new(RwLock::new(q)));
12975        inputs.insert(k_id, Arc::new(RwLock::new(k)));
12976        inputs.insert(v_id, Arc::new(RwLock::new(v)));
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: FlashAttn with causal mask — second query position
13000    /// attends to both keys (positions 0 and 1), first only attends
13001    /// to key 0 (everything beyond is masked).
13002    #[test]
13003    fn pipelined_realize_flash_attn_causal_f32() {
13004        // q [1,1,2,2]: query 0 = [1, 0], query 1 = [0, 1]
13005        // k [1,1,2,2]: keys = [[1, 0], [0, 1]]
13006        // v [1,1,2,2]: values = [[5, 6], [7, 8]]
13007        // softmax_scale=1, causal:
13008        //   query 0: only key 0 admissible → out = v[0] = [5, 6]
13009        //   query 1: both admissible. scores = q1·k = [0, 1]
13010        //            softmax = [1/(e+1), e/(e+1)]
13011        //            out = scores · v = [(5)/(e+1) + 7e/(e+1), 6/(e+1) + 8e/(e+1)]
13012        let q = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13013        let k = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13014        let v = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0, 7.0, 8.0]);
13015        let graph = Arc::new(RwLock::new(Graph::new()));
13016        let (q_id, k_id, v_id, op_id) = {
13017            let mut g = graph.write().unwrap();
13018            let q = g.push(Node {
13019                op: Op::Const,
13020                inputs: vec![],
13021                shape: Shape::from_dims(&[1, 1, 2, 2]),
13022                dtype: DType::F32,
13023            });
13024            let k = g.push(Node {
13025                op: Op::Const,
13026                inputs: vec![],
13027                shape: Shape::from_dims(&[1, 1, 2, 2]),
13028                dtype: DType::F32,
13029            });
13030            let v = g.push(Node {
13031                op: Op::Const,
13032                inputs: vec![],
13033                shape: Shape::from_dims(&[1, 1, 2, 2]),
13034                dtype: DType::F32,
13035            });
13036            let op = g.push(Node {
13037                op: Op::Fused(
13038                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13039                    fuel_graph::registry::FusedOpParams::FlashAttn {
13040                        softmax_scale: 1.0,
13041                        causal: true,
13042                        window_size_left: None,
13043                        window_size_right: None,
13044                        softcap: None,
13045                        k_len: None,
13046                    },
13047                ),
13048                inputs: vec![q, k, v],
13049                shape: Shape::from_dims(&[1, 1, 2, 2]),
13050                dtype: DType::F32,
13051            });
13052            g.set_target_backend(op, BackendId::Cpu);
13053            (q, k, v, op)
13054        };
13055        let mut inputs = StorageCache::new();
13056        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13057        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13058        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13059        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13060        let guard = result_arc.read().unwrap();
13061        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13062            panic!("expected Cpu storage");
13063        };
13064        let r = c.as_slice::<f32>().unwrap();
13065        // Query 0 sees only key 0 → output = v[0]
13066        assert!((r[0] - 5.0).abs() < 1e-5, "got {}", r[0]);
13067        assert!((r[1] - 6.0).abs() < 1e-5, "got {}", r[1]);
13068        // Query 1 sees both. softmax([0, 1]) = [1/(e+1), e/(e+1)]
13069        let denom = (1.0_f32).exp() + 1.0;
13070        let expected_a = 5.0 / denom + 7.0 * (1.0_f32).exp() / denom;
13071        let expected_b = 6.0 / denom + 8.0 * (1.0_f32).exp() / denom;
13072        assert!(
13073            (r[2] - expected_a).abs() < 1e-5,
13074            "row1[0]: got {} expected {}",
13075            r[2],
13076            expected_a
13077        );
13078        assert!(
13079            (r[3] - expected_b).abs() < 1e-5,
13080            "row1[1]: got {} expected {}",
13081            r[3],
13082            expected_b
13083        );
13084    }
13085
13086    /// E2E: FlashAttn over a fixed-**capacity** K/V with a runtime
13087    /// `k_len` resolved through a `SymEnv` (Phase D symbolic extents).
13088    /// Only the first `k_len` rows are attended; trailing "poison" rows
13089    /// in the capacity buffer are ignored, and the causal mask is
13090    /// bottom-right-aligned at offset `k_len - Sq`. This is flash decode
13091    /// over a persistent KV-cache: K/V are `[.., max_seq, ..]` capacity
13092    /// and the live prefix grows per token.
13093    #[test]
13094    fn pipelined_realize_flash_attn_dynamic_k_len() {
13095        use fuel_ir::{DynScalar, SymId};
13096        // q [1,1,2,2]; K/V capacity [1,1,4,2]; bind k_len = 3 so row 3
13097        // (the "poison" row) is never attended.
13098        let q = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13099        let k = fuel_memory::from_slice_cpu(&[
13100            1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0, 100.0,
13101            100.0, // poison row 3 — must be ignored (k_len=3)
13102        ]);
13103        let v = fuel_memory::from_slice_cpu(&[
13104            5.0_f32, 6.0, 7.0, 8.0, 9.0, 10.0, 999.0,
13105            999.0, // poison row 3 — must be ignored
13106        ]);
13107        let sym = SymId(0);
13108        let graph = Arc::new(RwLock::new(Graph::new()));
13109        let (q_id, k_id, v_id, op_id) = {
13110            let mut g = graph.write().unwrap();
13111            let q = g.push(Node {
13112                op: Op::Const,
13113                inputs: vec![],
13114                shape: Shape::from_dims(&[1, 1, 2, 2]),
13115                dtype: DType::F32,
13116            });
13117            let k = g.push(Node {
13118                op: Op::Const,
13119                inputs: vec![],
13120                shape: Shape::from_dims(&[1, 1, 4, 2]),
13121                dtype: DType::F32,
13122            });
13123            let v = g.push(Node {
13124                op: Op::Const,
13125                inputs: vec![],
13126                shape: Shape::from_dims(&[1, 1, 4, 2]),
13127                dtype: DType::F32,
13128            });
13129            let op = g.push(Node {
13130                op: Op::Fused(
13131                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13132                    fuel_graph::registry::FusedOpParams::FlashAttn {
13133                        softmax_scale: 1.0,
13134                        causal: true,
13135                        window_size_left: None,
13136                        window_size_right: None,
13137                        softcap: None,
13138                        k_len: Some(DynScalar::Sym(sym)),
13139                    },
13140                ),
13141                inputs: vec![q, k, v],
13142                shape: Shape::from_dims(&[1, 1, 2, 2]),
13143                dtype: DType::F32,
13144            });
13145            g.set_target_backend(op, BackendId::Cpu);
13146            (q, k, v, op)
13147        };
13148        let mut inputs = StorageCache::new();
13149        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13150        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13151        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13152        let mut env = SymEnv::new();
13153        env.bind(sym, 3).unwrap();
13154        let (result_arc, _) = PipelinedExecutor::realize_with_env(graph, op_id, inputs, env)
13155            .expect("realize_with_env");
13156        let guard = result_arc.read().unwrap();
13157        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13158            panic!("expected Cpu storage");
13159        };
13160        let r = c.as_slice::<f32>().unwrap();
13161        let e = 1.0_f32.exp();
13162        // causal_offset = k_len - Sq = 3 - 2 = 1.
13163        // Query 0 (abs pos 1): keys {0,1}. scores [1,0] → softmax [e,1]/(e+1).
13164        let d0 = e + 1.0;
13165        let e0x = (5.0 * e + 7.0) / d0;
13166        let e0y = (6.0 * e + 8.0) / d0;
13167        // Query 1 (abs pos 2): keys {0,1,2}. scores [0,1,1] → [1,e,e]/(1+2e).
13168        let d1 = 1.0 + 2.0 * e;
13169        let e1x = (5.0 + 7.0 * e + 9.0 * e) / d1;
13170        let e1y = (6.0 + 8.0 * e + 10.0 * e) / d1;
13171        for (got, want) in r.iter().zip([e0x, e0y, e1x, e1y].iter()) {
13172            assert!(
13173                (got - want).abs() < 1e-4,
13174                "flash dyn k_len: got {got}, want {want} (full output {r:?}); \
13175                 a poison-contaminated value means the capacity rows past k_len leaked in",
13176            );
13177        }
13178    }
13179
13180    /// A flash `k_len` symbol unbound in the `SymEnv` surfaces a typed
13181    /// error at realize (never a panic).
13182    #[test]
13183    fn pipelined_realize_flash_attn_dynamic_k_len_unbound_errors() {
13184        use fuel_ir::{DynScalar, SymId};
13185        let q = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13186        let k = fuel_memory::from_slice_cpu(&[0.0_f32; 16]);
13187        let v = fuel_memory::from_slice_cpu(&[0.0_f32; 16]);
13188        let graph = Arc::new(RwLock::new(Graph::new()));
13189        let (q_id, k_id, v_id, op_id) = {
13190            let mut g = graph.write().unwrap();
13191            let q = g.push(Node {
13192                op: Op::Const,
13193                inputs: vec![],
13194                shape: Shape::from_dims(&[1, 1, 2, 2]),
13195                dtype: DType::F32,
13196            });
13197            let k = g.push(Node {
13198                op: Op::Const,
13199                inputs: vec![],
13200                shape: Shape::from_dims(&[1, 1, 4, 2]),
13201                dtype: DType::F32,
13202            });
13203            let v = g.push(Node {
13204                op: Op::Const,
13205                inputs: vec![],
13206                shape: Shape::from_dims(&[1, 1, 4, 2]),
13207                dtype: DType::F32,
13208            });
13209            let op = g.push(Node {
13210                op: Op::Fused(
13211                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13212                    fuel_graph::registry::FusedOpParams::FlashAttn {
13213                        softmax_scale: 1.0,
13214                        causal: true,
13215                        window_size_left: None,
13216                        window_size_right: None,
13217                        softcap: None,
13218                        k_len: Some(DynScalar::Sym(SymId(0))),
13219                    },
13220                ),
13221                inputs: vec![q, k, v],
13222                shape: Shape::from_dims(&[1, 1, 2, 2]),
13223                dtype: DType::F32,
13224            });
13225            g.set_target_backend(op, BackendId::Cpu);
13226            (q, k, v, op)
13227        };
13228        let mut inputs = StorageCache::new();
13229        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13230        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13231        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13232        // Empty env — the k_len symbol is unbound.
13233        let result = PipelinedExecutor::realize_with_env(graph, op_id, inputs, SymEnv::new());
13234        assert!(
13235            result.is_err(),
13236            "unbound flash k_len symbol must surface a typed error"
13237        );
13238    }
13239
13240    /// E2E: FlashAttn BF16 — same single-row test as f32, tolerant.
13241    #[test]
13242    fn pipelined_realize_flash_attn_bf16() {
13243        let q_v: Vec<half::bf16> = [2.0_f32, 0.0]
13244            .iter()
13245            .map(|x| half::bf16::from_f32(*x))
13246            .collect();
13247        let k_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0]
13248            .iter()
13249            .map(|x| half::bf16::from_f32(*x))
13250            .collect();
13251        let v_v: Vec<half::bf16> = [10.0_f32, 0.0, 0.0, 10.0]
13252            .iter()
13253            .map(|x| half::bf16::from_f32(*x))
13254            .collect();
13255        let q = fuel_memory::from_slice_cpu(&q_v);
13256        let k = fuel_memory::from_slice_cpu(&k_v);
13257        let v = fuel_memory::from_slice_cpu(&v_v);
13258        let graph = Arc::new(RwLock::new(Graph::new()));
13259        let (q_id, k_id, v_id, op_id) = {
13260            let mut g = graph.write().unwrap();
13261            let q = g.push(Node {
13262                op: Op::Const,
13263                inputs: vec![],
13264                shape: Shape::from_dims(&[1, 1, 1, 2]),
13265                dtype: DType::BF16,
13266            });
13267            let k = g.push(Node {
13268                op: Op::Const,
13269                inputs: vec![],
13270                shape: Shape::from_dims(&[1, 1, 2, 2]),
13271                dtype: DType::BF16,
13272            });
13273            let v = g.push(Node {
13274                op: Op::Const,
13275                inputs: vec![],
13276                shape: Shape::from_dims(&[1, 1, 2, 2]),
13277                dtype: DType::BF16,
13278            });
13279            let op = g.push(Node {
13280                op: Op::Fused(
13281                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13282                    fuel_graph::registry::FusedOpParams::FlashAttn {
13283                        softmax_scale: 1.0,
13284                        causal: false,
13285                        window_size_left: None,
13286                        window_size_right: None,
13287                        softcap: None,
13288                        k_len: None,
13289                    },
13290                ),
13291                inputs: vec![q, k, v],
13292                shape: Shape::from_dims(&[1, 1, 1, 2]),
13293                dtype: DType::BF16,
13294            });
13295            g.set_target_backend(op, BackendId::Cpu);
13296            (q, k, v, op)
13297        };
13298        let mut inputs = StorageCache::new();
13299        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13300        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13301        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13302        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13303        let guard = result_arc.read().unwrap();
13304        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13305            panic!("expected Cpu storage");
13306        };
13307        let got: Vec<f32> = c
13308            .as_slice::<half::bf16>()
13309            .unwrap()
13310            .iter()
13311            .map(|v| v.to_f32())
13312            .collect();
13313        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
13314        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
13315        let want = [10.0 * expected_p0, 10.0 * expected_p1];
13316        for (g, w) in got.iter().zip(want.iter()) {
13317            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
13318        }
13319    }
13320
13321    /// E2E: Op::FusedLinear — F32. a[1,2,3] @ b[1,3,2] + bias[2].
13322    /// a = [[[1,2,3],[4,5,6]]], b = [[[1,0],[0,1],[1,1]]], bias=[10,20]
13323    /// matmul = [[1+0+3, 0+2+3], [4+0+6, 0+5+6]] = [[4, 5], [10, 11]]
13324    /// + bias = [[14, 25], [20, 31]]
13325    #[test]
13326    fn pipelined_realize_fused_linear_f32() {
13327        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
13328        let b = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0]);
13329        let bias = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
13330        let graph = Arc::new(RwLock::new(Graph::new()));
13331        let (a_id, b_id, bias_id, op_id) = {
13332            let mut g = graph.write().unwrap();
13333            let a = g.push(Node {
13334                op: Op::Const,
13335                inputs: vec![],
13336                shape: Shape::from_dims(&[1, 2, 3]),
13337                dtype: DType::F32,
13338            });
13339            let b = g.push(Node {
13340                op: Op::Const,
13341                inputs: vec![],
13342                shape: Shape::from_dims(&[1, 3, 2]),
13343                dtype: DType::F32,
13344            });
13345            let bias = g.push(Node {
13346                op: Op::Const,
13347                inputs: vec![],
13348                shape: Shape::from_dims(&[2]),
13349                dtype: DType::F32,
13350            });
13351            let op = g.push(Node {
13352                op: Op::Fused(
13353                    fuel_graph::registry::FusedOps::FUSED_LINEAR,
13354                    fuel_graph::registry::FusedOpParams::FusedLinear,
13355                ),
13356                inputs: vec![a, b, bias],
13357                shape: Shape::from_dims(&[1, 2, 2]),
13358                dtype: DType::F32,
13359            });
13360            g.set_target_backend(op, BackendId::Cpu);
13361            (a, b, bias, op)
13362        };
13363        let mut inputs = StorageCache::new();
13364        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13365        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13366        inputs.insert(bias_id, Arc::new(RwLock::new(bias)));
13367        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13368        let guard = result_arc.read().unwrap();
13369        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13370            panic!("expected Cpu storage");
13371        };
13372        assert_eq!(c.as_slice::<f32>().unwrap(), &[14.0, 25.0, 20.0, 31.0]);
13373    }
13374
13375    /// E2E: FusedLinear F64 — same shape test on doubles.
13376    #[test]
13377    fn pipelined_realize_fused_linear_f64() {
13378        let a = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
13379        let b = fuel_memory::from_slice_cpu(&[1.0_f64, 0.0, 0.0, 1.0, 1.0, 1.0]);
13380        let bias = fuel_memory::from_slice_cpu(&[10.0_f64, 20.0]);
13381        let graph = Arc::new(RwLock::new(Graph::new()));
13382        let (a_id, b_id, bias_id, op_id) = {
13383            let mut g = graph.write().unwrap();
13384            let a = g.push(Node {
13385                op: Op::Const,
13386                inputs: vec![],
13387                shape: Shape::from_dims(&[1, 2, 3]),
13388                dtype: DType::F64,
13389            });
13390            let b = g.push(Node {
13391                op: Op::Const,
13392                inputs: vec![],
13393                shape: Shape::from_dims(&[1, 3, 2]),
13394                dtype: DType::F64,
13395            });
13396            let bias = g.push(Node {
13397                op: Op::Const,
13398                inputs: vec![],
13399                shape: Shape::from_dims(&[2]),
13400                dtype: DType::F64,
13401            });
13402            let op = g.push(Node {
13403                op: Op::Fused(
13404                    fuel_graph::registry::FusedOps::FUSED_LINEAR,
13405                    fuel_graph::registry::FusedOpParams::FusedLinear,
13406                ),
13407                inputs: vec![a, b, bias],
13408                shape: Shape::from_dims(&[1, 2, 2]),
13409                dtype: DType::F64,
13410            });
13411            g.set_target_backend(op, BackendId::Cpu);
13412            (a, b, bias, op)
13413        };
13414        let mut inputs = StorageCache::new();
13415        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13416        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13417        inputs.insert(bias_id, Arc::new(RwLock::new(bias)));
13418        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13419        let guard = result_arc.read().unwrap();
13420        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13421            panic!("expected Cpu storage");
13422        };
13423        assert_eq!(c.as_slice::<f64>().unwrap(), &[14.0, 25.0, 20.0, 31.0]);
13424    }
13425
13426    /// E2E: FusedLinear BF16 — tolerant compare.
13427    #[test]
13428    fn pipelined_realize_fused_linear_bf16() {
13429        let a_v: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]
13430            .iter()
13431            .map(|x| half::bf16::from_f32(*x))
13432            .collect();
13433        let b_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0]
13434            .iter()
13435            .map(|x| half::bf16::from_f32(*x))
13436            .collect();
13437        let bias_v: Vec<half::bf16> = [10.0_f32, 20.0]
13438            .iter()
13439            .map(|x| half::bf16::from_f32(*x))
13440            .collect();
13441        let a = fuel_memory::from_slice_cpu(&a_v);
13442        let b = fuel_memory::from_slice_cpu(&b_v);
13443        let bias = fuel_memory::from_slice_cpu(&bias_v);
13444        let graph = Arc::new(RwLock::new(Graph::new()));
13445        let (a_id, b_id, bias_id, op_id) = {
13446            let mut g = graph.write().unwrap();
13447            let a = g.push(Node {
13448                op: Op::Const,
13449                inputs: vec![],
13450                shape: Shape::from_dims(&[1, 2, 3]),
13451                dtype: DType::BF16,
13452            });
13453            let b = g.push(Node {
13454                op: Op::Const,
13455                inputs: vec![],
13456                shape: Shape::from_dims(&[1, 3, 2]),
13457                dtype: DType::BF16,
13458            });
13459            let bias = g.push(Node {
13460                op: Op::Const,
13461                inputs: vec![],
13462                shape: Shape::from_dims(&[2]),
13463                dtype: DType::BF16,
13464            });
13465            let op = g.push(Node {
13466                op: Op::Fused(
13467                    fuel_graph::registry::FusedOps::FUSED_LINEAR,
13468                    fuel_graph::registry::FusedOpParams::FusedLinear,
13469                ),
13470                inputs: vec![a, b, bias],
13471                shape: Shape::from_dims(&[1, 2, 2]),
13472                dtype: DType::BF16,
13473            });
13474            g.set_target_backend(op, BackendId::Cpu);
13475            (a, b, bias, op)
13476        };
13477        let mut inputs = StorageCache::new();
13478        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13479        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13480        inputs.insert(bias_id, Arc::new(RwLock::new(bias)));
13481        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13482        let guard = result_arc.read().unwrap();
13483        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13484            panic!("expected Cpu storage");
13485        };
13486        let got: Vec<f32> = c
13487            .as_slice::<half::bf16>()
13488            .unwrap()
13489            .iter()
13490            .map(|v| v.to_f32())
13491            .collect();
13492        let want = [14.0_f32, 25.0, 20.0, 31.0];
13493        for (g, w) in got.iter().zip(want.iter()) {
13494            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
13495        }
13496    }
13497
13498    /// E2E: Op::ReduceSumTo — sum the leading axis of a [2,3] tensor.
13499    /// Input [[1,2,3],[4,5,6]] → output [5,7,9].
13500    #[test]
13501    fn pipelined_realize_reduce_sum_to_f32_drops_leading_axis() {
13502        let v = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
13503        let graph = Arc::new(RwLock::new(Graph::new()));
13504        let (in_id, op_id) = {
13505            let mut g = graph.write().unwrap();
13506            let in_id = g.push(Node {
13507                op: Op::Const,
13508                inputs: vec![],
13509                shape: Shape::from_dims(&[2, 3]),
13510                dtype: DType::F32,
13511            });
13512            let op_id = g.push(Node {
13513                op: Op::ReduceSumTo(Shape::from_dims(&[3])),
13514                inputs: vec![in_id],
13515                shape: Shape::from_dims(&[3]),
13516                dtype: DType::F32,
13517            });
13518            g.set_target_backend(op_id, BackendId::Cpu);
13519            (in_id, op_id)
13520        };
13521        let mut inputs = StorageCache::new();
13522        inputs.insert(in_id, Arc::new(RwLock::new(v)));
13523        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13524        let guard = result_arc.read().unwrap();
13525        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13526            panic!("expected Cpu storage");
13527        };
13528        assert_eq!(c.as_slice::<f32>().unwrap(), &[5.0, 7.0, 9.0]);
13529    }
13530
13531    /// E2E: Op::ReduceSumTo — keep-dim with 1 in the middle.
13532    /// Input [2,3,4] → [2,1,4] sums along dim 1.
13533    #[test]
13534    fn pipelined_realize_reduce_sum_to_f32_keepdim_middle() {
13535        // [2,3,4]: layer 0 = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
13536        //          layer 1 = [[13..16],[17..20],[21..24]]
13537        let mut v: Vec<f32> = (1..=24).map(|x| x as f32).collect();
13538        let _ = &mut v;
13539        let s = fuel_memory::from_slice_cpu(&v);
13540        let graph = Arc::new(RwLock::new(Graph::new()));
13541        let (in_id, op_id) = {
13542            let mut g = graph.write().unwrap();
13543            let in_id = g.push(Node {
13544                op: Op::Const,
13545                inputs: vec![],
13546                shape: Shape::from_dims(&[2, 3, 4]),
13547                dtype: DType::F32,
13548            });
13549            let op_id = g.push(Node {
13550                op: Op::ReduceSumTo(Shape::from_dims(&[2, 1, 4])),
13551                inputs: vec![in_id],
13552                shape: Shape::from_dims(&[2, 1, 4]),
13553                dtype: DType::F32,
13554            });
13555            g.set_target_backend(op_id, BackendId::Cpu);
13556            (in_id, op_id)
13557        };
13558        let mut inputs = StorageCache::new();
13559        inputs.insert(in_id, Arc::new(RwLock::new(s)));
13560        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13561        let guard = result_arc.read().unwrap();
13562        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13563            panic!("expected Cpu storage");
13564        };
13565        // layer0 dim1-sum: col j = 1+5+9, 2+6+10, 3+7+11, 4+8+12 = [15,18,21,24]
13566        // layer1 dim1-sum: col j = 13+17+21, 14+18+22, 15+19+23, 16+20+24 = [51,54,57,60]
13567        assert_eq!(
13568            c.as_slice::<f32>().unwrap(),
13569            &[15.0, 18.0, 21.0, 24.0, 51.0, 54.0, 57.0, 60.0],
13570        );
13571    }
13572
13573    /// E2E: ReduceSumTo F64 — same drop-leading-axis test on doubles.
13574    #[test]
13575    fn pipelined_realize_reduce_sum_to_f64() {
13576        let v = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
13577        let graph = Arc::new(RwLock::new(Graph::new()));
13578        let (in_id, op_id) = {
13579            let mut g = graph.write().unwrap();
13580            let in_id = g.push(Node {
13581                op: Op::Const,
13582                inputs: vec![],
13583                shape: Shape::from_dims(&[2, 3]),
13584                dtype: DType::F64,
13585            });
13586            let op_id = g.push(Node {
13587                op: Op::ReduceSumTo(Shape::from_dims(&[3])),
13588                inputs: vec![in_id],
13589                shape: Shape::from_dims(&[3]),
13590                dtype: DType::F64,
13591            });
13592            g.set_target_backend(op_id, BackendId::Cpu);
13593            (in_id, op_id)
13594        };
13595        let mut inputs = StorageCache::new();
13596        inputs.insert(in_id, Arc::new(RwLock::new(v)));
13597        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13598        let guard = result_arc.read().unwrap();
13599        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13600            panic!("expected Cpu storage");
13601        };
13602        assert_eq!(c.as_slice::<f64>().unwrap(), &[5.0, 7.0, 9.0]);
13603    }
13604
13605    /// E2E: Op::ReduceMaxTo F32 — drop the leading axis with max-reduce.
13606    #[test]
13607    fn pipelined_realize_reduce_max_to_f32_drops_leading_axis() {
13608        // Input [2,3]: row 0 = [1, 7, 3], row 1 = [4, 2, 6]. Max along
13609        // dim 0: [4, 7, 6].
13610        let v = fuel_memory::from_slice_cpu(&[1.0_f32, 7.0, 3.0, 4.0, 2.0, 6.0]);
13611        let graph = Arc::new(RwLock::new(Graph::new()));
13612        let (in_id, op_id) = {
13613            let mut g = graph.write().unwrap();
13614            let in_id = g.push(Node {
13615                op: Op::Const,
13616                inputs: vec![],
13617                shape: Shape::from_dims(&[2, 3]),
13618                dtype: DType::F32,
13619            });
13620            let op_id = g.push(Node {
13621                op: Op::ReduceMaxTo(Shape::from_dims(&[3])),
13622                inputs: vec![in_id],
13623                shape: Shape::from_dims(&[3]),
13624                dtype: DType::F32,
13625            });
13626            g.set_target_backend(op_id, BackendId::Cpu);
13627            (in_id, op_id)
13628        };
13629        let mut inputs = StorageCache::new();
13630        inputs.insert(in_id, Arc::new(RwLock::new(v)));
13631        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13632        let guard = result_arc.read().unwrap();
13633        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13634            panic!("expected Cpu storage");
13635        };
13636        assert_eq!(c.as_slice::<f32>().unwrap(), &[4.0, 7.0, 6.0]);
13637    }
13638
13639    /// E2E: Op::ReduceMaxTo F32 — keep-dim with 1 in the trailing axis.
13640    /// Mirrors the SoftmaxLastDim lowering's max-side shape: input
13641    /// [..., last] → [..., 1].
13642    #[test]
13643    fn pipelined_realize_reduce_max_to_f32_keepdim_trailing() {
13644        // Input [2, 3]: row maxes = [3, 6].
13645        let v = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
13646        let graph = Arc::new(RwLock::new(Graph::new()));
13647        let (in_id, op_id) = {
13648            let mut g = graph.write().unwrap();
13649            let in_id = g.push(Node {
13650                op: Op::Const,
13651                inputs: vec![],
13652                shape: Shape::from_dims(&[2, 3]),
13653                dtype: DType::F32,
13654            });
13655            let op_id = g.push(Node {
13656                op: Op::ReduceMaxTo(Shape::from_dims(&[2, 1])),
13657                inputs: vec![in_id],
13658                shape: Shape::from_dims(&[2, 1]),
13659                dtype: DType::F32,
13660            });
13661            g.set_target_backend(op_id, BackendId::Cpu);
13662            (in_id, op_id)
13663        };
13664        let mut inputs = StorageCache::new();
13665        inputs.insert(in_id, Arc::new(RwLock::new(v)));
13666        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13667        let guard = result_arc.read().unwrap();
13668        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13669            panic!("expected Cpu storage");
13670        };
13671        assert_eq!(c.as_slice::<f32>().unwrap(), &[3.0, 6.0]);
13672    }
13673
13674    /// E2E: ReduceSumTo BF16 — tolerant compare via f32-acc.
13675    #[test]
13676    fn pipelined_realize_reduce_sum_to_bf16() {
13677        let v: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]
13678            .iter()
13679            .map(|x| half::bf16::from_f32(*x))
13680            .collect();
13681        let s = fuel_memory::from_slice_cpu(&v);
13682        let graph = Arc::new(RwLock::new(Graph::new()));
13683        let (in_id, op_id) = {
13684            let mut g = graph.write().unwrap();
13685            let in_id = g.push(Node {
13686                op: Op::Const,
13687                inputs: vec![],
13688                shape: Shape::from_dims(&[2, 3]),
13689                dtype: DType::BF16,
13690            });
13691            let op_id = g.push(Node {
13692                op: Op::ReduceSumTo(Shape::from_dims(&[3])),
13693                inputs: vec![in_id],
13694                shape: Shape::from_dims(&[3]),
13695                dtype: DType::BF16,
13696            });
13697            g.set_target_backend(op_id, BackendId::Cpu);
13698            (in_id, op_id)
13699        };
13700        let mut inputs = StorageCache::new();
13701        inputs.insert(in_id, Arc::new(RwLock::new(s)));
13702        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13703        let guard = result_arc.read().unwrap();
13704        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13705            panic!("expected Cpu storage");
13706        };
13707        let got: Vec<f32> = c
13708            .as_slice::<half::bf16>()
13709            .unwrap()
13710            .iter()
13711            .map(|v| v.to_f32())
13712            .collect();
13713        let want = [5.0_f32, 7.0, 9.0];
13714        for (g, w) in got.iter().zip(want.iter()) {
13715            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
13716        }
13717    }
13718
13719    /// E2E: Op::ConvTranspose2D — F32 spread test.
13720    /// x = [[1, 2], [3, 4]] shape [1,1,2,2], all-ones kernel
13721    /// shape [1,1,2,2], stride=1, padding=0, dilation=1, no bias.
13722    /// Expected output (3x3):
13723    ///   [[1,  3, 2],
13724    ///    [4, 10, 6],
13725    ///    [3,  7, 4]]
13726    #[test]
13727    fn pipelined_realize_conv_transpose2d_f32() {
13728        let x_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
13729        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
13730        let graph = Arc::new(RwLock::new(Graph::new()));
13731        let (x_id, w_id, c_id) = {
13732            let mut g = graph.write().unwrap();
13733            let x = g.push(Node {
13734                op: Op::Const,
13735                inputs: vec![],
13736                shape: Shape::from_dims(&[1, 1, 2, 2]),
13737                dtype: DType::F32,
13738            });
13739            let w = g.push(Node {
13740                op: Op::Const,
13741                inputs: vec![],
13742                shape: Shape::from_dims(&[1, 1, 2, 2]),
13743                dtype: DType::F32,
13744            });
13745            let c = g.push(Node {
13746                op: Op::Fused(
13747                    fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D,
13748                    fuel_graph::registry::FusedOpParams::ConvTranspose2D {
13749                        stride: (1, 1),
13750                        padding: (0, 0),
13751                        output_padding: (0, 0),
13752                        dilation: (1, 1),
13753                        groups: 1,
13754                    },
13755                ),
13756                inputs: vec![x, w],
13757                shape: Shape::from_dims(&[1, 1, 3, 3]),
13758                dtype: DType::F32,
13759            });
13760            g.set_target_backend(c, BackendId::Cpu);
13761            (x, w, c)
13762        };
13763        let mut inputs = StorageCache::new();
13764        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
13765        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
13766        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
13767        let guard = result_arc.read().unwrap();
13768        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13769            panic!("expected Cpu storage");
13770        };
13771        assert_eq!(
13772            c.as_slice::<f32>().unwrap(),
13773            &[1.0, 3.0, 2.0, 4.0, 10.0, 6.0, 3.0, 7.0, 4.0],
13774        );
13775    }
13776
13777    /// E2E: ConvTranspose2D F64 — same shape test.
13778    #[test]
13779    fn pipelined_realize_conv_transpose2d_f64() {
13780        let x_storage = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0]);
13781        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f64, 1.0, 1.0, 1.0]);
13782        let graph = Arc::new(RwLock::new(Graph::new()));
13783        let (x_id, w_id, c_id) = {
13784            let mut g = graph.write().unwrap();
13785            let x = g.push(Node {
13786                op: Op::Const,
13787                inputs: vec![],
13788                shape: Shape::from_dims(&[1, 1, 2, 2]),
13789                dtype: DType::F64,
13790            });
13791            let w = g.push(Node {
13792                op: Op::Const,
13793                inputs: vec![],
13794                shape: Shape::from_dims(&[1, 1, 2, 2]),
13795                dtype: DType::F64,
13796            });
13797            let c = g.push(Node {
13798                op: Op::Fused(
13799                    fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D,
13800                    fuel_graph::registry::FusedOpParams::ConvTranspose2D {
13801                        stride: (1, 1),
13802                        padding: (0, 0),
13803                        output_padding: (0, 0),
13804                        dilation: (1, 1),
13805                        groups: 1,
13806                    },
13807                ),
13808                inputs: vec![x, w],
13809                shape: Shape::from_dims(&[1, 1, 3, 3]),
13810                dtype: DType::F64,
13811            });
13812            g.set_target_backend(c, BackendId::Cpu);
13813            (x, w, c)
13814        };
13815        let mut inputs = StorageCache::new();
13816        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
13817        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
13818        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
13819        let guard = result_arc.read().unwrap();
13820        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13821            panic!("expected Cpu storage");
13822        };
13823        assert_eq!(
13824            c.as_slice::<f64>().unwrap(),
13825            &[1.0, 3.0, 2.0, 4.0, 10.0, 6.0, 3.0, 7.0, 4.0],
13826        );
13827    }
13828
13829    /// E2E: ConvTranspose2D BF16 — tolerant compare via f32-acc.
13830    #[test]
13831    fn pipelined_realize_conv_transpose2d_bf16() {
13832        let x: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0]
13833            .iter()
13834            .map(|v| half::bf16::from_f32(*v))
13835            .collect();
13836        let w: Vec<half::bf16> = [1.0_f32, 1.0, 1.0, 1.0]
13837            .iter()
13838            .map(|v| half::bf16::from_f32(*v))
13839            .collect();
13840        let x_storage = fuel_memory::from_slice_cpu(&x);
13841        let w_storage = fuel_memory::from_slice_cpu(&w);
13842        let graph = Arc::new(RwLock::new(Graph::new()));
13843        let (x_id, w_id, c_id) = {
13844            let mut g = graph.write().unwrap();
13845            let x = g.push(Node {
13846                op: Op::Const,
13847                inputs: vec![],
13848                shape: Shape::from_dims(&[1, 1, 2, 2]),
13849                dtype: DType::BF16,
13850            });
13851            let w = g.push(Node {
13852                op: Op::Const,
13853                inputs: vec![],
13854                shape: Shape::from_dims(&[1, 1, 2, 2]),
13855                dtype: DType::BF16,
13856            });
13857            let c = g.push(Node {
13858                op: Op::Fused(
13859                    fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D,
13860                    fuel_graph::registry::FusedOpParams::ConvTranspose2D {
13861                        stride: (1, 1),
13862                        padding: (0, 0),
13863                        output_padding: (0, 0),
13864                        dilation: (1, 1),
13865                        groups: 1,
13866                    },
13867                ),
13868                inputs: vec![x, w],
13869                shape: Shape::from_dims(&[1, 1, 3, 3]),
13870                dtype: DType::BF16,
13871            });
13872            g.set_target_backend(c, BackendId::Cpu);
13873            (x, w, c)
13874        };
13875        let mut inputs = StorageCache::new();
13876        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
13877        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
13878        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
13879        let guard = result_arc.read().unwrap();
13880        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13881            panic!("expected Cpu storage");
13882        };
13883        let got: Vec<f32> = c
13884            .as_slice::<half::bf16>()
13885            .unwrap()
13886            .iter()
13887            .map(|v| v.to_f32())
13888            .collect();
13889        let want = [1.0_f32, 3.0, 2.0, 4.0, 10.0, 6.0, 3.0, 7.0, 4.0];
13890        for (g, w) in got.iter().zip(want.iter()) {
13891            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
13892        }
13893    }
13894
13895    /// E2E: GQA-style matmul through the pipelined executor.
13896    /// lhs has 4 batch heads, rhs has 2; each rhs head is shared
13897    /// by 2 lhs heads. Output's batch dim follows lhs (4 heads).
13898    #[test]
13899    fn pipelined_realize_matmul_gqa() {
13900        // lhs [4, 1, 2]: heads 0..3 are [[1,2]], [[3,4]], [[5,6]], [[7,8]]
13901        // rhs [2, 2, 1]: heads 0,1 are [[1],[0]], [[0],[1]]
13902        // Expected out [4, 1, 1]: [[1]], [[3]], [[6]], [[8]]
13903        let lhs_storage =
13904            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]);
13905        let rhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13906
13907        let graph = Arc::new(RwLock::new(Graph::new()));
13908        let (lhs_id, rhs_id, mm_id) = {
13909            let mut g = graph.write().unwrap();
13910            let lhs = g.push(Node {
13911                op: Op::Const,
13912                inputs: vec![],
13913                shape: Shape::from_dims(&[4, 1, 2]),
13914                dtype: DType::F32,
13915            });
13916            let rhs = g.push(Node {
13917                op: Op::Const,
13918                inputs: vec![],
13919                shape: Shape::from_dims(&[2, 2, 1]),
13920                dtype: DType::F32,
13921            });
13922            let mm = g.push(Node {
13923                op: Op::MatMul,
13924                inputs: vec![lhs, rhs],
13925                shape: Shape::from_dims(&[4, 1, 1]),
13926                dtype: DType::F32,
13927            });
13928            g.set_target_backend(mm, BackendId::Cpu);
13929            (lhs, rhs, mm)
13930        };
13931        let mut inputs = StorageCache::new();
13932        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
13933        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
13934
13935        let (result_arc, result_layout) =
13936            PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
13937        assert_eq!(result_layout.shape().dims(), &[4, 1, 1]);
13938
13939        let guard = result_arc.read().unwrap();
13940        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13941            panic!("expected Cpu storage");
13942        };
13943        assert_eq!(c.as_slice::<f32>().unwrap(), &[1.0, 3.0, 6.0, 8.0]);
13944    }
13945
13946    /// E2E: matmul with a transposed rhs — proves stage 3+4
13947    /// integration carries through the matmul path. The transpose
13948    /// is metadata-only; auto-Contiguize materializes the strided
13949    /// rhs before the matmul kernel sees it.
13950    #[test]
13951    fn pipelined_realize_matmul_with_transposed_rhs() {
13952        // lhs [[1, 2], [3, 4]], rhs original [[5, 6], [7, 8]]
13953        // rhs.T = [[5, 7], [6, 8]]
13954        // lhs @ rhs.T = [[1*5+2*6, 1*7+2*8], [3*5+4*6, 3*7+4*8]]
13955        //             = [[17, 23], [39, 53]]
13956        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
13957        let rhs_storage = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0, 7.0, 8.0]);
13958
13959        let graph = Arc::new(RwLock::new(Graph::new()));
13960        let (lhs_id, rhs_id, t_id, mm_id) = {
13961            let mut g = graph.write().unwrap();
13962            let lhs = g.push(Node {
13963                op: Op::Const,
13964                inputs: vec![],
13965                shape: Shape::from_dims(&[2, 2]),
13966                dtype: DType::F32,
13967            });
13968            let rhs = g.push(Node {
13969                op: Op::Const,
13970                inputs: vec![],
13971                shape: Shape::from_dims(&[2, 2]),
13972                dtype: DType::F32,
13973            });
13974            let t = g.push(Node {
13975                op: Op::Transpose,
13976                inputs: vec![rhs],
13977                shape: Shape::from_dims(&[2, 2]),
13978                dtype: DType::F32,
13979            });
13980            let mm = g.push(Node {
13981                op: Op::MatMul,
13982                inputs: vec![lhs, t],
13983                shape: Shape::from_dims(&[2, 2]),
13984                dtype: DType::F32,
13985            });
13986            g.set_target_backend(mm, BackendId::Cpu);
13987            (lhs, rhs, t, mm)
13988        };
13989        let _ = t_id;
13990        let mut inputs = StorageCache::new();
13991        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
13992        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
13993
13994        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
13995        let guard = result_arc.read().unwrap();
13996        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13997            panic!("expected Cpu storage");
13998        };
13999        assert_eq!(c.as_slice::<f32>().unwrap(), &[17.0, 23.0, 39.0, 53.0]);
14000    }
14001
14002    /// E2E: Const + Reshape — contiguous-input reshape is zero
14003    /// copy. The output Storage Arc is the input Arc; the layout
14004    /// is contiguous in the new shape.
14005    #[test]
14006    fn pipelined_realize_reshape_zero_copy_when_contiguous() {
14007        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14008        let graph = Arc::new(RwLock::new(Graph::new()));
14009        let (in_id, r_id) = {
14010            let mut g = graph.write().unwrap();
14011            let in_id = g.push(Node {
14012                op: Op::Const,
14013                inputs: vec![],
14014                shape: Shape::from_dims(&[2, 3]),
14015                dtype: DType::F32,
14016            });
14017            let r_id = g.push(Node {
14018                op: Op::Reshape(Shape::from_dims(&[3, 2])),
14019                inputs: vec![in_id],
14020                shape: Shape::from_dims(&[3, 2]),
14021                dtype: DType::F32,
14022            });
14023            (in_id, r_id)
14024        };
14025        let mut inputs = StorageCache::new();
14026        let in_arc = Arc::new(RwLock::new(storage));
14027        inputs.insert(in_id, Arc::clone(&in_arc));
14028
14029        let (result_arc, result_layout) =
14030            PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
14031
14032        // Zero copy — same Arc.
14033        assert!(
14034            Arc::ptr_eq(&result_arc, &in_arc),
14035            "contiguous reshape must zero-copy"
14036        );
14037        assert_eq!(result_layout.shape().dims(), &[3, 2]);
14038        assert!(result_layout.is_contiguous());
14039
14040        // Bytes are unchanged; just reinterpreted as [3, 2].
14041        let guard = result_arc.read().unwrap();
14042        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14043            panic!("expected Cpu storage");
14044        };
14045        assert_eq!(
14046            c.as_slice::<f32>().unwrap(),
14047            &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
14048        );
14049    }
14050
14051    /// E2E: Const + Transpose + Reshape — reshape on a strided
14052    /// input auto-contiguizes the bytes. Output Arc is fresh
14053    /// (NOT the input Arc); the bytes are the materialized
14054    /// transposed layout.
14055    #[test]
14056    fn pipelined_realize_reshape_materializes_when_strided() {
14057        // shape [2, 3]: 1 2 3 / 4 5 6
14058        // Transpose → [3, 2] strided
14059        // Reshape → [6] (forces materialization)
14060        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14061        let graph = Arc::new(RwLock::new(Graph::new()));
14062        let (in_id, t_id, r_id) = {
14063            let mut g = graph.write().unwrap();
14064            let in_id = g.push(Node {
14065                op: Op::Const,
14066                inputs: vec![],
14067                shape: Shape::from_dims(&[2, 3]),
14068                dtype: DType::F32,
14069            });
14070            let t_id = g.push(Node {
14071                op: Op::Transpose,
14072                inputs: vec![in_id],
14073                shape: Shape::from_dims(&[3, 2]),
14074                dtype: DType::F32,
14075            });
14076            let r_id = g.push(Node {
14077                op: Op::Reshape(Shape::from_dims(&[6])),
14078                inputs: vec![t_id],
14079                shape: Shape::from_dims(&[6]),
14080                dtype: DType::F32,
14081            });
14082            (in_id, t_id, r_id)
14083        };
14084        let _ = t_id;
14085        let mut inputs = StorageCache::new();
14086        let in_arc = Arc::new(RwLock::new(storage));
14087        inputs.insert(in_id, Arc::clone(&in_arc));
14088
14089        let (result_arc, result_layout) =
14090            PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
14091
14092        // Fresh Arc — auto-contiguize allocated new bytes.
14093        assert!(!Arc::ptr_eq(&result_arc, &in_arc));
14094        assert_eq!(result_layout.shape().dims(), &[6]);
14095        assert!(result_layout.is_contiguous());
14096
14097        // Materialized transposed bytes flattened: [1, 4, 2, 5, 3, 6].
14098        let guard = result_arc.read().unwrap();
14099        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14100            panic!("expected Cpu storage");
14101        };
14102        assert_eq!(
14103            c.as_slice::<f32>().unwrap(),
14104            &[1.0, 4.0, 2.0, 5.0, 3.0, 6.0]
14105        );
14106    }
14107
14108    /// E2E: Const + Transpose + SumDim — exercises stage 3
14109    /// (metadata-only Transpose, strided intermediate Layout) +
14110    /// stage 4 (auto-Contiguize before reduce kernel) end-to-end.
14111    /// The transpose makes the intermediate non-contiguous; the
14112    /// reduce wrapper would have failed in stage 2; with stage 4's
14113    /// auto-Contiguize, the kernel sees the materialized contiguous
14114    /// transposed bytes and produces the right answer.
14115    #[test]
14116    fn pipelined_realize_transpose_then_sum_dim_e2e() {
14117        // shape [2, 3]: rows are [1, 2, 3], [4, 5, 6]
14118        // After transpose: shape [3, 2], rows are [1, 4], [2, 5], [3, 6]
14119        // After SumDim(1): shape [3], values [5, 7, 9]
14120        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14121        let graph = Arc::new(RwLock::new(Graph::new()));
14122        let (in_id, t_id, sum_id) = {
14123            let mut g = graph.write().unwrap();
14124            let in_id = g.push(Node {
14125                op: Op::Const,
14126                inputs: vec![],
14127                shape: Shape::from_dims(&[2, 3]),
14128                dtype: DType::F32,
14129            });
14130            let t_id = g.push(Node {
14131                op: Op::Transpose,
14132                inputs: vec![in_id],
14133                shape: Shape::from_dims(&[3, 2]),
14134                dtype: DType::F32,
14135            });
14136            let sum_id = g.push(Node {
14137                op: Op::SumDim(1),
14138                inputs: vec![t_id],
14139                shape: Shape::from_dims(&[3]),
14140                dtype: DType::F32,
14141            });
14142            // Only the reduce kernel runs on the backend; the
14143            // transpose is metadata-only and doesn't need a target.
14144            g.set_target_backend(sum_id, BackendId::Cpu);
14145            (in_id, t_id, sum_id)
14146        };
14147        let _ = t_id;
14148        let mut inputs = StorageCache::new();
14149        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14150
14151        let (result_arc, result_layout) =
14152            PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
14153
14154        // The reduce output is contiguous (kernel-produced).
14155        assert_eq!(result_layout.shape().dims(), &[3]);
14156        assert!(result_layout.is_contiguous());
14157
14158        let guard = result_arc.read().unwrap();
14159        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14160            panic!("expected Cpu storage");
14161        };
14162        let typed: &[f32] = c.as_slice().unwrap();
14163        assert_eq!(typed, &[5.0, 7.0, 9.0]);
14164    }
14165
14166    /// E2E: Const + BroadcastTo + Add — broadcast intermediate
14167    /// auto-contiguizes for the Add kernel; the result is the
14168    /// expected sum.
14169    #[test]
14170    fn pipelined_realize_broadcast_then_add_e2e() {
14171        // shape [3]: [10, 20, 30]
14172        // BroadcastTo [2, 3]: [[10, 20, 30], [10, 20, 30]]
14173        // Plus shape [2, 3]: [[1, 2, 3], [4, 5, 6]]
14174        // Result: [[11, 22, 33], [14, 25, 36]]
14175        let bc_input = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
14176        let plus_input = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14177        let graph = Arc::new(RwLock::new(Graph::new()));
14178        let (bc_in_id, plus_in_id, b_id, add_id) = {
14179            let mut g = graph.write().unwrap();
14180            let bc_in = g.push(Node {
14181                op: Op::Const,
14182                inputs: vec![],
14183                shape: Shape::from_dims(&[3]),
14184                dtype: DType::F32,
14185            });
14186            let plus_in = g.push(Node {
14187                op: Op::Const,
14188                inputs: vec![],
14189                shape: Shape::from_dims(&[2, 3]),
14190                dtype: DType::F32,
14191            });
14192            let b = g.push(Node {
14193                op: Op::BroadcastTo(Shape::from_dims(&[2, 3])),
14194                inputs: vec![bc_in],
14195                shape: Shape::from_dims(&[2, 3]),
14196                dtype: DType::F32,
14197            });
14198            let add = g.push(Node {
14199                op: Op::Add,
14200                inputs: vec![b, plus_in],
14201                shape: Shape::from_dims(&[2, 3]),
14202                dtype: DType::F32,
14203            });
14204            g.set_target_backend(add, BackendId::Cpu);
14205            (bc_in, plus_in, b, add)
14206        };
14207        let _ = b_id;
14208        let mut inputs = StorageCache::new();
14209        inputs.insert(bc_in_id, Arc::new(RwLock::new(bc_input)));
14210        inputs.insert(plus_in_id, Arc::new(RwLock::new(plus_input)));
14211
14212        let (result_arc, _result_layout) =
14213            PipelinedExecutor::realize(graph, add_id, inputs).expect("realize");
14214        let guard = result_arc.read().unwrap();
14215        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14216            panic!("expected Cpu storage");
14217        };
14218        let typed: &[f32] = c.as_slice().unwrap();
14219        assert_eq!(typed, &[11.0, 22.0, 33.0, 14.0, 25.0, 36.0]);
14220    }
14221
14222    /// E2E: Const + SumDim — verifies that `OpParams::Reduce`
14223    /// flows from the graph (input shape via `op_to_op_params`)
14224    /// through compile_one and reaches the reduce kernel.
14225    #[test]
14226    fn pipelined_realize_sum_dim() {
14227        // shape [2, 3]; reduce dim 1 → output shape [2]
14228        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14229        let graph = Arc::new(RwLock::new(Graph::new()));
14230        let (in_id, sum_id) = {
14231            let mut g = graph.write().unwrap();
14232            let in_id = g.push(Node {
14233                op: Op::Const,
14234                inputs: vec![],
14235                shape: Shape::from_dims(&[2, 3]),
14236                dtype: DType::F32,
14237            });
14238            let sum_id = g.push(Node {
14239                op: Op::SumDim(1),
14240                inputs: vec![in_id],
14241                shape: Shape::from_dims(&[2]),
14242                dtype: DType::F32,
14243            });
14244            g.set_target_backend(sum_id, BackendId::Cpu);
14245            (in_id, sum_id)
14246        };
14247        let mut inputs = StorageCache::new();
14248        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14249
14250        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
14251        let guard = result_arc.read().unwrap();
14252        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14253            let typed: &[f32] = c.as_slice().unwrap();
14254            assert_eq!(typed, &[6.0, 15.0]);
14255        }
14256    }
14257
14258    /// E2E: SumAll on a rank-3 input, exercising the all-dims branch
14259    /// of `op_to_op_params` (every dim reduced, rank-0 output).
14260    #[test]
14261    fn pipelined_realize_sum_all_rank3() {
14262        let data: Vec<f32> = (1..=24).map(|x| x as f32).collect();
14263        let storage = fuel_memory::from_slice_cpu(&data);
14264        let graph = Arc::new(RwLock::new(Graph::new()));
14265        let (in_id, sum_id) = {
14266            let mut g = graph.write().unwrap();
14267            let in_id = g.push(Node {
14268                op: Op::Const,
14269                inputs: vec![],
14270                shape: Shape::from_dims(&[2, 3, 4]),
14271                dtype: DType::F32,
14272            });
14273            let sum_id = g.push(Node {
14274                op: Op::SumAll,
14275                inputs: vec![in_id],
14276                shape: Shape::from_dims(&[]),
14277                dtype: DType::F32,
14278            });
14279            g.set_target_backend(sum_id, BackendId::Cpu);
14280            (in_id, sum_id)
14281        };
14282        let mut inputs = StorageCache::new();
14283        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14284
14285        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
14286        let guard = result_arc.read().unwrap();
14287        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14288            let typed: &[f32] = c.as_slice().unwrap();
14289            // 1 + 2 + ... + 24 = 300
14290            assert_eq!(typed, &[300.0]);
14291        }
14292    }
14293
14294    /// E2E: MaxDim + MeanDim chained — verifies all four reduce
14295    /// OpKinds reach their wrappers via the OpParams plumbing.
14296    #[test]
14297    fn pipelined_realize_max_then_mean() {
14298        // shape [2, 3], MaxDim(1) → [2], MeanDim(0) → []
14299        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 9.0, 3.0, 4.0, 2.0, 8.0]);
14300        let graph = Arc::new(RwLock::new(Graph::new()));
14301        let (in_id, mean_id) = {
14302            let mut g = graph.write().unwrap();
14303            let in_id = g.push(Node {
14304                op: Op::Const,
14305                inputs: vec![],
14306                shape: Shape::from_dims(&[2, 3]),
14307                dtype: DType::F32,
14308            });
14309            let max_id = g.push(Node {
14310                op: Op::MaxDim(1),
14311                inputs: vec![in_id],
14312                shape: Shape::from_dims(&[2]),
14313                dtype: DType::F32,
14314            });
14315            let mean_id = g.push(Node {
14316                op: Op::MeanDim(0),
14317                inputs: vec![max_id],
14318                shape: Shape::from_dims(&[]),
14319                dtype: DType::F32,
14320            });
14321            g.set_target_backend(max_id, BackendId::Cpu);
14322            g.set_target_backend(mean_id, BackendId::Cpu);
14323            (in_id, mean_id)
14324        };
14325        let mut inputs = StorageCache::new();
14326        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14327
14328        let (result_arc, _) = PipelinedExecutor::realize(graph, mean_id, inputs).expect("realize");
14329        let guard = result_arc.read().unwrap();
14330        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14331            let typed: &[f32] = c.as_slice().unwrap();
14332            // MaxDim(1) on [[1,9,3],[4,2,8]] = [9, 8]; MeanDim(0) = 8.5
14333            assert_eq!(typed, &[8.5]);
14334        }
14335    }
14336
14337    /// E2E: Sigmoid + Silu — exercises two of the more compositional
14338    /// new unary kernels through the pipelined executor. Verifies
14339    /// the additional `op_to_op_kind` mappings reach the right
14340    /// dispatch wrappers.
14341    #[test]
14342    fn pipelined_realize_sigmoid_then_silu() {
14343        let storage = fuel_memory::from_slice_cpu(&[0.0_f32, 1.0, -1.0]);
14344        let graph = Arc::new(RwLock::new(Graph::new()));
14345        let (in_id, sig_id, silu_id) = {
14346            let mut g = graph.write().unwrap();
14347            let in_id = g.push(Node {
14348                op: Op::Const,
14349                inputs: vec![],
14350                shape: Shape::from_dims(&[3]),
14351                dtype: DType::F32,
14352            });
14353            let sig_id = g.push(Node {
14354                op: Op::Sigmoid,
14355                inputs: vec![in_id],
14356                shape: Shape::from_dims(&[3]),
14357                dtype: DType::F32,
14358            });
14359            // Silu of the sigmoid output — chains to confirm cache flow.
14360            let silu_id = g.push(Node {
14361                op: Op::Silu,
14362                inputs: vec![sig_id],
14363                shape: Shape::from_dims(&[3]),
14364                dtype: DType::F32,
14365            });
14366            g.set_target_backend(sig_id, BackendId::Cpu);
14367            g.set_target_backend(silu_id, BackendId::Cpu);
14368            (in_id, sig_id, silu_id)
14369        };
14370        let _ = sig_id;
14371        let mut inputs = StorageCache::new();
14372        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14373
14374        let (result_arc, _) = PipelinedExecutor::realize(graph, silu_id, inputs).expect("realize");
14375        let guard = result_arc.read().unwrap();
14376        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14377            let typed: &[f32] = c.as_slice().unwrap();
14378            // sigmoid(0) = 0.5; silu(0.5) = 0.5 * sigmoid(0.5) ≈ 0.3112
14379            assert!((typed[0] - 0.5 * (1.0 / (1.0 + (-0.5_f32).exp()))).abs() < 1e-6);
14380        }
14381    }
14382
14383    /// E2E: chained unary ops — Const + Sqr + Sqrt should be a noop
14384    /// for non-negative inputs. Exercises the cache reuse path.
14385    #[test]
14386    fn pipelined_realize_chained_unary_sqr_then_sqrt() {
14387        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 4.0, 9.0]);
14388        let graph = Arc::new(RwLock::new(Graph::new()));
14389        let (in_id, sqrt_id) = {
14390            let mut g = graph.write().unwrap();
14391            let in_id = g.push(Node {
14392                op: Op::Const,
14393                inputs: vec![],
14394                shape: Shape::from_dims(&[3]),
14395                dtype: DType::F32,
14396            });
14397            let sqr_id = g.push(Node {
14398                op: Op::Sqr,
14399                inputs: vec![in_id],
14400                shape: Shape::from_dims(&[3]),
14401                dtype: DType::F32,
14402            });
14403            let sqrt_id = g.push(Node {
14404                op: Op::Sqrt,
14405                inputs: vec![sqr_id],
14406                shape: Shape::from_dims(&[3]),
14407                dtype: DType::F32,
14408            });
14409            g.set_target_backend(sqr_id, BackendId::Cpu);
14410            g.set_target_backend(sqrt_id, BackendId::Cpu);
14411            (in_id, sqrt_id)
14412        };
14413        let mut inputs = StorageCache::new();
14414        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14415
14416        let (result_arc, _) = PipelinedExecutor::realize(graph, sqrt_id, inputs).expect("realize");
14417        let guard = result_arc.read().unwrap();
14418        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14419            let typed: &[f32] = c.as_slice().unwrap();
14420            // sqrt(sqr(x)) == |x| == x for non-negative inputs.
14421            assert_eq!(typed, &[1.0, 4.0, 9.0]);
14422        }
14423    }
14424
14425    /// Multi-stage pipelined: Const + Const + Add + Add (chain of
14426    /// two adds). Tests that work items are processed in topo order
14427    /// and intermediate results are cached and reused.
14428    #[test]
14429    fn pipelined_realize_chained_adds() {
14430        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
14431        let b_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
14432        let c_storage = fuel_memory::from_slice_cpu(&[100.0_f32, 200.0]);
14433
14434        let graph = Arc::new(RwLock::new(Graph::new()));
14435        let (a_id, b_id, c_id, ab_id, abc_id) = {
14436            let mut g = graph.write().unwrap();
14437            let a = g.push(Node {
14438                op: Op::Const,
14439                inputs: vec![],
14440                shape: Shape::from_dims(&[2]),
14441                dtype: DType::F32,
14442            });
14443            let b = g.push(Node {
14444                op: Op::Const,
14445                inputs: vec![],
14446                shape: Shape::from_dims(&[2]),
14447                dtype: DType::F32,
14448            });
14449            let c = g.push(Node {
14450                op: Op::Const,
14451                inputs: vec![],
14452                shape: Shape::from_dims(&[2]),
14453                dtype: DType::F32,
14454            });
14455            let ab = g.push(Node {
14456                op: Op::Add,
14457                inputs: vec![a, b],
14458                shape: Shape::from_dims(&[2]),
14459                dtype: DType::F32,
14460            });
14461            let abc = g.push(Node {
14462                op: Op::Add,
14463                inputs: vec![ab, c],
14464                shape: Shape::from_dims(&[2]),
14465                dtype: DType::F32,
14466            });
14467            g.set_target_backend(ab, BackendId::Cpu);
14468            g.set_target_backend(abc, BackendId::Cpu);
14469            (a, b, c, ab, abc)
14470        };
14471
14472        let mut inputs = StorageCache::new();
14473        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
14474        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
14475        inputs.insert(c_id, Arc::new(RwLock::new(c_storage)));
14476
14477        let (result_arc, _) = PipelinedExecutor::realize(graph, abc_id, inputs).expect("realize");
14478        // Suppress unused warning for the intermediate id.
14479        let _ = ab_id;
14480
14481        let guard = result_arc.read().unwrap();
14482        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14483            let typed: &[f32] = c.as_slice().unwrap();
14484            // (1+10) + 100 = 111;  (2+20) + 200 = 222.
14485            assert_eq!(typed, &[111.0, 222.0]);
14486        }
14487    }
14488
14489    /// E2E: triu(diagonal=0) on a 3×3 matrix.
14490    /// Input:  [1 2 3 / 4 5 6 / 7 8 9]
14491    /// Output: [1 2 3 / 0 5 6 / 0 0 9]
14492    #[test]
14493    fn pipelined_realize_triu_3x3_diag0() {
14494        let storage =
14495            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
14496        let graph = Arc::new(RwLock::new(Graph::new()));
14497        let (in_id, out_id) = {
14498            let mut g = graph.write().unwrap();
14499            let in_id = g.push(Node {
14500                op: Op::Const,
14501                inputs: vec![],
14502                shape: Shape::from_dims(&[3, 3]),
14503                dtype: DType::F32,
14504            });
14505            let out_id = g.push(Node {
14506                op: Op::Triu { diagonal: 0 },
14507                inputs: vec![in_id],
14508                shape: Shape::from_dims(&[3, 3]),
14509                dtype: DType::F32,
14510            });
14511            g.set_target_backend(out_id, BackendId::Cpu);
14512            (in_id, out_id)
14513        };
14514        let mut inputs = StorageCache::new();
14515        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14516        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
14517        let guard = result_arc.read().unwrap();
14518        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14519            panic!("expected Cpu storage");
14520        };
14521        let out: &[f32] = c.as_slice().unwrap();
14522        assert_eq!(out, &[1.0, 2.0, 3.0, 0.0, 5.0, 6.0, 0.0, 0.0, 9.0,]);
14523    }
14524
14525    /// E2E: tril(diagonal=0) on a 3×3 matrix — the canonical causal mask.
14526    /// Output: [1 0 0 / 4 5 0 / 7 8 9]
14527    #[test]
14528    fn pipelined_realize_tril_3x3_diag0_causal_mask() {
14529        let storage =
14530            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
14531        let graph = Arc::new(RwLock::new(Graph::new()));
14532        let (in_id, out_id) = {
14533            let mut g = graph.write().unwrap();
14534            let in_id = g.push(Node {
14535                op: Op::Const,
14536                inputs: vec![],
14537                shape: Shape::from_dims(&[3, 3]),
14538                dtype: DType::F32,
14539            });
14540            let out_id = g.push(Node {
14541                op: Op::Tril { diagonal: 0 },
14542                inputs: vec![in_id],
14543                shape: Shape::from_dims(&[3, 3]),
14544                dtype: DType::F32,
14545            });
14546            g.set_target_backend(out_id, BackendId::Cpu);
14547            (in_id, out_id)
14548        };
14549        let mut inputs = StorageCache::new();
14550        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14551        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
14552        let guard = result_arc.read().unwrap();
14553        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14554            panic!("expected Cpu storage");
14555        };
14556        let out: &[f32] = c.as_slice().unwrap();
14557        assert_eq!(out, &[1.0, 0.0, 0.0, 4.0, 5.0, 0.0, 7.0, 8.0, 9.0,]);
14558    }
14559
14560    /// E2E: log_softmax over a 2×3 input. Rows are [1,2,3] and [3,2,1].
14561    /// log_softmax(row) = row - max - log(sum exp(row - max)).
14562    /// Row 0: max=3, exp(-2)+exp(-1)+exp(0) = 0.135+0.368+1.0 = 1.503;
14563    ///        log(1.503) ≈ 0.4076; out = [1-3-0.4076, 2-3-0.4076, 3-3-0.4076]
14564    ///                              = [-2.4076, -1.4076, -0.4076]
14565    /// Row 1 is row 0 reversed: [-0.4076, -1.4076, -2.4076].
14566    #[test]
14567    fn pipelined_realize_log_softmax_last_dim() {
14568        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 3.0, 2.0, 1.0]);
14569        let graph = Arc::new(RwLock::new(Graph::new()));
14570        let (in_id, out_id) = {
14571            let mut g = graph.write().unwrap();
14572            let in_id = g.push(Node {
14573                op: Op::Const,
14574                inputs: vec![],
14575                shape: Shape::from_dims(&[2, 3]),
14576                dtype: DType::F32,
14577            });
14578            let out_id = g.push(Node {
14579                op: Op::LogSoftmaxLastDim,
14580                inputs: vec![in_id],
14581                shape: Shape::from_dims(&[2, 3]),
14582                dtype: DType::F32,
14583            });
14584            g.set_target_backend(out_id, BackendId::Cpu);
14585            (in_id, out_id)
14586        };
14587        let mut inputs = StorageCache::new();
14588        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14589        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
14590        let guard = result_arc.read().unwrap();
14591        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14592            panic!("expected Cpu storage");
14593        };
14594        let out: &[f32] = c.as_slice().unwrap();
14595        let expected = [
14596            -2.407_606,
14597            -1.4076059,
14598            -0.40760595_f32,
14599            -0.40760595,
14600            -1.4076059,
14601            -2.407_606,
14602        ];
14603        for (a, b) in out.iter().zip(expected.iter()) {
14604            assert!((a - b).abs() < 1e-5, "log_softmax mismatch: {a} vs {b}");
14605        }
14606        // The exp() of the output should sum to 1 per row.
14607        for row in out.chunks(3) {
14608            let sum: f32 = row.iter().map(|x| x.exp()).sum();
14609            assert!(
14610                (sum - 1.0).abs() < 1e-5,
14611                "softmax(log_softmax) row sum != 1: {sum}"
14612            );
14613        }
14614    }
14615
14616    // --- side-effect roots + destructive cleanup (9c Phase B) -----
14617
14618    /// Side-effect roots get merged into the realize walk even when
14619    /// not reachable from the user's targets. The production trigger
14620    /// is `Op::Release` (emitted by `ResidencyEvictionRule`); this
14621    /// test uses that exact shape.
14622    ///
14623    /// Graph: Const(a) + Const(b) → Add (user target); separate
14624    /// Const(c) → Release(c) (side-effect root, not reachable from
14625    /// Add). After realize_many on `[add]`, the Add should be in the
14626    /// output AND the Release should have fired (verified by the
14627    /// fact that realize succeeded — Op::Release in the walk used to
14628    /// fail compilation pre-Phase B+).
14629    #[test]
14630    fn pipelined_realize_merges_op_release_side_effect_root() {
14631        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
14632        let b = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
14633        let c = fuel_memory::from_slice_cpu(&[100.0_f32, 200.0]);
14634        let graph = Arc::new(RwLock::new(Graph::new()));
14635        let (a_id, b_id, c_id, add_id, release_id) = {
14636            let mut g = graph.write().unwrap();
14637            let a = g.push(Node {
14638                op: Op::Const,
14639                inputs: vec![],
14640                shape: Shape::from_dims(&[2]),
14641                dtype: DType::F32,
14642            });
14643            let b = g.push(Node {
14644                op: Op::Const,
14645                inputs: vec![],
14646                shape: Shape::from_dims(&[2]),
14647                dtype: DType::F32,
14648            });
14649            // c is NOT reachable from add; its Release IS marked as
14650            // a side-effect root.
14651            let c = g.push(Node {
14652                op: Op::Const,
14653                inputs: vec![],
14654                shape: Shape::from_dims(&[2]),
14655                dtype: DType::F32,
14656            });
14657            let add = g.push(Node {
14658                op: Op::Add,
14659                inputs: vec![a, b],
14660                shape: Shape::from_dims(&[2]),
14661                dtype: DType::F32,
14662            });
14663            // Production shape: Op::Release on c, marked as
14664            // side-effect root so it fires even though no graph
14665            // node reads its output.
14666            let release = g.push(Node {
14667                op: Op::Release,
14668                inputs: vec![c],
14669                shape: Shape::from_dims(&[0]),
14670                dtype: DType::F32,
14671            });
14672            g.set_target_backend(add, BackendId::Cpu);
14673            g.set_target_backend(release, BackendId::Cpu);
14674            g.add_side_effect_root(release);
14675            (a, b, c, add, release)
14676        };
14677        let mut inputs = StorageCache::new();
14678        inputs.insert(a_id, Arc::new(RwLock::new(a)));
14679        inputs.insert(b_id, Arc::new(RwLock::new(b)));
14680        let c_arc = Arc::new(RwLock::new(c));
14681        let c_arc_external = Arc::clone(&c_arc);
14682        inputs.insert(c_id, c_arc);
14683
14684        // Only `add` is requested. The Release on c is a side-effect
14685        // root that must still fire.
14686        let out = PipelinedExecutor::realize_many(graph, &[add_id], inputs).expect("realize_many");
14687        assert_eq!(out.len(), 1);
14688        let add_guard = out[0].0.read().unwrap();
14689        let fuel_memory::BackendStorage::Cpu(arr) = &add_guard.inner else {
14690            panic!()
14691        };
14692        assert_eq!(arr.as_slice::<f32>().unwrap(), &[11.0, 22.0]);
14693
14694        // The Release's destructive_input cleanup dropped the
14695        // cache's Arc to c. The only Arc to c that survives is the
14696        // external one this test holds — confirms the eviction
14697        // actually freed the cache's reference.
14698        assert_eq!(
14699            Arc::strong_count(&c_arc_external),
14700            1,
14701            "Op::Release should evict the cache's Arc to its source; \
14702             only the test's external clone should remain",
14703        );
14704        let _ = release_id;
14705    }
14706
14707    /// `compile_one` emits a `WorkItemKind::ReleaseMarker` for
14708    /// `Op::Release` with `destructive_input = Some(0)`. Verify
14709    /// the WorkItem shape via a direct compile_one call.
14710    #[test]
14711    fn compile_one_emits_release_marker_with_destructive_input() {
14712        let graph_rc = Arc::new(RwLock::new(Graph::new()));
14713        let (src_id, release_id) = {
14714            let mut g = graph_rc.write().unwrap();
14715            let src = g.push(Node {
14716                op: Op::Const,
14717                inputs: vec![],
14718                shape: Shape::from_dims(&[2]),
14719                dtype: DType::F32,
14720            });
14721            let release = g.push(Node {
14722                op: Op::Release,
14723                inputs: vec![src],
14724                shape: Shape::from_dims(&[0]),
14725                dtype: DType::F32,
14726            });
14727            g.set_target_backend(release, BackendId::Cpu);
14728            (src, release)
14729        };
14730        let g = graph_rc.read().unwrap();
14731        let bindings = crate::dispatch::global_bindings();
14732        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
14733        let item = compile_one(
14734            &g,
14735            release_id,
14736            &mut layout_cache,
14737            &bindings,
14738            &SymEnv::default(),
14739        )
14740        .expect("compile_one Op::Release");
14741        assert!(matches!(item.kind, WorkItemKind::ReleaseMarker));
14742        assert_eq!(item.destructive_input, Some(0));
14743        assert_eq!(item.inputs, vec![src_id]);
14744        assert_eq!(
14745            item.elem_count, 0,
14746            "Release output is the zero-element marker"
14747        );
14748    }
14749
14750    // --- Op::Move (executor-unification Session 1, gap 13) --------
14751
14752    /// `compile_one` emits a `WorkItemKind::Move` for `Op::Move` with
14753    /// `destructive_input = Some(0)` and a resolved transfer kernel
14754    /// (binding-table lookup at `(OpKind::Copy, [dt, dt], source
14755    /// backend)` — Move shares Op::Copy's data-movement kernel).
14756    #[test]
14757    fn compile_one_emits_move_with_destructive_input() {
14758        let graph_rc = Arc::new(RwLock::new(Graph::new()));
14759        let (src_id, move_id) = {
14760            let mut g = graph_rc.write().unwrap();
14761            let src = g.push(Node {
14762                op: Op::Const,
14763                inputs: vec![],
14764                shape: Shape::from_dims(&[2]),
14765                dtype: DType::F32,
14766            });
14767            let mv = g.push(Node {
14768                op: Op::Move {
14769                    target: DeviceLocation::Cpu,
14770                },
14771                inputs: vec![src],
14772                shape: Shape::from_dims(&[2]),
14773                dtype: DType::F32,
14774            });
14775            g.set_target_backend(mv, BackendId::Cpu);
14776            (src, mv)
14777        };
14778        let g = graph_rc.read().unwrap();
14779        let bindings = crate::dispatch::global_bindings();
14780        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
14781        let item = compile_one(
14782            &g,
14783            move_id,
14784            &mut layout_cache,
14785            &bindings,
14786            &SymEnv::default(),
14787        )
14788        .expect("compile_one Op::Move");
14789        assert!(matches!(
14790            item.kind,
14791            WorkItemKind::Move {
14792                target_location: DeviceLocation::Cpu
14793            },
14794        ));
14795        assert_eq!(item.destructive_input, Some(0), "Move destroys its source");
14796        assert_eq!(item.inputs, vec![src_id]);
14797        assert!(
14798            item.compiled.is_some(),
14799            "Move resolves a transfer kernel at (OpKind::Copy, [dt, dt], source backend)",
14800        );
14801    }
14802
14803    // --- runtime fused op (JIT-adopted Tier-2 kernel) --------------
14804
14805    /// `compile_one` resolves an `Op::Fused(fid, Runtime)` node with
14806    /// `fid.is_runtime()` from the runtime-kernel sidecar (never the
14807    /// binding table): `WorkItemKind::Kernel`, `compiled.op ==
14808    /// OpKind::RuntimeFused`, and the kernel pointer is exactly the one
14809    /// `adopt_runtime_fused` bound.
14810    #[test]
14811    fn compile_one_resolves_runtime_fused_from_the_sidecar() {
14812        fn sentinel_kernel(
14813            _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
14814            _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
14815            _layouts: &[Layout],
14816            _params: &crate::kernel::OpParams,
14817        ) -> Result<()> {
14818            Ok(())
14819        }
14820        // A region shape unique to this test (process-global sidecar; see
14821        // runtime_fused_pathfinder's tests for the collision rationale).
14822        let region = fuel_graph::jit::PatternNode::Op {
14823            op: fuel_graph::jit::OpTag::Exp,
14824            attrs: fuel_graph::jit::OpAttrs::default(),
14825            operands: vec![fuel_graph::jit::PatternNode::Op {
14826                op: fuel_graph::jit::OpTag::Sub,
14827                attrs: fuel_graph::jit::OpAttrs::default(),
14828                operands: vec![
14829                    fuel_graph::jit::PatternNode::Bind { index: 0 },
14830                    fuel_graph::jit::PatternNode::Bind { index: 1 },
14831                ],
14832            }],
14833        };
14834        let rid = crate::runtime_fused_kernels::adopt_runtime_fused(
14835            "test::compile_one::exp_sub",
14836            region,
14837            sentinel_kernel as crate::kernel::KernelRef,
14838            vec![DType::F32, DType::F32, DType::F32],
14839            BackendId::Cpu,
14840        )
14841        .expect("registrable region");
14842
14843        let graph_rc = Arc::new(RwLock::new(Graph::new()));
14844        let fused_id = {
14845            let mut g = graph_rc.write().unwrap();
14846            let s = Shape::from_dims(&[4]);
14847            let a = g.push(Node {
14848                op: Op::Const,
14849                inputs: vec![],
14850                shape: s.clone(),
14851                dtype: DType::F32,
14852            });
14853            let b = g.push(Node {
14854                op: Op::Const,
14855                inputs: vec![],
14856                shape: s.clone(),
14857                dtype: DType::F32,
14858            });
14859            let fused = g.push(Node {
14860                op: Op::Fused(
14861                    rid,
14862                    fuel_graph::registry::FusedOpParams::Runtime {
14863                        scalars: Vec::new(),
14864                    },
14865                ),
14866                inputs: vec![a, b],
14867                shape: s,
14868                dtype: DType::F32,
14869            });
14870            // The arm emitter pins the backend; mirror that here.
14871            g.set_target_backend(fused, BackendId::Cpu);
14872            fused
14873        };
14874        let g = graph_rc.read().unwrap();
14875        let bindings = crate::dispatch::global_bindings();
14876        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
14877        let item = compile_one(
14878            &g,
14879            fused_id,
14880            &mut layout_cache,
14881            &bindings,
14882            &SymEnv::default(),
14883        )
14884        .expect("compile_one runtime fused op");
14885        assert!(matches!(item.kind, WorkItemKind::Kernel));
14886        let compiled = item.compiled.expect("resolved a kernel");
14887        assert_eq!(compiled.op, fuel_ir::dispatch::OpKind::RuntimeFused);
14888        assert_eq!(compiled.backend, BackendId::Cpu);
14889        assert!(
14890            std::ptr::fn_addr_eq(compiled.kernel, sentinel_kernel as crate::kernel::KernelRef),
14891            "the kernel pointer is exactly the adopted one",
14892        );
14893        assert!(
14894            layout_cache.contains_key(&fused_id),
14895            "output layout cached for consumers"
14896        );
14897    }
14898
14899    /// The dtype belt-and-suspenders guard: an `Op::Fused(runtime)` node
14900    /// whose per-operand dtypes disagree with the adopted kernel's tuple is
14901    /// a typed error, not a silent wrong-kernel dispatch.
14902    #[test]
14903    fn compile_one_rejects_runtime_fused_dtype_mismatch() {
14904        fn noop_kernel(
14905            _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
14906            _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
14907            _layouts: &[Layout],
14908            _params: &crate::kernel::OpParams,
14909        ) -> Result<()> {
14910            Ok(())
14911        }
14912        let region = fuel_graph::jit::PatternNode::Op {
14913            op: fuel_graph::jit::OpTag::Log,
14914            attrs: fuel_graph::jit::OpAttrs::default(),
14915            operands: vec![fuel_graph::jit::PatternNode::Op {
14916                op: fuel_graph::jit::OpTag::Maximum,
14917                attrs: fuel_graph::jit::OpAttrs::default(),
14918                operands: vec![
14919                    fuel_graph::jit::PatternNode::Bind { index: 0 },
14920                    fuel_graph::jit::PatternNode::Bind { index: 1 },
14921                ],
14922            }],
14923        };
14924        // Adopted for F32 operands…
14925        let rid = crate::runtime_fused_kernels::adopt_runtime_fused(
14926            "test::compile_one::log_maximum",
14927            region,
14928            noop_kernel as crate::kernel::KernelRef,
14929            vec![DType::F32, DType::F32, DType::F32],
14930            BackendId::Cpu,
14931        )
14932        .expect("registrable region");
14933
14934        let graph_rc = Arc::new(RwLock::new(Graph::new()));
14935        let fused_id = {
14936            let mut g = graph_rc.write().unwrap();
14937            let s = Shape::from_dims(&[4]);
14938            // …but the node's operands are F64.
14939            let a = g.push(Node {
14940                op: Op::Const,
14941                inputs: vec![],
14942                shape: s.clone(),
14943                dtype: DType::F64,
14944            });
14945            let b = g.push(Node {
14946                op: Op::Const,
14947                inputs: vec![],
14948                shape: s.clone(),
14949                dtype: DType::F64,
14950            });
14951            let fused = g.push(Node {
14952                op: Op::Fused(
14953                    rid,
14954                    fuel_graph::registry::FusedOpParams::Runtime {
14955                        scalars: Vec::new(),
14956                    },
14957                ),
14958                inputs: vec![a, b],
14959                shape: s,
14960                dtype: DType::F64,
14961            });
14962            g.set_target_backend(fused, BackendId::Cpu);
14963            fused
14964        };
14965        let g = graph_rc.read().unwrap();
14966        let bindings = crate::dispatch::global_bindings();
14967        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
14968        let err = match compile_one(
14969            &g,
14970            fused_id,
14971            &mut layout_cache,
14972            &bindings,
14973            &SymEnv::default(),
14974        ) {
14975            Ok(_) => panic!("dtype mismatch must be a typed error"),
14976            Err(e) => e,
14977        };
14978        // Post-fold, the dtype tuple IS the binding key: a mismatch is the
14979        // same honest `NoBackendForOp` miss as an absent kernel — reported
14980        // with the `RuntimeFused` diagnostic op tag, never a wrong-kernel bind.
14981        assert!(
14982            matches!(
14983                err,
14984                fuel_ir::Error::NoBackendForOp {
14985                    op: fuel_ir::dispatch::OpKind::RuntimeFused,
14986                    ..
14987                }
14988            ),
14989            "a dtype mismatch is an honest binding miss: {err}",
14990        );
14991    }
14992
14993    /// A runtime fused node carrying live `Runtime { scalars }` compiles with
14994    /// `OpParams::JitScalars` — the launch channel for the kernel's trailing
14995    /// `p{i}` args. (A param-free node keeps `OpParams::None`, covered by
14996    /// `compile_one_resolves_runtime_fused_from_the_sidecar`.)
14997    #[test]
14998    fn compile_one_maps_runtime_scalars_to_jit_scalars() {
14999        fn noop_kernel(
15000            _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
15001            _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
15002            _layouts: &[Layout],
15003            _params: &crate::kernel::OpParams,
15004        ) -> Result<()> {
15005            Ok(())
15006        }
15007        // Unique slot-template region (process-global sidecar).
15008        let region = fuel_graph::jit::PatternNode::Op {
15009            op: fuel_graph::jit::OpTag::Floor,
15010            attrs: fuel_graph::jit::OpAttrs::default(),
15011            operands: vec![fuel_graph::jit::PatternNode::Op {
15012                op: fuel_graph::jit::OpTag::MulScalar,
15013                attrs: fuel_graph::jit::OpAttrs::default(), // open slot
15014                operands: vec![fuel_graph::jit::PatternNode::Bind { index: 0 }],
15015            }],
15016        };
15017        let rid = crate::runtime_fused_kernels::adopt_runtime_fused(
15018            "test::compile_one::floor_mul_scalar",
15019            region,
15020            noop_kernel as crate::kernel::KernelRef,
15021            vec![DType::F32, DType::F32],
15022            BackendId::Cpu,
15023        )
15024        .expect("slot template registrable");
15025
15026        let graph_rc = Arc::new(RwLock::new(Graph::new()));
15027        let fused_id = {
15028            let mut g = graph_rc.write().unwrap();
15029            let s = Shape::from_dims(&[4]);
15030            let x = g.push(Node {
15031                op: Op::Const,
15032                inputs: vec![],
15033                shape: s.clone(),
15034                dtype: DType::F32,
15035            });
15036            let fused = g.push(Node {
15037                op: Op::Fused(
15038                    rid,
15039                    fuel_graph::registry::FusedOpParams::Runtime {
15040                        scalars: vec![3.5, -1.25],
15041                    },
15042                ),
15043                inputs: vec![x],
15044                shape: s,
15045                dtype: DType::F32,
15046            });
15047            g.set_target_backend(fused, BackendId::Cpu);
15048            fused
15049        };
15050        let g = graph_rc.read().unwrap();
15051        let bindings = crate::dispatch::global_bindings();
15052        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
15053        let item = compile_one(
15054            &g,
15055            fused_id,
15056            &mut layout_cache,
15057            &bindings,
15058            &SymEnv::default(),
15059        )
15060        .expect("compile_one runtime fused op with scalars");
15061        let compiled = item.compiled.expect("resolved a kernel");
15062        assert!(
15063            matches!(
15064                &compiled.op_params,
15065                crate::kernel::OpParams::JitScalars { scalars } if scalars == &vec![3.5, -1.25]
15066            ),
15067            "Runtime scalars ride into OpParams::JitScalars, got {:?}",
15068            compiled.op_params,
15069        );
15070    }
15071
15072    /// Move-to-same-device is the degenerate case: per the legacy
15073    /// `GraphExecutor` contract (`Op::Copy | Op::Move` shared arm →
15074    /// `backend.copy_to`) it is a plain copy — fresh storage on the
15075    /// same device, data intact — and the source is still evicted
15076    /// afterward (destructive semantics don't depend on the devices
15077    /// differing).
15078    #[test]
15079    fn pipelined_op_move_same_device_is_plain_copy() {
15080        let src = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
15081        let graph = Arc::new(RwLock::new(Graph::new()));
15082        let (src_id, move_id) = {
15083            let mut g = graph.write().unwrap();
15084            let src = g.push(Node {
15085                op: Op::Const,
15086                inputs: vec![],
15087                shape: Shape::from_dims(&[4]),
15088                dtype: DType::F32,
15089            });
15090            let mv = g.push(Node {
15091                op: Op::Move {
15092                    target: DeviceLocation::Cpu,
15093                },
15094                inputs: vec![src],
15095                shape: Shape::from_dims(&[4]),
15096                dtype: DType::F32,
15097            });
15098            g.set_target_backend(mv, BackendId::Cpu);
15099            (src, mv)
15100        };
15101        let src_arc = Arc::new(RwLock::new(src));
15102        let src_arc_external = Arc::clone(&src_arc);
15103        let mut inputs = StorageCache::new();
15104        inputs.insert(src_id, src_arc);
15105
15106        let (out, layout) =
15107            PipelinedExecutor::realize(graph, move_id, inputs).expect("realize Op::Move");
15108        let guard = out.read().unwrap();
15109        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15110            panic!()
15111        };
15112        assert_eq!(
15113            c.as_slice::<f32>().unwrap(),
15114            &[1.0, 2.0, 3.0, 4.0],
15115            "Op::Move output should carry input's data to target",
15116        );
15117        assert!(layout.is_contiguous());
15118        drop(guard);
15119        assert!(
15120            !Arc::ptr_eq(&out, &src_arc_external),
15121            "same-device Move is a plain copy — fresh storage, not an alias",
15122        );
15123        // The realize loop's destructive_input cleanup dropped the
15124        // cache's Arc to the source; only the test's external clone
15125        // survives.
15126        assert_eq!(
15127            Arc::strong_count(&src_arc_external),
15128            1,
15129            "Op::Move should evict the cache's Arc to its source",
15130        );
15131    }
15132
15133    /// The multiple-consumer-source case: a Move must NOT strand
15134    /// another consumer of its source. `execution_plan` (via
15135    /// `derive_ordering`, keyed off `destructive_input`) pins the
15136    /// Move AFTER the sibling reader; the executor's post-Move cache
15137    /// eviction then can't break the reader. Mirrors the legacy
15138    /// `op_move_pinned_after_sibling_reader_via_derive_ordering`
15139    /// test in fuel-graph-router/tests/cross_device.rs.
15140    ///
15141    ///   a   = const [1, 2, 3, 4]
15142    ///   b   = relu(a)        (non-destructive sibling reader)
15143    ///   m   = move(a, Cpu)   (destructive — evicts a once run)
15144    ///   out = add(b, m)      → [2, 4, 6, 8]
15145    #[test]
15146    fn pipelined_op_move_multi_consumer_source_not_stranded() {
15147        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
15148        let graph = Arc::new(RwLock::new(Graph::new()));
15149        let (a_id, out_id) = {
15150            let mut g = graph.write().unwrap();
15151            let a = g.push(Node {
15152                op: Op::Const,
15153                inputs: vec![],
15154                shape: Shape::from_dims(&[4]),
15155                dtype: DType::F32,
15156            });
15157            let b = g.push(Node {
15158                op: Op::Relu,
15159                inputs: vec![a],
15160                shape: Shape::from_dims(&[4]),
15161                dtype: DType::F32,
15162            });
15163            let m = g.push(Node {
15164                op: Op::Move {
15165                    target: DeviceLocation::Cpu,
15166                },
15167                inputs: vec![a],
15168                shape: Shape::from_dims(&[4]),
15169                dtype: DType::F32,
15170            });
15171            let out = g.push(Node {
15172                op: Op::Add,
15173                inputs: vec![b, m],
15174                shape: Shape::from_dims(&[4]),
15175                dtype: DType::F32,
15176            });
15177            g.set_target_backend(b, BackendId::Cpu);
15178            g.set_target_backend(m, BackendId::Cpu);
15179            g.set_target_backend(out, BackendId::Cpu);
15180            (a, out)
15181        };
15182        let mut inputs = StorageCache::new();
15183        inputs.insert(a_id, Arc::new(RwLock::new(a)));
15184
15185        let (out, _) = PipelinedExecutor::realize(graph, out_id, inputs)
15186            .expect("realize add(relu(a), move(a))");
15187        let guard = out.read().unwrap();
15188        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15189            panic!()
15190        };
15191        assert_eq!(
15192            c.as_slice::<f32>().unwrap(),
15193            &[2.0, 4.0, 6.0, 8.0],
15194            "relu(a) must run before move(a) evicts a",
15195        );
15196    }
15197
15198    /// A Move whose source is itself in the realize target set must
15199    /// not evict it — the caller asked for the source's storage. The
15200    /// destructive cleanup's `target_set` gate covers Move exactly
15201    /// like Release.
15202    #[test]
15203    fn pipelined_op_move_source_in_target_set_not_evicted() {
15204        let a = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0]);
15205        let graph = Arc::new(RwLock::new(Graph::new()));
15206        let (a_id, move_id) = {
15207            let mut g = graph.write().unwrap();
15208            let a = g.push(Node {
15209                op: Op::Const,
15210                inputs: vec![],
15211                shape: Shape::from_dims(&[2]),
15212                dtype: DType::F32,
15213            });
15214            let mv = g.push(Node {
15215                op: Op::Move {
15216                    target: DeviceLocation::Cpu,
15217                },
15218                inputs: vec![a],
15219                shape: Shape::from_dims(&[2]),
15220                dtype: DType::F32,
15221            });
15222            g.set_target_backend(mv, BackendId::Cpu);
15223            (a, mv)
15224        };
15225        let a_arc = Arc::new(RwLock::new(a));
15226        let a_arc_external = Arc::clone(&a_arc);
15227        let mut inputs = StorageCache::new();
15228        inputs.insert(a_id, a_arc);
15229
15230        let out = PipelinedExecutor::realize_many(graph, &[move_id, a_id], inputs)
15231            .expect("realize_many [move, source]");
15232        assert_eq!(out.len(), 2);
15233        let mv_guard = out[0].0.read().unwrap();
15234        let fuel_memory::BackendStorage::Cpu(c) = &mv_guard.inner else {
15235            panic!()
15236        };
15237        assert_eq!(c.as_slice::<f32>().unwrap(), &[5.0, 6.0]);
15238        assert!(
15239            Arc::ptr_eq(&out[1].0, &a_arc_external),
15240            "requested source must survive the Move's destructive cleanup",
15241        );
15242    }
15243
15244    // --- realize_many (Phase 7.6 step 9c Phase A) ----------------
15245
15246    /// realize_many on empty targets returns an empty Vec — no graph
15247    /// walk, no panic.
15248    #[test]
15249    fn pipelined_realize_many_empty_targets() {
15250        let graph = Arc::new(RwLock::new(Graph::new()));
15251        let inputs = StorageCache::new();
15252        let out = PipelinedExecutor::realize_many(graph, &[], inputs).expect("realize_many");
15253        assert!(out.is_empty());
15254    }
15255
15256    /// realize_many with two independent target chains. Each chain's
15257    /// output is in the cache; the shared topo walk realizes both.
15258    /// Verifies parallel chain handling + return order matches input.
15259    #[test]
15260    fn pipelined_realize_many_two_independent_targets() {
15261        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
15262        let rhs = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
15263        let graph = Arc::new(RwLock::new(Graph::new()));
15264        let (lhs_id, rhs_id, add_id, mul_id) = {
15265            let mut g = graph.write().unwrap();
15266            let lhs = g.push(Node {
15267                op: Op::Const,
15268                inputs: vec![],
15269                shape: Shape::from_dims(&[3]),
15270                dtype: DType::F32,
15271            });
15272            let rhs = g.push(Node {
15273                op: Op::Const,
15274                inputs: vec![],
15275                shape: Shape::from_dims(&[3]),
15276                dtype: DType::F32,
15277            });
15278            let add = g.push(Node {
15279                op: Op::Add,
15280                inputs: vec![lhs, rhs],
15281                shape: Shape::from_dims(&[3]),
15282                dtype: DType::F32,
15283            });
15284            let mul = g.push(Node {
15285                op: Op::Mul,
15286                inputs: vec![lhs, rhs],
15287                shape: Shape::from_dims(&[3]),
15288                dtype: DType::F32,
15289            });
15290            g.set_target_backend(add, BackendId::Cpu);
15291            g.set_target_backend(mul, BackendId::Cpu);
15292            (lhs, rhs, add, mul)
15293        };
15294        let mut inputs = StorageCache::new();
15295        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs)));
15296        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs)));
15297
15298        // Pass mul first to confirm return order matches targets order
15299        // (not graph order — graph order would put add first).
15300        let out = PipelinedExecutor::realize_many(graph, &[mul_id, add_id], inputs)
15301            .expect("realize_many");
15302        assert_eq!(out.len(), 2);
15303
15304        let mul_guard = out[0].0.read().unwrap();
15305        let fuel_memory::BackendStorage::Cpu(c) = &mul_guard.inner else {
15306            panic!()
15307        };
15308        assert_eq!(c.as_slice::<f32>().unwrap(), &[10.0, 40.0, 90.0]);
15309
15310        let add_guard = out[1].0.read().unwrap();
15311        let fuel_memory::BackendStorage::Cpu(c) = &add_guard.inner else {
15312            panic!()
15313        };
15314        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 22.0, 33.0]);
15315    }
15316
15317    /// realize_many with the same NodeId twice — caller asking for
15318    /// the same output twice. Both outputs are the same Arc (cheap).
15319    #[test]
15320    fn pipelined_realize_many_duplicate_target_returns_same_arc() {
15321        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
15322        let graph = Arc::new(RwLock::new(Graph::new()));
15323        let (in_id, neg_id) = {
15324            let mut g = graph.write().unwrap();
15325            let in_id = g.push(Node {
15326                op: Op::Const,
15327                inputs: vec![],
15328                shape: Shape::from_dims(&[3]),
15329                dtype: DType::F32,
15330            });
15331            let neg = g.push(Node {
15332                op: Op::Neg,
15333                inputs: vec![in_id],
15334                shape: Shape::from_dims(&[3]),
15335                dtype: DType::F32,
15336            });
15337            g.set_target_backend(neg, BackendId::Cpu);
15338            (in_id, neg)
15339        };
15340        let mut inputs = StorageCache::new();
15341        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
15342
15343        let out = PipelinedExecutor::realize_many(graph, &[neg_id, neg_id], inputs)
15344            .expect("realize_many");
15345        assert_eq!(out.len(), 2);
15346        assert!(
15347            Arc::ptr_eq(&out[0].0, &out[1].0),
15348            "duplicate target should share the same storage Arc",
15349        );
15350    }
15351
15352    /// realize_many with shared upstream nodes evaluates the shared
15353    /// chunk exactly once. Two targets `f = a + b` and `g = (a + b) * a`
15354    /// — `a + b` is computed once.
15355    #[test]
15356    fn pipelined_realize_many_shared_subgraph_evaluates_once() {
15357        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
15358        let b_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
15359        let graph = Arc::new(RwLock::new(Graph::new()));
15360        let (a_id, b_id, add_id, mul_id) = {
15361            let mut g = graph.write().unwrap();
15362            let a = g.push(Node {
15363                op: Op::Const,
15364                inputs: vec![],
15365                shape: Shape::from_dims(&[3]),
15366                dtype: DType::F32,
15367            });
15368            let b = g.push(Node {
15369                op: Op::Const,
15370                inputs: vec![],
15371                shape: Shape::from_dims(&[3]),
15372                dtype: DType::F32,
15373            });
15374            let add = g.push(Node {
15375                op: Op::Add,
15376                inputs: vec![a, b],
15377                shape: Shape::from_dims(&[3]),
15378                dtype: DType::F32,
15379            });
15380            let mul = g.push(Node {
15381                op: Op::Mul,
15382                inputs: vec![add, a],
15383                shape: Shape::from_dims(&[3]),
15384                dtype: DType::F32,
15385            });
15386            g.set_target_backend(add, BackendId::Cpu);
15387            g.set_target_backend(mul, BackendId::Cpu);
15388            (a, b, add, mul)
15389        };
15390        let mut inputs = StorageCache::new();
15391        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
15392        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
15393
15394        let out = PipelinedExecutor::realize_many(graph, &[add_id, mul_id], inputs)
15395            .expect("realize_many");
15396        assert_eq!(out.len(), 2);
15397
15398        let add_guard = out[0].0.read().unwrap();
15399        let fuel_memory::BackendStorage::Cpu(c) = &add_guard.inner else {
15400            panic!()
15401        };
15402        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 22.0, 33.0]);
15403
15404        let mul_guard = out[1].0.read().unwrap();
15405        let fuel_memory::BackendStorage::Cpu(c) = &mul_guard.inner else {
15406            panic!()
15407        };
15408        // (a + b) * a = [11*1, 22*2, 33*3] = [11, 44, 99].
15409        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 44.0, 99.0]);
15410    }
15411
15412    /// E2E: masked_fill with -inf — the attention masking pattern.
15413    /// x = [1, 2, 3, 4]; mask = [0, 1, 0, 1]; value = -1000.
15414    /// out = [1, -1000, 3, -1000].
15415    #[test]
15416    fn pipelined_realize_masked_fill_attention_pattern() {
15417        let x_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
15418        let mut mask_storage = fuel_memory::from_slice_cpu(&[0u8, 1, 0, 1]);
15419        mask_storage.dtype = DType::Bool; // GAP-168(c): a Bool mask, not U8 bytes
15420        let graph = Arc::new(RwLock::new(Graph::new()));
15421        let (x_id, mask_id, out_id) = {
15422            let mut g = graph.write().unwrap();
15423            let x = g.push(Node {
15424                op: Op::Const,
15425                inputs: vec![],
15426                shape: Shape::from_dims(&[4]),
15427                dtype: DType::F32,
15428            });
15429            let mask = g.push(Node {
15430                op: Op::Const,
15431                inputs: vec![],
15432                shape: Shape::from_dims(&[4]),
15433                dtype: DType::Bool,
15434            });
15435            let out = g.push(Node {
15436                op: Op::MaskedFill {
15437                    value: fuel_ir::Scalar::F32(-1000.0),
15438                },
15439                inputs: vec![x, mask],
15440                shape: Shape::from_dims(&[4]),
15441                dtype: DType::F32,
15442            });
15443            g.set_target_backend(out, BackendId::Cpu);
15444            (x, mask, out)
15445        };
15446        let mut inputs = StorageCache::new();
15447        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
15448        inputs.insert(mask_id, Arc::new(RwLock::new(mask_storage)));
15449        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
15450        let guard = result_arc.read().unwrap();
15451        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15452            panic!("expected Cpu storage");
15453        };
15454        let out: &[f32] = c.as_slice().unwrap();
15455        assert_eq!(out, &[1.0, -1000.0, 3.0, -1000.0]);
15456    }
15457
15458    // ---- WriteSlice (Phase 7.6 step 9c E.3.2) -------------------------------
15459
15460    /// E2E: pipelined realize of `Op::WriteSlice` writing a [1, 3, 2]
15461    /// source slab into a [4, 3, 2] destination at axis-0 row 2 — the
15462    /// canonical KV-cache append shape.
15463    #[test]
15464    fn pipelined_realize_write_slice_kv_cache_append() {
15465        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 24]);
15466        let src_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
15467        let graph = Arc::new(RwLock::new(Graph::new()));
15468        let (dest_id, src_id, ws_id) = {
15469            let mut g = graph.write().unwrap();
15470            let dest = g.push(Node {
15471                op: Op::Const,
15472                inputs: vec![],
15473                shape: Shape::from_dims(&[4, 3, 2]),
15474                dtype: DType::F32,
15475            });
15476            let src = g.push(Node {
15477                op: Op::Const,
15478                inputs: vec![],
15479                shape: Shape::from_dims(&[1, 3, 2]),
15480                dtype: DType::F32,
15481            });
15482            let ws = g.push(Node {
15483                op: Op::WriteSlice {
15484                    ranges: vec![(2, 3), (0, 3), (0, 2)],
15485                    dyn_offset: None,
15486                },
15487                inputs: vec![dest, src],
15488                shape: Shape::from_dims(&[4, 3, 2]), // adopts dest shape
15489                dtype: DType::F32,
15490            });
15491            g.set_target_backend(ws, BackendId::Cpu);
15492            (dest, src, ws)
15493        };
15494        let mut inputs = StorageCache::new();
15495        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
15496        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
15497        let (result_arc, _) = PipelinedExecutor::realize(graph, ws_id, inputs).expect("realize");
15498        let guard = result_arc.read().unwrap();
15499        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15500            panic!("expected Cpu storage");
15501        };
15502        let out: &[f32] = c.as_slice().unwrap();
15503        let expected = [
15504            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,
15505            6.0, // row 2 = source
15506            0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
15507        ];
15508        assert_eq!(out, &expected);
15509    }
15510
15511    /// E2E: pipelined realize of `Op::WriteSlice` adopts the
15512    /// destination's Storage Arc as the output slot (in-place
15513    /// alias) — the resulting Arc points to the SAME bytes the
15514    /// destination was constructed from.
15515    #[test]
15516    fn pipelined_realize_write_slice_aliases_dest_storage() {
15517        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
15518        let src_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
15519        let graph = Arc::new(RwLock::new(Graph::new()));
15520        let (dest_id, src_id, ws_id, dest_arc_external) = {
15521            let mut g = graph.write().unwrap();
15522            let dest = g.push(Node {
15523                op: Op::Const,
15524                inputs: vec![],
15525                shape: Shape::from_dims(&[3, 2]),
15526                dtype: DType::F32,
15527            });
15528            let src = g.push(Node {
15529                op: Op::Const,
15530                inputs: vec![],
15531                shape: Shape::from_dims(&[1, 2]),
15532                dtype: DType::F32,
15533            });
15534            let ws = g.push(Node {
15535                op: Op::WriteSlice {
15536                    ranges: vec![(1, 2), (0, 2)],
15537                    dyn_offset: None,
15538                },
15539                inputs: vec![dest, src],
15540                shape: Shape::from_dims(&[3, 2]),
15541                dtype: DType::F32,
15542            });
15543            g.set_target_backend(ws, BackendId::Cpu);
15544            let arc = Arc::new(RwLock::new(dest_storage));
15545            (dest, src, ws, arc)
15546        };
15547        let mut inputs = StorageCache::new();
15548        inputs.insert(dest_id, Arc::clone(&dest_arc_external));
15549        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
15550        let (result_arc, _) = PipelinedExecutor::realize(graph, ws_id, inputs).expect("realize");
15551        // Bytes were written into the same Arc the caller held —
15552        // the WriteSlice op aliases dest's Storage Arc, not allocates
15553        // a fresh buffer.
15554        assert!(
15555            Arc::ptr_eq(&result_arc, &dest_arc_external),
15556            "WriteSlice output Arc must be the same Arc as the destination's"
15557        );
15558        let guard = dest_arc_external.read().unwrap();
15559        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15560            panic!("expected Cpu storage");
15561        };
15562        let out: &[f32] = c.as_slice().unwrap();
15563        assert_eq!(out, &[0.0, 0.0, 10.0, 20.0, 0.0, 0.0]);
15564    }
15565
15566    // ---- WriteSlice dynamic offset (Phase D symbolic extents) ---------------
15567
15568    /// E2E: pipelined realize of `Op::WriteSlice` with a runtime start
15569    /// offset (`dyn_offset`) resolved through a per-pass `SymEnv`. The
15570    /// width-2 source slab lands at the bound offset (3), not the static
15571    /// `ranges[0].0` placeholder (0) — the persistent-decode KV-cache
15572    /// write at a per-token `cached_len`.
15573    #[test]
15574    fn pipelined_realize_write_slice_dynamic_offset() {
15575        use fuel_ir::{DynScalar, SymId};
15576        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
15577        let src_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0]);
15578        let graph = Arc::new(RwLock::new(Graph::new()));
15579        let sym = SymId(0);
15580        let (dest_id, src_id, ws_id) = {
15581            let mut g = graph.write().unwrap();
15582            let dest = g.push(Node {
15583                op: Op::Const,
15584                inputs: vec![],
15585                shape: Shape::from_dims(&[6]),
15586                dtype: DType::F32,
15587            });
15588            let src = g.push(Node {
15589                op: Op::Const,
15590                inputs: vec![],
15591                shape: Shape::from_dims(&[2]),
15592                dtype: DType::F32,
15593            });
15594            let ws = g.push(Node {
15595                // ranges[0] = (0, 2): the start is a placeholder (ignored —
15596                // overridden by dyn_offset); only the width (2) is read.
15597                op: Op::WriteSlice {
15598                    ranges: vec![(0, 2)],
15599                    dyn_offset: Some((0, DynScalar::Sym(sym))),
15600                },
15601                inputs: vec![dest, src],
15602                shape: Shape::from_dims(&[6]),
15603                dtype: DType::F32,
15604            });
15605            g.set_target_backend(ws, BackendId::Cpu);
15606            (dest, src, ws)
15607        };
15608        let mut inputs = StorageCache::new();
15609        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
15610        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
15611
15612        // Bind cached_len = 3: the slab must land at indices [3, 4].
15613        let mut env = SymEnv::new();
15614        env.bind(sym, 3).unwrap();
15615
15616        let (result_arc, _) = PipelinedExecutor::realize_with_env(graph, ws_id, inputs, env)
15617            .expect("realize_with_env");
15618        let guard = result_arc.read().unwrap();
15619        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15620            panic!("expected Cpu storage");
15621        };
15622        let out: &[f32] = c.as_slice().unwrap();
15623        assert_eq!(
15624            out,
15625            &[0.0, 0.0, 0.0, 7.0, 8.0, 0.0],
15626            "slab must land at the SymEnv-bound offset 3, not the static placeholder 0",
15627        );
15628    }
15629
15630    /// Increment 2a — the data-determined bind seam. After
15631    /// `Op::NonZeroIndices` realizes, the executor reads its runtime count
15632    /// from bundle slot 1 and PUBLISHES it into the produced `SymEnv` under
15633    /// `count_sym`. This is the first op to bind a *data-determined* symbol
15634    /// mid-realize (all prior binds are host-known before realize) — the
15635    /// keystone capability for SSM decode / MoE sparsity / MLA KV.
15636    #[test]
15637    fn pipelined_realize_nonzero_indices_publishes_count() {
15638        use fuel_ir::SymId;
15639        use fuel_ir::storage::{OutputViewSpec, compose_bundle};
15640        // flat [0,1,0,1,1,0] → 3 nonzeros at 1,3,4; capacity 6.
15641        let x_storage = fuel_memory::from_slice_cpu(&[0.0_f32, 1.0, 0.0, 1.0, 1.0, 0.0]);
15642        let graph = Arc::new(RwLock::new(Graph::new()));
15643        let count_sym = SymId(0);
15644        let (x_id, nzi_id) = {
15645            let mut g = graph.write().unwrap();
15646            let x = g.push(Node {
15647                op: Op::Const,
15648                inputs: vec![],
15649                shape: Shape::from_dims(&[2, 3]),
15650                dtype: DType::F32,
15651            });
15652            let capacity = 6usize;
15653            let idx_shape = Shape::from_dims(&[capacity]);
15654            let cnt_shape = Shape::from_dims(&[1]);
15655            let specs = vec![
15656                OutputViewSpec {
15657                    dtype: DType::U32,
15658                    shape: idx_shape.clone(),
15659                    layout: Layout::contiguous(idx_shape.clone()),
15660                    name: Some("indices"),
15661                },
15662                OutputViewSpec {
15663                    dtype: DType::U32,
15664                    shape: cnt_shape.clone(),
15665                    layout: Layout::contiguous(cnt_shape),
15666                    name: Some("count"),
15667                },
15668            ];
15669            let (_bytes, views) = compose_bundle(&specs).unwrap();
15670            let nzi = g.push(Node {
15671                op: Op::NonZeroIndices { count_sym },
15672                inputs: vec![x],
15673                shape: idx_shape,
15674                dtype: DType::U32,
15675            });
15676            g.set_output_views(nzi, Arc::from(views.into_boxed_slice()))
15677                .unwrap();
15678            g.set_target_backend(nzi, BackendId::Cpu);
15679            (x, nzi)
15680        };
15681        let mut inputs = StorageCache::new();
15682        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
15683
15684        let (_arc, _layout, produced) =
15685            PipelinedExecutor::realize_with_env_producing(graph, nzi_id, inputs, SymEnv::new())
15686                .expect("realize_with_env_producing");
15687
15688        assert_eq!(
15689            produced.get(count_sym),
15690            Some(3),
15691            "the executor must publish the data-determined nonzero count into the SymEnv",
15692        );
15693    }
15694
15695    /// A `dyn_offset` whose symbol is unbound in the `SymEnv` surfaces a
15696    /// typed error at realize (never a panic).
15697    #[test]
15698    fn pipelined_realize_write_slice_dynamic_offset_unbound_errors() {
15699        use fuel_ir::{DynScalar, SymId};
15700        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
15701        let src_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0]);
15702        let graph = Arc::new(RwLock::new(Graph::new()));
15703        let (dest_id, src_id, ws_id) = {
15704            let mut g = graph.write().unwrap();
15705            let dest = g.push(Node {
15706                op: Op::Const,
15707                inputs: vec![],
15708                shape: Shape::from_dims(&[6]),
15709                dtype: DType::F32,
15710            });
15711            let src = g.push(Node {
15712                op: Op::Const,
15713                inputs: vec![],
15714                shape: Shape::from_dims(&[2]),
15715                dtype: DType::F32,
15716            });
15717            let ws = g.push(Node {
15718                op: Op::WriteSlice {
15719                    ranges: vec![(0, 2)],
15720                    dyn_offset: Some((0, DynScalar::Sym(SymId(0)))),
15721                },
15722                inputs: vec![dest, src],
15723                shape: Shape::from_dims(&[6]),
15724                dtype: DType::F32,
15725            });
15726            g.set_target_backend(ws, BackendId::Cpu);
15727            (dest, src, ws)
15728        };
15729        let mut inputs = StorageCache::new();
15730        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
15731        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
15732        // Empty env — the symbol is unbound.
15733        let result = PipelinedExecutor::realize_with_env(graph, ws_id, inputs, SymEnv::new());
15734        assert!(
15735            result.is_err(),
15736            "unbound dyn_offset symbol must surface a typed error, not a panic",
15737        );
15738    }
15739
15740    /// A runtime offset whose resolved slab runs past the destination
15741    /// capacity errors at realize (never an out-of-bounds write).
15742    #[test]
15743    fn pipelined_realize_write_slice_dynamic_offset_out_of_capacity_errors() {
15744        use fuel_ir::{DynScalar, SymId};
15745        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
15746        let src_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0]);
15747        let graph = Arc::new(RwLock::new(Graph::new()));
15748        let sym = SymId(0);
15749        let (dest_id, src_id, ws_id) = {
15750            let mut g = graph.write().unwrap();
15751            let dest = g.push(Node {
15752                op: Op::Const,
15753                inputs: vec![],
15754                shape: Shape::from_dims(&[6]),
15755                dtype: DType::F32,
15756            });
15757            let src = g.push(Node {
15758                op: Op::Const,
15759                inputs: vec![],
15760                shape: Shape::from_dims(&[2]),
15761                dtype: DType::F32,
15762            });
15763            let ws = g.push(Node {
15764                op: Op::WriteSlice {
15765                    ranges: vec![(0, 2)],
15766                    dyn_offset: Some((0, DynScalar::Sym(sym))),
15767                },
15768                inputs: vec![dest, src],
15769                shape: Shape::from_dims(&[6]),
15770                dtype: DType::F32,
15771            });
15772            g.set_target_backend(ws, BackendId::Cpu);
15773            (dest, src, ws)
15774        };
15775        let mut inputs = StorageCache::new();
15776        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
15777        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
15778        // offset 5 + width 2 = 7 > capacity 6.
15779        let mut env = SymEnv::new();
15780        env.bind(sym, 5).unwrap();
15781        let result = PipelinedExecutor::realize_with_env(graph, ws_id, inputs, env);
15782        assert!(
15783            result.is_err(),
15784            "resolved slab past destination capacity must surface a typed error",
15785        );
15786    }
15787
15788    /// Regression for the PipelinedExecutor ordering-integration session.
15789    ///
15790    /// Graph: `x = Const`, `step_x = Step(x)`, `y = SigmoidInplace(x)`.
15791    /// `Step` and `SigmoidInplace` are both readers of `x`; `Step` is
15792    /// non-destructive, `SigmoidInplace` mutates `x`'s storage. The
15793    /// correct semantic is for `Step` to read PRE-mutation bytes.
15794    ///
15795    /// Pre-this-session (raw `topo_order_multi`): the two are siblings
15796    /// in topo order and the tie-break is unspecified — `SigmoidInplace`
15797    /// could run first, making `step_x` see post-sigmoid bytes
15798    /// (`[1, 1, 1, 1]` because every sigmoid output is positive).
15799    ///
15800    /// Post-this-session: `execution_plan` consults `derive_ordering`,
15801    /// which pins `SigmoidInplace` AFTER every other reader of `x`.
15802    /// `step_x` deterministically sees `x` and is `[1, 0, 1, 0]`.
15803    #[test]
15804    fn pipelined_inplace_with_multiple_readers_orders_correctly() {
15805        use fuel_ir::Shape;
15806        let data = [1.0_f32, -2.0, 3.0, -4.0];
15807        let src_storage = fuel_memory::from_slice_cpu(&data);
15808
15809        let graph = Arc::new(RwLock::new(Graph::new()));
15810        let (x_id, step_id, sig_id) = {
15811            let mut g = graph.write().unwrap();
15812            let x = g.push(Node {
15813                op: Op::Const,
15814                inputs: vec![],
15815                shape: Shape::from_dims(&[4]),
15816                dtype: DType::F32,
15817            });
15818            let step = g.push(Node {
15819                op: Op::Step,
15820                inputs: vec![x],
15821                shape: Shape::from_dims(&[4]),
15822                dtype: DType::F32,
15823            });
15824            let sig = g.push(Node {
15825                op: Op::SigmoidInplace,
15826                inputs: vec![x],
15827                shape: Shape::from_dims(&[4]),
15828                dtype: DType::F32,
15829            });
15830            g.set_target_backend(step, BackendId::Cpu);
15831            g.set_target_backend(sig, BackendId::Cpu);
15832            (x, step, sig)
15833        };
15834
15835        let mut cache = StorageCache::new();
15836        cache.insert(x_id, Arc::new(RwLock::new(src_storage)));
15837
15838        let results = PipelinedExecutor::realize_many(graph, &[step_id, sig_id], cache)
15839            .expect("realize_many");
15840
15841        // step_x must reflect pre-mutation x: sign of [1, -2, 3, -4] →
15842        // [1, 0, 1, 0]. If the executor ran SigmoidInplace first, step
15843        // would see all-positive sigmoid outputs and produce [1, 1, 1, 1].
15844        let step_guard = results[0].0.read().unwrap();
15845        let fuel_memory::BackendStorage::Cpu(c) = &step_guard.inner else {
15846            panic!("expected Cpu storage for step output");
15847        };
15848        let step_out: &[f32] = c.as_slice().expect("f32 cast");
15849        assert_eq!(
15850            step_out,
15851            &[1.0_f32, 0.0, 1.0, 0.0],
15852            "Step must run before SigmoidInplace; got post-mutation bytes"
15853        );
15854        drop(step_guard);
15855
15856        // SigmoidInplace's output Arc IS the mutated cache entry — bytes
15857        // approximate sigmoid([1, -2, 3, -4]).
15858        let sig_guard = results[1].0.read().unwrap();
15859        let fuel_memory::BackendStorage::Cpu(c) = &sig_guard.inner else {
15860            panic!("expected Cpu storage for sigmoid output");
15861        };
15862        let sig_out: &[f32] = c.as_slice().expect("f32 cast");
15863        let sig_ref = [
15864            1.0_f32 / (1.0 + (-1.0_f32).exp()),
15865            1.0_f32 / (1.0 + (2.0_f32).exp()),
15866            1.0_f32 / (1.0 + (-3.0_f32).exp()),
15867            1.0_f32 / (1.0 + (4.0_f32).exp()),
15868        ];
15869        for (got, want) in sig_out.iter().zip(sig_ref.iter()) {
15870            assert!((got - want).abs() < 1e-6, "sigmoid: got {got}, want {want}");
15871        }
15872    }
15873
15874    /// Regression for the PipelinedExecutor ordering-integration session.
15875    ///
15876    /// Canonical residual-connection pattern:
15877    ///   `x = Const`, `y = ReluInplace(x)`, `z = Add(y, x)`.
15878    ///
15879    /// Pre-this-session: `derive_ordering` was never run, so the cycle
15880    /// (Add must precede ReluInplace per ordering edge; Add must follow
15881    /// ReluInplace per data-flow edge through y) was undetected. The
15882    /// executor produced `z = relu(x) + relu(x) = [2, 0, 6, 0]` —
15883    /// silently wrong.
15884    ///
15885    /// Post-this-session: `insert_safety_copies` runs before
15886    /// `execution_plan`, inserts `Op::Copy(x) → x_safe`, rewires Add's
15887    /// `x` input to `x_safe`. Result: `z = relu(x) + x = [2, -2, 6, -4]`.
15888    #[test]
15889    fn pipelined_residual_connection_inserts_safety_copy() {
15890        use fuel_ir::Shape;
15891        let data = [1.0_f32, -2.0, 3.0, -4.0];
15892        let src_storage = fuel_memory::from_slice_cpu(&data);
15893
15894        let graph = Arc::new(RwLock::new(Graph::new()));
15895        let (x_id, _y_id, z_id) = {
15896            let mut g = graph.write().unwrap();
15897            let x = g.push(Node {
15898                op: Op::Const,
15899                inputs: vec![],
15900                shape: Shape::from_dims(&[4]),
15901                dtype: DType::F32,
15902            });
15903            let y = g.push(Node {
15904                op: Op::ReluInplace,
15905                inputs: vec![x],
15906                shape: Shape::from_dims(&[4]),
15907                dtype: DType::F32,
15908            });
15909            let z = g.push(Node {
15910                op: Op::Add,
15911                inputs: vec![y, x],
15912                shape: Shape::from_dims(&[4]),
15913                dtype: DType::F32,
15914            });
15915            g.set_target_backend(y, BackendId::Cpu);
15916            g.set_target_backend(z, BackendId::Cpu);
15917            (x, y, z)
15918        };
15919
15920        let mut cache = StorageCache::new();
15921        cache.insert(x_id, Arc::new(RwLock::new(src_storage)));
15922
15923        let (result_arc, _) = PipelinedExecutor::realize(graph, z_id, cache)
15924            .expect("realize z — insert_safety_copies must break the cycle");
15925
15926        let guard = result_arc.read().unwrap();
15927        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15928            panic!("expected Cpu storage");
15929        };
15930        let got: &[f32] = c.as_slice().expect("f32 cast");
15931        assert_eq!(
15932            got,
15933            &[2.0_f32, -2.0, 6.0, -4.0],
15934            "Add must read pre-mutation x via the inserted safety copy"
15935        );
15936    }
15937
15938    // ------------------------------------------------------------------
15939    // Item 3 end-to-end: SelectiveScan through the bundled-output
15940    // PipelinedExecutor path. The producer allocates bundled
15941    // (y_bytes + last_state_bytes), the kernel writes both slots,
15942    // and the bundled-tuple builder returns each via Op::View.
15943    // ------------------------------------------------------------------
15944
15945    fn cpu_const_f32(
15946        graph: &Arc<RwLock<Graph>>,
15947        cache: &mut StorageCache,
15948        data: &[f32],
15949        dims: &[usize],
15950    ) -> NodeId {
15951        let id = {
15952            let mut g = graph.write().unwrap();
15953            g.push(Node {
15954                op: Op::Const,
15955                inputs: vec![],
15956                shape: Shape::from_dims(dims),
15957                dtype: DType::F32,
15958            })
15959        };
15960        cache.insert(id, Arc::new(RwLock::new(fuel_memory::from_slice_cpu(data))));
15961        id
15962    }
15963
15964    /// `selective_scan_bundled` realizes both `y` and `last_state` in
15965    /// a single `realize_many` pass; the Views project the same
15966    /// producer's bundled Storage Arc and the numerics match the
15967    /// hand-computed single-step kernel test (b=1,s=1,d=1,k=1).
15968    #[test]
15969    fn pipelined_realize_selective_scan_bundled_produces_y_and_last_state() {
15970        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
15971        let mut cache = StorageCache::new();
15972
15973        let u_id = cpu_const_f32(&graph, &mut cache, &[3.0], &[1, 1, 1]);
15974        let delta_id = cpu_const_f32(&graph, &mut cache, &[1.0], &[1, 1, 1]);
15975        let a_id = cpu_const_f32(&graph, &mut cache, &[-1.0], &[1, 1]);
15976        let b_id = cpu_const_f32(&graph, &mut cache, &[2.0], &[1, 1, 1]);
15977        let c_id = cpu_const_f32(&graph, &mut cache, &[0.5], &[1, 1, 1]);
15978
15979        let (y_id, last_state_id) = {
15980            let u_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), u_id);
15981            let delta_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), delta_id);
15982            let a_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), a_id);
15983            let b_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), b_id);
15984            let c_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), c_id);
15985            let (y, last_state) = u_t
15986                .selective_scan_bundled(&delta_t, &a_t, &b_t, &c_t, /* delta_softplus */ false)
15987                .expect("selective_scan_bundled");
15988            (y.id(), last_state.id())
15989        };
15990        // Set target_backend on the producer (View nodes inherit it).
15991        {
15992            let mut g = graph.write().unwrap();
15993            let producer = g.node(y_id).inputs[0];
15994            g.set_target_backend(producer, BackendId::Cpu);
15995        }
15996
15997        let outputs =
15998            PipelinedExecutor::realize_many(Arc::clone(&graph), &[y_id, last_state_id], cache)
15999                .expect("realize_many");
16000        let (y_arc, y_layout) = outputs[0].clone();
16001        let (last_state_arc, last_state_layout) = outputs[1].clone();
16002
16003        // Both Views project the same bundled producer Storage Arc.
16004        assert!(
16005            Arc::ptr_eq(&y_arc, &last_state_arc),
16006            "y and last_state Views project the SAME bundled producer Storage",
16007        );
16008
16009        // Hand-computed numerics (single-step recurrence):
16010        // h[0,0,0] = exp(1.0 * -1.0) * 0 + 1.0 * 2.0 * 3.0 = 6.0
16011        // y[0,0,0] = h * c = 6.0 * 0.5 = 3.0
16012        // last_state[0,0,0] = h = 6.0
16013        let guard = y_arc.read().unwrap();
16014        let fuel_memory::BackendStorage::Cpu(c_bytes) = &guard.inner else {
16015            panic!("expected Cpu storage");
16016        };
16017        let typed: &[f32] = c_bytes.as_slice().expect("f32 cast");
16018        assert_eq!(y_layout.start_offset(), 0);
16019        let y_value = typed[y_layout.start_offset()];
16020        assert!((y_value - 3.0).abs() < 1e-5, "y expected 3.0 got {y_value}");
16021        assert_eq!(
16022            last_state_layout.start_offset(),
16023            1,
16024            "slot 1 byte_offset 4 / sizeof(f32) = 1",
16025        );
16026        let ls_value = typed[last_state_layout.start_offset()];
16027        assert!(
16028            (ls_value - 6.0).abs() < 1e-5,
16029            "last_state expected 6.0 got {ls_value}"
16030        );
16031    }
16032
16033    // ---- Ordering-defect repros (MLA decode multi-round WriteSlice) -----
16034
16035    /// DIAGNOSTIC (not a repro by itself): a plain single-hop view chain
16036    /// `S = Slice(X); K = Relu(S)` competing with a SECOND destructive
16037    /// WriteSlice on `X` (`Y = WriteSlice(X, ...)`) within one
16038    /// `realize_many` call. `collect_alias_set` adds `S` to `X`'s alias
16039    /// set (Slice IS `is_view_op`), so `derive_ordering` pins `Y` after
16040    /// `S`'s reader `K` directly. This form is expected to STAY GREEN —
16041    /// recorded here as the control that isolates the Reshape-specific
16042    /// gap exercised by the next test.
16043    #[test]
16044    fn pipelined_write_slice_round2_plain_slice_reader_not_stranded() {
16045        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16046        let mut cache = StorageCache::new();
16047
16048        let b_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16049        let src1_id = cpu_const_f32(&graph, &mut cache, &[1.0, 2.0], &[2]);
16050        let src2_id = cpu_const_f32(&graph, &mut cache, &[99.0, 98.0], &[2]);
16051
16052        let (k_id, y_id) = {
16053            let mut g = graph.write().unwrap();
16054            let x_id = g.push(Node {
16055                op: Op::WriteSlice {
16056                    ranges: vec![(0, 2)],
16057                    dyn_offset: None,
16058                },
16059                inputs: vec![b_id, src1_id],
16060                shape: Shape::from_dims(&[4]),
16061                dtype: DType::F32,
16062            });
16063            let s_id = g.push(Node {
16064                op: Op::Slice {
16065                    dim: 0,
16066                    start: 0,
16067                    len: 2,
16068                },
16069                inputs: vec![x_id],
16070                shape: Shape::from_dims(&[2]),
16071                dtype: DType::F32,
16072            });
16073            let k_id = g.push(Node {
16074                op: Op::Relu,
16075                inputs: vec![s_id],
16076                shape: Shape::from_dims(&[2]),
16077                dtype: DType::F32,
16078            });
16079            // Round 2 OVERLAPS round 1's [0,2) range so a wrong-order
16080            // execution would be numerically visible in K's output.
16081            let y_id = g.push(Node {
16082                op: Op::WriteSlice {
16083                    ranges: vec![(0, 2)],
16084                    dyn_offset: None,
16085                },
16086                inputs: vec![x_id, src2_id],
16087                shape: Shape::from_dims(&[4]),
16088                dtype: DType::F32,
16089            });
16090            g.set_target_backend(x_id, BackendId::Cpu);
16091            g.set_target_backend(k_id, BackendId::Cpu);
16092            g.set_target_backend(y_id, BackendId::Cpu);
16093            (k_id, y_id)
16094        };
16095
16096        let plan = fuel_graph::opt::execution_plan(&graph.read().unwrap(), &[k_id, y_id]);
16097        eprintln!("[diagnostic plain-slice] execution_plan = {:?}", plan,);
16098
16099        let outputs = PipelinedExecutor::realize_many(Arc::clone(&graph), &[k_id, y_id], cache)
16100            .expect("realize_many: plain slice reader must not error");
16101        let (k_arc, _) = &outputs[0];
16102        let guard = k_arc.read().unwrap();
16103        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16104            panic!("expected Cpu storage");
16105        };
16106        let out: &[f32] = c.as_slice().unwrap();
16107        assert_eq!(
16108            out,
16109            &[1.0, 2.0],
16110            "K = relu(slice(X,0,2)) must read PRE-round-2 bytes; got {:?}",
16111            out,
16112        );
16113    }
16114
16115    /// CRITICAL SUSPECT #2 repro: `Op::Reshape`/`Op::Contiguize` compile
16116    /// to `WorkItemKind::ContiguizeOf`, which zero-copy ADOPTS the
16117    /// input's Storage Arc when the input is contiguous at offset 0 —
16118    /// but `Op::Reshape` is NOT in `collect_alias_set`'s alias-extending
16119    /// predicate (only `Op::is_view_op` + `Op::View{..}`). So for
16120    /// `X = write_slice(B, src1); S = X.slice(0, 0, 2) [offset-0
16121    /// contiguous]; R = S.reshape([2]); K = relu(R); Y =
16122    /// write_slice(X, src2)`, `collect_alias_set(X)` stops at `{X, S}`
16123    /// — `R` never enters the alias set, so `derive_ordering` never
16124    /// scans `R`'s consumers (`K`) for pinning against `Y`. `K` and `Y`
16125    /// become simultaneously "ready" once `R` completes, and
16126    /// `execution_plan`'s stable tiebreak (smaller `topo_order_multi`
16127    /// position wins) can schedule `Y` (destructive) BEFORE `K` — `K`
16128    /// then dereferences `R`'s adopted Arc (== `X`'s Arc, mutated
16129    /// in-place by `Y`) and silently reads POST-`Y` bytes. No error;
16130    /// wrong numbers.
16131    #[test]
16132    fn pipelined_write_slice_reshape_adopted_arc_reader_reads_pre_write_bytes() {
16133        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16134        let mut cache = StorageCache::new();
16135
16136        let b_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16137        let src1_id = cpu_const_f32(&graph, &mut cache, &[1.0, 2.0], &[2]);
16138        let src2_id = cpu_const_f32(&graph, &mut cache, &[99.0, 98.0], &[2]);
16139
16140        let (x_id, k_id, y_id) = {
16141            let mut g = graph.write().unwrap();
16142            let x_id = g.push(Node {
16143                op: Op::WriteSlice {
16144                    ranges: vec![(0, 2)],
16145                    dyn_offset: None,
16146                },
16147                inputs: vec![b_id, src1_id],
16148                shape: Shape::from_dims(&[4]),
16149                dtype: DType::F32,
16150            });
16151            let s_id = g.push(Node {
16152                // OFFSET-0 contiguous prefix slice — ContiguizeOf's
16153                // zero-copy fast path requires this at execute time.
16154                op: Op::Slice {
16155                    dim: 0,
16156                    start: 0,
16157                    len: 2,
16158                },
16159                inputs: vec![x_id],
16160                shape: Shape::from_dims(&[2]),
16161                dtype: DType::F32,
16162            });
16163            let r_id = g.push(Node {
16164                op: Op::Reshape(Shape::from_dims(&[2])),
16165                inputs: vec![s_id],
16166                shape: Shape::from_dims(&[2]),
16167                dtype: DType::F32,
16168            });
16169            let k_id = g.push(Node {
16170                op: Op::Relu,
16171                inputs: vec![r_id],
16172                shape: Shape::from_dims(&[2]),
16173                dtype: DType::F32,
16174            });
16175            // Round 2 OVERLAPS round 1's [0,2) range (not the [2,4)
16176            // tail) so a wrong-order execution is numerically visible
16177            // in K's output — a disjoint round 2 would corrupt bytes
16178            // K never reads, masking the defect.
16179            let y_id = g.push(Node {
16180                op: Op::WriteSlice {
16181                    ranges: vec![(0, 2)],
16182                    dyn_offset: None,
16183                },
16184                inputs: vec![x_id, src2_id],
16185                shape: Shape::from_dims(&[4]),
16186                dtype: DType::F32,
16187            });
16188            g.set_target_backend(x_id, BackendId::Cpu);
16189            g.set_target_backend(k_id, BackendId::Cpu);
16190            g.set_target_backend(y_id, BackendId::Cpu);
16191            (x_id, k_id, y_id)
16192        };
16193        let _ = x_id;
16194
16195        let plan = fuel_graph::opt::execution_plan(&graph.read().unwrap(), &[k_id, y_id]);
16196        eprintln!(
16197            "[diagnostic reshape-adopted-arc] execution_plan = {:?}",
16198            plan,
16199        );
16200
16201        let outputs = PipelinedExecutor::realize_many(Arc::clone(&graph), &[k_id, y_id], cache)
16202            .expect("realize_many");
16203        let (k_arc, _) = &outputs[0];
16204        let guard = k_arc.read().unwrap();
16205        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16206            panic!("expected Cpu storage");
16207        };
16208        let out: &[f32] = c.as_slice().unwrap();
16209        // K = relu(reshape(slice(X,0,2))) must read PRE-round-2 bytes:
16210        // relu([1.0, 2.0]) = [1.0, 2.0]. Round 2 overwrites the SAME
16211        // [0,2) range with [99.0, 98.0] — if Y (round 2) runs before K
16212        // (the ordering defect), K instead observes [99.0, 98.0].
16213        assert_eq!(
16214            out,
16215            &[1.0, 2.0],
16216            "K must read PRE-round-2 bytes through the adopted Arc; got {:?} \
16217             (post-round-2 corruption if this fails)",
16218            out,
16219        );
16220    }
16221
16222    /// The MLA-decode shape from `rebind_latent_cache_fresh_graph`'s doc
16223    /// (`fuel-core/src/lazy_deepseek2.rs`): layer L's post-append buffer
16224    /// `X_L_N` (round N) is read TWICE within one realize call — once
16225    /// (non-destructively) through a Slice+Reshape "attention math" view
16226    /// chain whose result becomes an ancestor of layer L+1's round-N
16227    /// write, and again as the DESTINATION of layer L's round-(N+1)
16228    /// append. Reproduces the same Reshape-adoption gap as
16229    /// `pipelined_write_slice_reshape_adopted_arc_reader_reads_pre_write_bytes`
16230    /// at 2-layer scale, confirming the defect is not an artifact of the
16231    /// single-hop minimal form.
16232    #[test]
16233    fn pipelined_write_slice_mla_two_layer_round2_reshape_reader_not_stranded() {
16234        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16235        let mut cache = StorageCache::new();
16236
16237        let b_l_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16238        let src_l_n_id = cpu_const_f32(&graph, &mut cache, &[1.0, 2.0], &[2]);
16239        let b_l1_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16240        let src_l_n1_id = cpu_const_f32(&graph, &mut cache, &[99.0, 98.0], &[2]);
16241
16242        let (x_l_n1_id, x_l1_n_id) = {
16243            let mut g = graph.write().unwrap();
16244            // Round N, layer L: append src_l_n into b_l.
16245            let x_l_n = g.push(Node {
16246                op: Op::WriteSlice {
16247                    ranges: vec![(0, 2)],
16248                    dyn_offset: None,
16249                },
16250                inputs: vec![b_l_id, src_l_n_id],
16251                shape: Shape::from_dims(&[4]),
16252                dtype: DType::F32,
16253            });
16254            // "Attention math" for round N at layer L: read the filled
16255            // prefix, reshape (head-split-style hop), then a kernel.
16256            let s_l_n = g.push(Node {
16257                op: Op::Slice {
16258                    dim: 0,
16259                    start: 0,
16260                    len: 2,
16261                },
16262                inputs: vec![x_l_n],
16263                shape: Shape::from_dims(&[2]),
16264                dtype: DType::F32,
16265            });
16266            let rs_l_n = g.push(Node {
16267                op: Op::Reshape(Shape::from_dims(&[2])),
16268                inputs: vec![s_l_n],
16269                shape: Shape::from_dims(&[2]),
16270                dtype: DType::F32,
16271            });
16272            let r_l_n = g.push(Node {
16273                op: Op::Relu,
16274                inputs: vec![rs_l_n],
16275                shape: Shape::from_dims(&[2]),
16276                dtype: DType::F32,
16277            });
16278            // Round N, layer L+1: append the attention-math result.
16279            let x_l1_n = g.push(Node {
16280                op: Op::WriteSlice {
16281                    ranges: vec![(0, 2)],
16282                    dyn_offset: None,
16283                },
16284                inputs: vec![b_l1_id, r_l_n],
16285                shape: Shape::from_dims(&[4]),
16286                dtype: DType::F32,
16287            });
16288            // Round N+1, layer L: append into x_l_n directly (SAME node
16289            // s_l_n/rs_l_n/r_l_n read from) — OVERLAPPING range so a
16290            // wrong-order execution is numerically visible downstream.
16291            let x_l_n1 = g.push(Node {
16292                op: Op::WriteSlice {
16293                    ranges: vec![(0, 2)],
16294                    dyn_offset: None,
16295                },
16296                inputs: vec![x_l_n, src_l_n1_id],
16297                shape: Shape::from_dims(&[4]),
16298                dtype: DType::F32,
16299            });
16300            g.set_target_backend(x_l_n, BackendId::Cpu);
16301            g.set_target_backend(r_l_n, BackendId::Cpu);
16302            g.set_target_backend(x_l1_n, BackendId::Cpu);
16303            g.set_target_backend(x_l_n1, BackendId::Cpu);
16304            (x_l_n1, x_l1_n)
16305        };
16306
16307        let plan = fuel_graph::opt::execution_plan(&graph.read().unwrap(), &[x_l1_n_id, x_l_n1_id]);
16308        eprintln!("[diagnostic mla-2-layer] execution_plan = {:?}", plan);
16309
16310        let outputs =
16311            PipelinedExecutor::realize_many(Arc::clone(&graph), &[x_l1_n_id, x_l_n1_id], cache)
16312                .expect("realize_many");
16313        // outputs[0] = x_l1_n = write_slice(b_l1, relu(reshape(slice(x_l_n))))
16314        // Must reflect round-N's PRE-round-(N+1) bytes: relu([1,2]) = [1,2].
16315        let (x_l1_n_arc, _) = &outputs[0];
16316        let guard = x_l1_n_arc.read().unwrap();
16317        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16318            panic!("expected Cpu storage");
16319        };
16320        let out: &[f32] = c.as_slice().unwrap();
16321        assert_eq!(
16322            out,
16323            &[1.0, 2.0, 0.0, 0.0],
16324            "layer L+1's round-N append must reflect PRE-round-(N+1) attention \
16325             math output; got {:?} (post-round-(N+1) corruption if this fails)",
16326            out,
16327        );
16328    }
16329}