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                        std::mem::discriminant(other),
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                        std::mem::discriminant(other),
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                        std::mem::discriminant(other),
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 = match target {
2970            DeviceLocation::Cpu => BackendId::Cpu,
2971            DeviceLocation::Cuda { .. } => BackendId::Cuda,
2972            DeviceLocation::Vulkan { .. } => BackendId::Vulkan,
2973            DeviceLocation::Metal { .. } => BackendId::Metal,
2974        };
2975        return Ok(WorkItem {
2976            node_id: id,
2977            inputs,
2978            elem_count,
2979            dtype: node.dtype,
2980            target_backend,
2981            kind: WorkItemKind::Alloc {
2982                target_location: target,
2983            },
2984            compiled: None,
2985            output_layout,
2986            destructive_input,
2987            output_bundle: None,
2988        });
2989    }
2990
2991    if let Op::Iota { len } = node.op {
2992        // Op::Iota { len }: 0-input F32 position generator
2993        // [0.0, 1.0, …, (len-1)]. Direct executor dispatch via
2994        // WorkItemKind::Iota — no binding-table lookup (a leaf has no
2995        // inputs[0] to inherit a backend from). Modeled on Op::Alloc.
2996        if !inputs.is_empty() {
2997            return Err(
2998                Error::Msg(format!("Op::Iota expects 0 inputs, got {}", inputs.len(),)).bt(),
2999            );
3000        }
3001        let output_layout = Layout::contiguous(node.shape.clone());
3002        layout_cache.insert(id, output_layout.clone());
3003        // Leaf: the planner may not place a 0-input node, so fall back to
3004        // CPU. Iota is a tiny host-side generator; its only consumer today
3005        // is the CPU flash-attn decomposition's alibi bias.
3006        let target_backend = graph.target_backend(id).unwrap_or(BackendId::Cpu);
3007        return Ok(WorkItem {
3008            node_id: id,
3009            inputs,
3010            elem_count,
3011            dtype: node.dtype,
3012            target_backend,
3013            kind: WorkItemKind::Iota { len },
3014            compiled: None,
3015            output_layout,
3016            destructive_input,
3017            output_bundle: None,
3018        });
3019    }
3020
3021    if matches!(node.op, Op::ZeroFill) {
3022        // Op::ZeroFill: 1 input (the buffer to zero); output aliases
3023        // input's Storage Arc (destructive in-place). No binding-
3024        // table lookup — per-backend dispatch in execute_work_item.
3025        if inputs.len() != 1 {
3026            return Err(Error::Msg(format!(
3027                "Op::ZeroFill expects 1 input, got {}",
3028                inputs.len(),
3029            ))
3030            .bt());
3031        }
3032        // Output layout: contiguous in the node's shape. We don't
3033        // require the input to be contiguous (auto_contiguize in the
3034        // executor handles strided inputs), but the destructive
3035        // semantic means callers should only ZeroFill an Op::Alloc
3036        // output today.
3037        let output_layout = Layout::contiguous(node.shape.clone());
3038        layout_cache.insert(id, output_layout.clone());
3039        let target_backend = graph
3040            .target_backend(id)
3041            .or_else(|| graph.target_backend(inputs[0]))
3042            .unwrap_or(BackendId::Cpu);
3043        return Ok(WorkItem {
3044            node_id: id,
3045            inputs,
3046            elem_count,
3047            dtype: node.dtype,
3048            target_backend,
3049            kind: WorkItemKind::ZeroFill,
3050            compiled: None,
3051            output_layout,
3052            destructive_input,
3053            output_bundle: None,
3054        });
3055    }
3056
3057    if let Op::Copy { target } = node.op {
3058        // Op::Copy { target }: download bytes from the source residency
3059        // to a fresh Storage allocated on `target`. Kernel lookup uses
3060        // `target_backend` = source backend (set by `prepare()` on the
3061        // realize device the source is on); the wrapper does the actual
3062        // transfer (e.g. Vulkan::download_bytes → memcpy into a CPU
3063        // CpuStorageBytes). The output Storage's variant is determined
3064        // by `target_location` and allocated in `execute_work_item`'s
3065        // WorkItemKind::Copy arm.
3066        if inputs.len() != 1 {
3067            return Err(
3068                Error::Msg(format!("Op::Copy expects 1 input, got {}", inputs.len(),)).bt(),
3069            );
3070        }
3071        let target_backend = graph.target_backend(id).ok_or_else(|| {
3072            Error::Msg(format!(
3073                "PipelinedExecutor: Op::Copy node {:?} has no target_backend \
3074                 set (= source backend, the one whose kernel runs the \
3075                 download)",
3076                id
3077            ))
3078            .bt()
3079        })?;
3080        let op_params = OpParams::None;
3081        let dtypes = build_lookup_dtypes(graph, node);
3082        let compiled =
3083            resolve_compiled(OpKind::Copy, &dtypes, target_backend, op_params, bindings)?;
3084        // Output layout: contiguous in the node's shape (mirrors the
3085        // source's logical shape). Auto-contiguize on the input side
3086        // (in execute_work_item) handles strided source views by
3087        // materializing them into a contiguous source buffer before
3088        // the kernel runs.
3089        let output_layout = Layout::contiguous(node.shape.clone());
3090        layout_cache.insert(id, output_layout.clone());
3091        return Ok(WorkItem {
3092            node_id: id,
3093            inputs,
3094            elem_count,
3095            dtype: node.dtype,
3096            target_backend,
3097            kind: WorkItemKind::Copy {
3098                target_location: target,
3099            },
3100            compiled: Some(compiled),
3101            output_layout,
3102            destructive_input,
3103            output_bundle: None,
3104        });
3105    }
3106
3107    if let Op::Move { target } = node.op {
3108        // Op::Move { target }: identical data-movement half to
3109        // Op::Copy — kernel lookup at (OpKind::Copy, [dt, dt],
3110        // source_backend); output allocated on `target` by the
3111        // executor's Copy/Move arm. The destructive half (release
3112        // the source) rides the realize loop's `destructive_input`
3113        // cleanup via the snapshot taken at the top of this function
3114        // (`Op::Move::destructive_input() == Some(0)`). Ordering
3115        // safety (a Move must not strand a sibling consumer of its
3116        // source) is `execution_plan`/`derive_ordering`'s job — the
3117        // Move is pinned after every non-destructive reader of the
3118        // source's alias set before any work item is emitted.
3119        if inputs.len() != 1 {
3120            return Err(
3121                Error::Msg(format!("Op::Move expects 1 input, got {}", inputs.len(),)).bt(),
3122            );
3123        }
3124        let target_backend = graph.target_backend(id).ok_or_else(|| {
3125            Error::Msg(format!(
3126                "PipelinedExecutor: Op::Move node {:?} has no target_backend \
3127                 set (= source backend, the one whose kernel runs the \
3128                 transfer)",
3129                id
3130            ))
3131            .bt()
3132        })?;
3133        let op_params = OpParams::None;
3134        let dtypes = build_lookup_dtypes(graph, node);
3135        let compiled =
3136            resolve_compiled(OpKind::Copy, &dtypes, target_backend, op_params, bindings)?;
3137        // Output layout: contiguous in the node's shape, same as
3138        // Op::Copy (the transfer materializes strided sources via
3139        // auto-contiguize on the input side).
3140        let output_layout = Layout::contiguous(node.shape.clone());
3141        layout_cache.insert(id, output_layout.clone());
3142        return Ok(WorkItem {
3143            node_id: id,
3144            inputs,
3145            elem_count,
3146            dtype: node.dtype,
3147            target_backend,
3148            kind: WorkItemKind::Move {
3149                target_location: target,
3150            },
3151            compiled: Some(compiled),
3152            output_layout,
3153            destructive_input,
3154            output_bundle: None,
3155        });
3156    }
3157
3158    if matches!(node.op, Op::Reshape(_)) {
3159        if inputs.len() != 1 {
3160            return Err(
3161                Error::Msg(format!("Op::Reshape expects 1 input, got {}", inputs.len(),)).bt(),
3162            );
3163        }
3164        let input_layout = graph.layout(inputs[0]);
3165        // Output is contiguous in the new shape — bytes per element
3166        // are unchanged, so a contiguous input flows through with
3167        // zero copy. A non-contiguous input is auto-contiguized at
3168        // execute time and the result is naturally contiguous.
3169        let output_layout = Layout::contiguous(node.shape.clone());
3170        layout_cache.insert(id, output_layout.clone());
3171        let target_backend = graph
3172            .target_backend(id)
3173            .or_else(|| graph.target_backend(inputs[0]))
3174            .unwrap_or(BackendId::Cpu);
3175        // Sanity: same total element count.
3176        let in_elem_count = input_layout.shape().elem_count();
3177        if in_elem_count != elem_count {
3178            return Err(Error::Msg(format!(
3179                "Op::Reshape changes element count: input {} → output {}",
3180                in_elem_count, elem_count,
3181            ))
3182            .bt());
3183        }
3184        return Ok(WorkItem {
3185            node_id: id,
3186            inputs,
3187            elem_count,
3188            dtype: node.dtype,
3189            target_backend,
3190            kind: WorkItemKind::ContiguizeOf {
3191                input: node.inputs[0],
3192            },
3193            compiled: None,
3194            output_layout,
3195            destructive_input,
3196            output_bundle: None,
3197        });
3198    }
3199
3200    if matches!(node.op, Op::Contiguize) {
3201        // Op::Contiguize: same execute-time path as Reshape, but
3202        // output shape == input shape so there's no element-count
3203        // check. Zero-copy when input is already contiguous +
3204        // zero-offset (the ContiguizeOf arm in execute_work_item
3205        // adopts the input Arc); otherwise auto_contiguize allocates
3206        // a fresh contiguous Storage on the input's backend.
3207        if inputs.len() != 1 {
3208            return Err(Error::Msg(format!(
3209                "Op::Contiguize expects 1 input, got {}",
3210                inputs.len(),
3211            ))
3212            .bt());
3213        }
3214        let output_layout = Layout::contiguous(node.shape.clone());
3215        layout_cache.insert(id, output_layout.clone());
3216        let target_backend = graph
3217            .target_backend(id)
3218            .or_else(|| graph.target_backend(inputs[0]))
3219            .unwrap_or(BackendId::Cpu);
3220        return Ok(WorkItem {
3221            node_id: id,
3222            inputs,
3223            elem_count,
3224            dtype: node.dtype,
3225            target_backend,
3226            kind: WorkItemKind::ContiguizeOf {
3227                input: node.inputs[0],
3228            },
3229            compiled: None,
3230            output_layout,
3231            destructive_input,
3232            output_bundle: None,
3233        });
3234    }
3235
3236    // Runtime fused op — a JIT-adopted (Tier-2) kernel. `Op::Fused(fid, _)`
3237    // with `fid.is_runtime()` has no `OpKind` (the op was synthesized after
3238    // startup): its kernel resolves from the SAME binding table as every
3239    // static kernel, under `BindingKey::RuntimeFused(fid)` — the dtype tuple
3240    // is the key, so an absent kernel AND a dtype mismatch are one honest
3241    // `NoBackendForOp` miss. A deterministic *lookup*, not a decision: the
3242    // optimizer's gate emitted the arm only when this kernel was bound, and
3243    // pinned `target_backend` (`runtime-fused-op-registration.md` §6). The
3244    // guards are invariant checks, never live fallbacks.
3245    if let Op::Fused(fid, _) = &node.op
3246        && fid.is_runtime()
3247    {
3248        let target_backend = graph.target_backend(id).ok_or_else(|| {
3249            Error::Msg(format!(
3250                "PipelinedExecutor: runtime fused op {:?} (node {:?}) has no \
3251                     target_backend — the arm emitter pins it at emission",
3252                fid, id,
3253            ))
3254            .bt()
3255        })?;
3256        // v1: single-output only. Reject a multi-output bundle explicitly
3257        // rather than silently dropping it.
3258        if graph.output_views_arc(id).is_some() {
3259            return Err(Error::Msg(format!(
3260                "PipelinedExecutor: runtime fused op {:?} (node {:?}) carries a \
3261                     multi-output bundle — synthesized kernels are single-output in v1",
3262                fid, id,
3263            ))
3264            .bt());
3265        }
3266        let dtypes = build_lookup_dtypes(graph, node);
3267        let (kernel, caps) = bindings.lookup_with_caps(
3268            crate::kernel::BindingKey::RuntimeFused(*fid),
3269            &dtypes,
3270            target_backend,
3271        )?;
3272        let output_layout = Layout::contiguous(node.shape.clone());
3273        layout_cache.insert(id, output_layout.clone());
3274        // Deliberate, not a fallthrough to `op_to_op_params` (which doesn't
3275        // know runtime ops): the node's `Runtime { scalars }` — the live
3276        // `extract:` values, pattern pre-order — becomes `JitScalars` (the
3277        // launch appends them as the kernel's trailing `p{i}` args); a
3278        // param-free op carries `None` (its launch is layout-driven:
3279        // pointers + element count).
3280        let op_params = match &node.op {
3281            Op::Fused(_, FusedOpParams::Runtime { scalars }) if !scalars.is_empty() => {
3282                OpParams::JitScalars {
3283                    scalars: scalars.clone(),
3284                }
3285            }
3286            _ => OpParams::None,
3287        };
3288        let compiled = CompiledNode {
3289            op: OpKind::RuntimeFused,
3290            dtypes: KernelDTypes::from_slice(&dtypes),
3291            backend: target_backend,
3292            kernel,
3293            caps,
3294            op_params,
3295        };
3296        return Ok(WorkItem {
3297            node_id: id,
3298            inputs,
3299            elem_count,
3300            dtype: node.dtype,
3301            target_backend,
3302            kind: WorkItemKind::Kernel,
3303            compiled: Some(compiled),
3304            output_layout,
3305            destructive_input,
3306            output_bundle: None,
3307        });
3308    }
3309
3310    let target_backend = graph.target_backend(id).ok_or_else(|| {
3311        Error::Msg(format!(
3312            "PipelinedExecutor: node {:?} ({:?}) has no target_backend set",
3313            id, node.op
3314        ))
3315        .bt()
3316    })?;
3317
3318    let op_kind = op_to_op_kind(&node.op).ok_or_else(|| {
3319        Error::Msg(format!(
3320            "PipelinedExecutor: op {:?} not yet mapped to an OpKind \
3321             (Phase C migrates more ops as they're registered)",
3322            node.op,
3323        ))
3324        .bt()
3325    })?;
3326
3327    let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3328    // Build the per-operand dtype list for the binding-table lookup —
3329    // inputs in order, then outputs. Variadic uniform-dtype ops
3330    // (Concat) collapse to the canonical `[T_in, T_out]` shorthand to
3331    // match how registrations index them.
3332    let dtypes = build_lookup_dtypes(graph, node);
3333    let compiled = resolve_compiled(op_kind, &dtypes, target_backend, op_params, bindings)?;
3334    let output_layout = Layout::contiguous(node.shape.clone());
3335    layout_cache.insert(id, output_layout.clone());
3336    // Multi-output: snapshot the producer's bundle metadata. When
3337    // `Some(_)`, the Kernel arm allocates a single Storage sized to
3338    // fit every slot and attaches the bundle via
3339    // `Storage::with_bundle` so downstream Op::View/Op::ViewOwned
3340    // resolve correctly.
3341    let output_bundle = graph.output_views_arc(id);
3342    Ok(WorkItem {
3343        node_id: id,
3344        inputs,
3345        elem_count,
3346        dtype: node.dtype,
3347        target_backend,
3348        kind: WorkItemKind::Kernel,
3349        compiled: Some(compiled),
3350        output_layout,
3351        destructive_input,
3352        output_bundle,
3353    })
3354}
3355
3356/// Build the per-operand dtype list used as the binding-table lookup
3357/// key. Inputs in order, then the output. Variadic-uniform ops
3358/// (Concat) collapse to the canonical `[T_in, T_out]` shorthand to
3359/// match how those wrappers are registered (otherwise an N-way concat
3360/// would need N+1 distinct registrations per dtype).
3361///
3362/// `pub(crate)` — `crate::plan::compile_plan` (step 9b) reuses this
3363/// to key the route picker's binding-table lookup the same way the
3364/// pipelined path does.
3365pub(crate) fn build_lookup_dtypes(graph: &Graph, node: &Node) -> Vec<DType> {
3366    if matches!(node.op, Op::Concat { .. }) {
3367        // Concat: all inputs share node.dtype by construction.
3368        let in_dt = node
3369            .inputs
3370            .first()
3371            .map(|&id| graph.node(id).dtype)
3372            .unwrap_or(node.dtype);
3373        return vec![in_dt, node.dtype];
3374    }
3375    if matches!(node.op, Op::WriteSlice { .. }) {
3376        // WriteSlice: the destination (inputs[0]) is exposed to the
3377        // executor as the OUTPUT slot (in-place adoption), not as an
3378        // input the kernel reads. Canonicalize the binding-table key
3379        // to `[T_source, T_out]` so registrations match the kernel's
3380        // actual surface (one input slab + one output buffer).
3381        let src_dt = node
3382            .inputs
3383            .get(1)
3384            .map(|&id| graph.node(id).dtype)
3385            .unwrap_or(node.dtype);
3386        return vec![src_dt, node.dtype];
3387    }
3388    if matches!(node.op, Op::WriteSliceRotating { .. }) {
3389        // Same canonicalization as WriteSlice: dest = output slot;
3390        // position (inputs[2]) is read by the kernel via the
3391        // position-input parameter, not the binding-table key.
3392        let src_dt = node
3393            .inputs
3394            .get(1)
3395            .map(|&id| graph.node(id).dtype)
3396            .unwrap_or(node.dtype);
3397        return vec![src_dt, node.dtype];
3398    }
3399    if matches!(node.op, Op::WriteSliceDoff { .. }) {
3400        // Same canonicalization as WriteSlice: dest = output slot;
3401        // offset (inputs[2], I64) is a non-key runtime operand read by
3402        // the kernel via its device pointer, not the binding-table key.
3403        let src_dt = node
3404            .inputs
3405            .get(1)
3406            .map(|&id| graph.node(id).dtype)
3407            .unwrap_or(node.dtype);
3408        return vec![src_dt, node.dtype];
3409    }
3410    let mut dts: Vec<DType> = node.inputs.iter().map(|&id| graph.node(id).dtype).collect();
3411    dts.push(node.dtype);
3412    dts
3413}
3414
3415/// SoftmaxLastDim is reachable only through `Op::Fused(FusedOps::
3416/// SOFTMAX_LAST_DIM, _)` post-step-5 (the legacy `Op::SoftmaxLastDim`
3417/// primitive variant was retired). This helper collapses the
3418/// op-to-OpKind/OpParams shapes for callers that want a single-arm
3419/// match.
3420fn op_is_softmax_last_dim(op: &Op) -> bool {
3421    matches!(op, Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM)
3422}
3423
3424/// FusedLinear is reachable only through `Op::Fused(FusedOps::
3425/// FUSED_LINEAR, _)` post-step-5.
3426fn op_is_fused_linear(op: &Op) -> bool {
3427    matches!(op, Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::FUSED_LINEAR)
3428}
3429
3430/// Map a `fuel_graph::Op` to a `fuel_ir::dispatch::OpKind`.
3431/// Returns `None` for ops that haven't been wired into the new
3432/// dispatch path yet — Phase C extends this as op families migrate.
3433///
3434/// `pub(crate)` — `crate::plan::compile_plan` (step 9b) reuses this
3435/// to skip nodes the binding-table doesn't index (view ops,
3436/// `Op::Const`, not-yet-migrated ops) when building bindings.
3437pub(crate) fn op_to_op_kind(op: &Op) -> Option<OpKind> {
3438    match op {
3439        Op::Add => Some(OpKind::AddElementwise),
3440        Op::Sub => Some(OpKind::SubElementwise),
3441        Op::Mul => Some(OpKind::MulElementwise),
3442        Op::Div => Some(OpKind::DivElementwise),
3443        Op::Relu => Some(OpKind::ReluElementwise),
3444        Op::Neg => Some(OpKind::NegElementwise),
3445        Op::Sqr => Some(OpKind::SqrElementwise),
3446        Op::Sqrt => Some(OpKind::SqrtElementwise),
3447        Op::Tanh => Some(OpKind::TanhElementwise),
3448        Op::Exp => Some(OpKind::ExpElementwise),
3449        Op::Log => Some(OpKind::LogElementwise),
3450        Op::Sin => Some(OpKind::SinElementwise),
3451        Op::Cos => Some(OpKind::CosElementwise),
3452        Op::Sigmoid => Some(OpKind::SigmoidElementwise),
3453        Op::Silu => Some(OpKind::SiluElementwise),
3454        Op::GeluTanh => Some(OpKind::GeluTanhElementwise),
3455        Op::Step => Some(OpKind::StepElementwise),
3456        Op::Recip => Some(OpKind::RecipElementwise),
3457        Op::Abs => Some(OpKind::AbsElementwise),
3458        Op::Equal => Some(OpKind::EqualElementwise),
3459        Op::Ne => Some(OpKind::NotEqualElementwise),
3460        Op::Lt => Some(OpKind::LessElementwise),
3461        Op::Le => Some(OpKind::LessEqualElementwise),
3462        Op::Gt => Some(OpKind::GreaterElementwise),
3463        Op::Ge => Some(OpKind::GreaterEqualElementwise),
3464        Op::Where => Some(OpKind::Where),
3465        Op::Floor => Some(OpKind::FloorElementwise),
3466        Op::Ceil => Some(OpKind::CeilElementwise),
3467        Op::Round => Some(OpKind::RoundElementwise),
3468        Op::Sign => Some(OpKind::SignElementwise),
3469        Op::Erf => Some(OpKind::ErfElementwise),
3470        Op::Gelu => Some(OpKind::GeluElementwise),
3471        Op::Pow => Some(OpKind::PowElementwise),
3472        Op::Rsqrt => Some(OpKind::RsqrtElementwise),
3473        Op::Rem => Some(OpKind::RemElementwise),
3474        Op::Flip { .. } => Some(OpKind::Flip),
3475        Op::Roll { .. } => Some(OpKind::Roll),
3476        Op::CumSum { .. } => Some(OpKind::CumSum),
3477        Op::Triu { .. } => Some(OpKind::Triu),
3478        Op::Tril { .. } => Some(OpKind::Tril),
3479        Op::LogSoftmaxLastDim => Some(OpKind::LogSoftmaxLastDim),
3480        Op::LogSoftmaxLastDimBackward => Some(OpKind::LogSoftmaxLastDimBackward),
3481        Op::MaskedFill { .. } => Some(OpKind::MaskedFill),
3482        Op::Pad { .. } => Some(OpKind::Pad),
3483        Op::PadBackward { .. } => Some(OpKind::PadBackward),
3484        Op::SumDim(_) => Some(OpKind::SumReduce),
3485        Op::MaxDim(_) => Some(OpKind::MaxReduce),
3486        Op::MinDim(_) => Some(OpKind::MinReduce),
3487        Op::MeanDim(_) => Some(OpKind::MeanReduce),
3488        Op::SumAll => Some(OpKind::SumReduce),
3489        Op::MaxAll => Some(OpKind::MaxReduce),
3490        Op::MinAll => Some(OpKind::MinReduce),
3491        Op::MeanAll => Some(OpKind::MeanReduce),
3492        Op::MatMul => Some(OpKind::MatMul),
3493        Op::Cast(_) => Some(OpKind::Cast),
3494        // Phase 7.6 step 5: fused-op dispatch routes through
3495        // `Op::Fused(fid, _)`; the legacy `Op::Conv2D` /
3496        // `Op::FusedLinear` / `Op::SoftmaxLastDim` /
3497        // `Op::RmsNormLastDim` / `Op::LayerNormLastDim` / `Op::Rope`
3498        // arms were dropped together with the variants.
3499        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::CONV2D => Some(OpKind::Conv2D),
3500        // Phase 7.6 step 5 (final): legacy `Op::ConvTranspose2D` /
3501        // `Op::FlashAttn` / `Op::PagedAttn` arms dropped with the
3502        // variants; dispatch flows only through `Op::Fused`.
3503        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D => {
3504            Some(OpKind::ConvTranspose2D)
3505        }
3506        Op::ReduceSumTo(_) => Some(OpKind::ReduceSumTo),
3507        Op::ReduceMaxTo(_) => Some(OpKind::ReduceMaxTo),
3508        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::FLASH_ATTN => {
3509            Some(OpKind::FlashAttn)
3510        }
3511        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::PAGED_ATTN => {
3512            Some(OpKind::PagedAttn)
3513        }
3514        Op::AddScalar(_) => Some(OpKind::Affine),
3515        Op::MulScalar(_) => Some(OpKind::Affine),
3516        Op::Clamp { .. } => Some(OpKind::ClampElementwise),
3517        Op::PowI(_) => Some(OpKind::PowIElementwise),
3518        Op::Maximum => Some(OpKind::MaximumElementwise),
3519        Op::Minimum => Some(OpKind::MinimumElementwise),
3520        Op::Concat { .. } => Some(OpKind::Concat),
3521        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM => {
3522            Some(OpKind::SoftmaxLastDim)
3523        }
3524        // Phase 7.6 step 6 follow-up: backward helpers now route
3525        // through the byte-level binding table too.
3526        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM_BACKWARD => {
3527            Some(OpKind::SoftmaxLastDimBackward)
3528        }
3529        Op::Fused(fid, _)
3530            if *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM_BACKWARD =>
3531        {
3532            Some(OpKind::LayerNormLastDimBackward)
3533        }
3534        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM_BACKWARD => {
3535            Some(OpKind::RmsNormLastDimBackward)
3536        }
3537        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::REDUCE_MAX_TO_BACKWARD => {
3538            Some(OpKind::ReduceMaxToBackward)
3539        }
3540        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::POWI_BACKWARD => {
3541            Some(OpKind::PowIElementwiseBackward)
3542        }
3543        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::FUSED_LINEAR => {
3544            Some(OpKind::FusedLinear)
3545        }
3546        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM => {
3547            Some(OpKind::RmsNormLastDim)
3548        }
3549        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM => {
3550            Some(OpKind::LayerNormLastDim)
3551        }
3552        Op::IndexSelect { .. } => Some(OpKind::IndexSelect),
3553        Op::Gather { .. } => Some(OpKind::Gather),
3554        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::ROPE => Some(OpKind::Rope),
3555        Op::IndexAdd { .. } => Some(OpKind::IndexAdd),
3556        Op::ScatterAdd { .. } => Some(OpKind::ScatterAdd),
3557        Op::NonZeroIndices { .. } => Some(OpKind::NonZeroIndices),
3558        Op::ArgMaxDim(_) => Some(OpKind::ArgMaxDim),
3559        Op::ArgMinDim(_) => Some(OpKind::ArgMinDim),
3560        // Phase 7.6 step 5 (final): legacy `Op::QMatMul` arm dropped.
3561        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::QMATMUL => {
3562            Some(OpKind::QMatMul)
3563        }
3564        Op::WriteSlice { .. } => Some(OpKind::WriteSlice),
3565        Op::WriteSliceRotating { .. } => Some(OpKind::WriteSliceRotating),
3566        Op::WriteSliceDoff { .. } => Some(OpKind::WriteSliceDoff),
3567        // Phase 2 of bridge-retirement (post-9c): Op::Copy dispatches
3568        // through the binding table at OpKind::Copy. The BackendId
3569        // axis encodes the source backend (the kernel runs there —
3570        // download from local memory). The executor handles output
3571        // allocation on the target via a dedicated WorkItemKind::Copy
3572        // arm, since target_location differs from target_backend for
3573        // this op (the only one with that property today).
3574        Op::Copy { .. } => Some(OpKind::Copy),
3575        // Op::Move dispatches the same data-movement kernel as
3576        // Op::Copy — the destructive release of the source is
3577        // realize-loop bookkeeping (`destructive_input` cleanup), not
3578        // a kernel. Same OpKind, same source-backend key convention.
3579        // `compile_plan` skips both (residency-determined, not a
3580        // picker decision).
3581        Op::Move { .. } => Some(OpKind::Copy),
3582        // Phase 3 of the in-place ops infrastructure: each in-place Op
3583        // variant maps to its OpKind so the binding-table dispatch can
3584        // resolve a kernel. The executor's dedicated WorkItemKind
3585        // arms (added alongside) handle the storage-Arc adoption.
3586        Op::ReluInplace => Some(OpKind::ReluInplace),
3587        Op::SiluInplace => Some(OpKind::SiluInplace),
3588        Op::GeluTanhInplace => Some(OpKind::GeluTanhInplace),
3589        Op::TanhInplace => Some(OpKind::TanhInplace),
3590        Op::SigmoidInplace => Some(OpKind::SigmoidInplace),
3591        Op::NegInplace => Some(OpKind::NegInplace),
3592        Op::AbsInplace => Some(OpKind::AbsInplace),
3593        Op::SqrInplace => Some(OpKind::SqrInplace),
3594        Op::SqrtInplace => Some(OpKind::SqrtInplace),
3595        Op::RsqrtInplace => Some(OpKind::RsqrtInplace),
3596        Op::RecipInplace => Some(OpKind::RecipInplace),
3597        Op::ExpInplace => Some(OpKind::ExpInplace),
3598        Op::LogInplace => Some(OpKind::LogInplace),
3599        Op::SinInplace => Some(OpKind::SinInplace),
3600        Op::CosInplace => Some(OpKind::CosInplace),
3601        Op::SignInplace => Some(OpKind::SignInplace),
3602        Op::FloorInplace => Some(OpKind::FloorInplace),
3603        Op::CeilInplace => Some(OpKind::CeilInplace),
3604        Op::RoundInplace => Some(OpKind::RoundInplace),
3605        Op::ErfInplace => Some(OpKind::ErfInplace),
3606        Op::GeluInplace => Some(OpKind::GeluInplace),
3607        Op::ClampInplace { .. } => Some(OpKind::ClampInplace),
3608        Op::PowIInplace(_) => Some(OpKind::PowIInplace),
3609        // In-place binary variants (Add/Sub/Mul/Div/MaskedFill) and
3610        // their OpKind siblings are tracked by a parallel session and
3611        // toggle in and out of the Op enum as that work progresses.
3612        // No multi-output arm references them; nothing to map here in
3613        // the current HEAD.
3614        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::INPLACE_AFFINE => {
3615            Some(OpKind::InplaceAffine)
3616        }
3617        Op::Fused(fid, _)
3618            if *fid == fuel_graph::registry::FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY =>
3619        {
3620            Some(OpKind::FusedSoftmaxCrossEntropy)
3621        }
3622        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::CAUSAL_CONV1D => {
3623            Some(OpKind::CausalConv1d)
3624        }
3625        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SELECTIVE_SCAN => {
3626            Some(OpKind::SelectiveScan)
3627        }
3628        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SSD_CHUNK_SCAN => {
3629            Some(OpKind::SsdChunkScan)
3630        }
3631        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::NF4_MATMUL => {
3632            Some(OpKind::Nf4Matmul)
3633        }
3634        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::AWQ_MATMUL => {
3635            Some(OpKind::AwqMatmul)
3636        }
3637        // Phase 3a (post-9c): Op::Alloc + Op::ZeroFill are structural
3638        // ops dispatched directly via `WorkItemKind::Alloc` /
3639        // `WorkItemKind::ZeroFill` (no binding-table lookup).
3640        // `compile_plan` skips these.
3641        Op::Alloc { .. } | Op::ZeroFill => None,
3642        _ => None,
3643    }
3644}
3645
3646/// Build the [`OpParams`] for `node`'s op. Most ops use
3647/// `OpParams::None`; reductions / matmul / conv / slice carry their
3648/// op-specific extras here. The graph is consulted to read input
3649/// shapes (e.g. reductions need the input shape to walk the
3650/// multi-index — Storage only carries bytes + dtype).
3651///
3652/// Phase C — extends as op families migrate. Returns Err if a
3653/// graph-shape lookup fails (currently can't, but the signature is
3654/// `Result` so future cases needing validation slot in cleanly).
3655/// Encode an `f64` value into the byte pattern of `dtype`. Used by
3656/// `Op::Pad` (Constant mode) to pre-convert the fill value once at
3657/// op_params time, so the kernel itself stays dtype-agnostic.
3658fn encode_value_to_bytes(dtype: DType, value: f64) -> Result<Vec<u8>> {
3659    match dtype {
3660        DType::F32 => Ok((value as f32).to_le_bytes().to_vec()),
3661        DType::F64 => Ok(value.to_le_bytes().to_vec()),
3662        DType::BF16 => Ok(half::bf16::from_f32(value as f32).to_le_bytes().to_vec()),
3663        DType::F16 => Ok(half::f16::from_f32(value as f32).to_le_bytes().to_vec()),
3664        DType::U8 => Ok(vec![value as u8]),
3665        DType::U32 => Ok((value as u32).to_le_bytes().to_vec()),
3666        other => Err(Error::Msg(format!(
3667            "encode_value_to_bytes: dtype {other:?} not yet supported for Pad fill",
3668        ))
3669        .bt()),
3670    }
3671}
3672
3673/// Encode a typed `Scalar` to its little-endian byte representation.
3674/// Used by Op::MaskedFill so the kernel only sees bytes — never has
3675/// to know the value's dtype.
3676fn scalar_to_bytes(s: fuel_ir::Scalar) -> Vec<u8> {
3677    use fuel_ir::Scalar;
3678    match s {
3679        Scalar::U8(v) => vec![v],
3680        Scalar::I8(v) => vec![v as u8],
3681        Scalar::U32(v) => v.to_le_bytes().to_vec(),
3682        Scalar::I16(v) => v.to_le_bytes().to_vec(),
3683        Scalar::I32(v) => v.to_le_bytes().to_vec(),
3684        Scalar::I64(v) => v.to_le_bytes().to_vec(),
3685        Scalar::BF16(v) => v.to_le_bytes().to_vec(),
3686        Scalar::F16(v) => v.to_le_bytes().to_vec(),
3687        Scalar::F32(v) => v.to_le_bytes().to_vec(),
3688        Scalar::F64(v) => v.to_le_bytes().to_vec(),
3689        Scalar::Bool(b) => vec![b as u8],
3690        Scalar::F8E4M3(v) => vec![v.to_bits()],
3691        Scalar::F8E5M2(v) => vec![v.to_bits()],
3692        // OCP-MX E8M0 block scale is a raw byte on the wire (`2^(X-127)`,
3693        // decoded kernel-side); a single byte is its own LE encoding.
3694        Scalar::F8E8M0(v) => vec![v],
3695    }
3696}
3697
3698fn op_to_op_params(
3699    graph: &Graph,
3700    node: &Node,
3701    node_id: NodeId,
3702    layout_cache: &HashMap<NodeId, Layout>,
3703    sym_env: &SymEnv,
3704) -> Result<OpParams> {
3705    // Helper: read an input's layout from the compiler-thread-local
3706    // cache (which is current within the realize call), falling back
3707    // to the graph's side-table if the input wasn't visited (which
3708    // shouldn't happen in topo order, but the fallback keeps the
3709    // path safe).
3710    let input_layout = |input_id: NodeId| -> Layout {
3711        layout_cache
3712            .get(&input_id)
3713            .cloned()
3714            .unwrap_or_else(|| graph.layout(input_id))
3715    };
3716    Ok(match &node.op {
3717        // Phase 7.6 step 5 (final): legacy `Op::QMatMul` arm dropped.
3718        Op::Fused(_, fuel_graph::registry::FusedOpParams::QMatMul { quant_type, k, n }) => {
3719            // Inputs: (activations f32 [..., m, k], weight_bytes
3720            // u32-typed). Output shape (this Node's shape) is
3721            // [..., m, n]. Flatten leading dims into batch_count.
3722            if node.inputs.len() != 2 {
3723                return Err(Error::Msg(format!(
3724                    "Op::QMatMul expects 2 inputs (activations, weight_bytes), got {}",
3725                    node.inputs.len(),
3726                ))
3727                .bt());
3728            }
3729            let act_layout = input_layout(node.inputs[0]);
3730            let act_dims = act_layout.shape().dims();
3731            if act_dims.len() < 2 {
3732                return Err(Error::Msg(format!(
3733                    "Op::QMatMul: activations must be rank ≥ 2, got {act_dims:?}",
3734                ))
3735                .bt());
3736            }
3737            let m = act_dims[act_dims.len() - 2];
3738            let k_act = act_dims[act_dims.len() - 1];
3739            if k_act != *k {
3740                return Err(Error::Msg(format!(
3741                    "Op::QMatMul: activation last dim ({k_act}) must equal Op's k ({k})",
3742                ))
3743                .bt());
3744            }
3745            let batch_count: usize = act_dims[..act_dims.len() - 2].iter().product();
3746            OpParams::QMatMul {
3747                quant_type: *quant_type,
3748                batch_count,
3749                m,
3750                n: *n,
3751                k: *k,
3752            }
3753        }
3754        Op::ArgMaxDim(d) | Op::ArgMinDim(d) => {
3755            // Reuse OpParams::Reduce — same shape contract; the
3756            // single reduce dim is the argmax/argmin axis. Input
3757            // layout flows through KernelRef's `layouts[0]`.
3758            OpParams::Reduce {
3759                dims: vec![*d],
3760                keepdim: false,
3761            }
3762        }
3763        Op::SumDim(d) | Op::MaxDim(d) | Op::MinDim(d) | Op::MeanDim(d) => OpParams::Reduce {
3764            dims: vec![*d],
3765            keepdim: false,
3766        },
3767        Op::SumAll | Op::MaxAll | Op::MinAll | Op::MeanAll => {
3768            let il = input_layout(node.inputs[0]);
3769            let rank = il.shape().rank();
3770            OpParams::Reduce {
3771                dims: (0..rank).collect(),
3772                keepdim: false,
3773            }
3774        }
3775        Op::MatMul => {
3776            // Batched matmul: lhs `[..lhs_batch.., m, k]` @
3777            // rhs `[..rhs_batch.., k, n]` → out `[..lhs_batch.., m, n]`.
3778            // Per-axis the batch dims either match or follow GQA-style
3779            // divisibility (lhs_dim > rhs_dim && lhs_dim % rhs_dim == 0);
3780            // the kernel honors the latter via `rhs_idx = lhs_idx / n_rep`.
3781            if node.inputs.len() != 2 {
3782                return Err(Error::Msg(format!(
3783                    "Op::MatMul expects 2 inputs, got {}",
3784                    node.inputs.len(),
3785                ))
3786                .bt());
3787            }
3788            let lhs = input_layout(node.inputs[0]);
3789            let rhs = input_layout(node.inputs[1]);
3790            let lhs_dims = lhs.shape().dims();
3791            let rhs_dims = rhs.shape().dims();
3792            if lhs_dims.len() < 2 || rhs_dims.len() < 2 {
3793                return Err(Error::Msg(format!(
3794                    "Op::MatMul requires both inputs rank ≥ 2; got lhs={:?} rhs={:?}",
3795                    lhs_dims, rhs_dims,
3796                ))
3797                .bt());
3798            }
3799            if lhs_dims.len() != rhs_dims.len() {
3800                return Err(Error::Msg(format!(
3801                    "Op::MatMul: ranks must match (auto-broadcast happens at \
3802                     graph construction time); got lhs rank {} vs rhs rank {}",
3803                    lhs_dims.len(),
3804                    rhs_dims.len(),
3805                ))
3806                .bt());
3807            }
3808            let rank = lhs_dims.len();
3809            let batch_rank = rank - 2;
3810            // Per-axis validation: equal or GQA-divisible.
3811            for i in 0..batch_rank {
3812                let la = lhs_dims[i];
3813                let ra = rhs_dims[i];
3814                let ok = la == ra || (ra > 0 && la > ra && la % ra == 0);
3815                if !ok {
3816                    return Err(Error::Msg(format!(
3817                        "Op::MatMul: batch dim {i} disallowed combination \
3818                         (lhs={la}, rhs={ra}); must be equal or \
3819                         GQA-divisible (lhs > rhs && lhs % rhs == 0)",
3820                    ))
3821                    .bt());
3822                }
3823            }
3824            let lhs_batch_dims: Vec<usize> = lhs_dims[..batch_rank].to_vec();
3825            let rhs_batch_dims: Vec<usize> = rhs_dims[..batch_rank].to_vec();
3826            let (m, k_lhs) = (lhs_dims[rank - 2], lhs_dims[rank - 1]);
3827            let (k_rhs, n) = (rhs_dims[rank - 2], rhs_dims[rank - 1]);
3828            if k_lhs != k_rhs {
3829                return Err(Error::Msg(format!(
3830                    "Op::MatMul: contracting dims disagree — lhs trailing is \
3831                     [{m}, {k_lhs}], rhs trailing is [{k_rhs}, {n}]",
3832                ))
3833                .bt());
3834            }
3835            // Data-determined-M (sparse-MoE): a side-table row count makes
3836            // `m` the capacity and this the compute count. Dual-path,
3837            // mirroring WriteSlice: resolve in the compile-time SymEnv
3838            // (static / input-determined) now; else DEFER a producer-bound
3839            // sym to execute; else it is a genuine caller error.
3840            let m_compute = match graph.matmul_row_count(node_id) {
3841                None => MatmulM::All,
3842                Some(dyn_m) => match dyn_m.resolve(sym_env) {
3843                    Some(c) => {
3844                        if c > m {
3845                            return Err(Error::Msg(format!(
3846                                "Op::MatMul: resolved row count {c} exceeds capacity {m}",
3847                            ))
3848                            .bt());
3849                        }
3850                        MatmulM::Rows(c)
3851                    }
3852                    None => match dyn_m {
3853                        fuel_ir::DynScalar::Sym(s) if graph.binds_data_determined_sym(s) => {
3854                            MatmulM::Deferred(dyn_m)
3855                        }
3856                        _ => {
3857                            return Err(Error::Msg(format!(
3858                                "Op::MatMul: dynamic row count {dyn_m:?} is unbound in the \
3859                                 SymEnv at compile and no producer binds it (not \
3860                                 data-determined)",
3861                            ))
3862                            .bt());
3863                        }
3864                    },
3865                },
3866            };
3867            OpParams::Matmul {
3868                lhs_batch_dims,
3869                rhs_batch_dims,
3870                m,
3871                n,
3872                k: k_lhs,
3873                m_compute,
3874            }
3875        }
3876        // Phase 7.6 step 4: legacy `Op::FusedLinear` and registry-extended
3877        // `Op::Fused(FUSED_LINEAR, _)` share the same shape contract and
3878        // params encoding (reuses OpParams::Matmul). One body covers both.
3879        op if op_is_fused_linear(op) => {
3880            // Inputs: [a, b, bias]. Same shape semantics as MatMul on
3881            // a/b; bias is rank-1 [N] and broadcasts along all leading
3882            // dims. We reuse OpParams::Matmul (kernel reads bias from
3883            // inputs[2] directly).
3884            if node.inputs.len() != 3 {
3885                return Err(Error::Msg(format!(
3886                    "Op::FusedLinear expects 3 inputs (a, b, bias), got {}",
3887                    node.inputs.len(),
3888                ))
3889                .bt());
3890            }
3891            let lhs = input_layout(node.inputs[0]);
3892            let rhs = input_layout(node.inputs[1]);
3893            let bias = input_layout(node.inputs[2]);
3894            let lhs_dims = lhs.shape().dims();
3895            let rhs_dims = rhs.shape().dims();
3896            let bias_dims = bias.shape().dims();
3897            if lhs_dims.len() < 2 || rhs_dims.len() < 2 {
3898                return Err(Error::Msg(format!(
3899                    "Op::FusedLinear requires both a, b rank ≥ 2; got a={:?} b={:?}",
3900                    lhs_dims, rhs_dims,
3901                ))
3902                .bt());
3903            }
3904            if lhs_dims.len() != rhs_dims.len() {
3905                return Err(Error::Msg(format!(
3906                    "Op::FusedLinear: ranks must match (auto-broadcast happens at \
3907                     graph construction time); got a rank {} vs b rank {}",
3908                    lhs_dims.len(),
3909                    rhs_dims.len(),
3910                ))
3911                .bt());
3912            }
3913            let rank = lhs_dims.len();
3914            let batch_rank = rank - 2;
3915            for i in 0..batch_rank {
3916                let la = lhs_dims[i];
3917                let ra = rhs_dims[i];
3918                let ok = la == ra || (ra > 0 && la > ra && la % ra == 0);
3919                if !ok {
3920                    return Err(Error::Msg(format!(
3921                        "Op::FusedLinear: batch dim {i} disallowed (a={la}, b={ra})",
3922                    ))
3923                    .bt());
3924                }
3925            }
3926            let lhs_batch_dims: Vec<usize> = lhs_dims[..batch_rank].to_vec();
3927            let rhs_batch_dims: Vec<usize> = rhs_dims[..batch_rank].to_vec();
3928            let (m, k_lhs) = (lhs_dims[rank - 2], lhs_dims[rank - 1]);
3929            let (k_rhs, n) = (rhs_dims[rank - 2], rhs_dims[rank - 1]);
3930            if k_lhs != k_rhs {
3931                return Err(Error::Msg(format!(
3932                    "Op::FusedLinear: contracting dims disagree — a trailing is \
3933                     [{m}, {k_lhs}], b trailing is [{k_rhs}, {n}]",
3934                ))
3935                .bt());
3936            }
3937            if bias_dims.len() != 1 || bias_dims[0] != n {
3938                return Err(Error::Msg(format!(
3939                    "Op::FusedLinear: bias must be rank-1 [{n}], got {bias_dims:?}",
3940                ))
3941                .bt());
3942            }
3943            OpParams::Matmul {
3944                lhs_batch_dims,
3945                rhs_batch_dims,
3946                m,
3947                n,
3948                k: k_lhs,
3949                // FusedLinear is always static-M (dense linear layer).
3950                m_compute: MatmulM::All,
3951            }
3952        }
3953        // FusedSoftmaxCrossEntropy: flatten logits `[..., V]` to
3954        // `[n_rows, V]` for the kernel. n_rows is the product of all
3955        // leading dims (≥1 even for rank-1 logits, where targets are
3956        // a scalar). The kernel walks rows internally.
3957        Op::Fused(
3958            _,
3959            fuel_graph::registry::FusedOpParams::FusedSoftmaxCrossEntropy {
3960                reduction,
3961                ignore_index,
3962            },
3963        ) => {
3964            if node.inputs.len() != 2 {
3965                return Err(Error::Msg(format!(
3966                    "FusedSoftmaxCrossEntropy expects 2 inputs (logits, targets), got {}",
3967                    node.inputs.len(),
3968                ))
3969                .bt());
3970            }
3971            let logits_layout = input_layout(node.inputs[0]);
3972            let logits_dims = logits_layout.shape().dims();
3973            if logits_dims.is_empty() {
3974                return Err(Error::Msg(
3975                    "FusedSoftmaxCrossEntropy: logits must have rank ≥ 1".to_string(),
3976                )
3977                .bt());
3978            }
3979            let vocab = *logits_dims.last().unwrap();
3980            let n_rows: usize = logits_dims[..logits_dims.len() - 1]
3981                .iter()
3982                .product::<usize>()
3983                .max(1);
3984            let targets_layout = input_layout(node.inputs[1]);
3985            let target_count: usize = targets_layout
3986                .shape()
3987                .dims()
3988                .iter()
3989                .product::<usize>()
3990                .max(1);
3991            if target_count != n_rows {
3992                return Err(Error::Msg(format!(
3993                    "FusedSoftmaxCrossEntropy: targets element count {target_count} must \
3994                     equal logits row count {n_rows} (logits {logits_dims:?}, targets {:?})",
3995                    targets_layout.shape().dims(),
3996                ))
3997                .bt());
3998            }
3999            OpParams::FusedSoftmaxCrossEntropy {
4000                n_rows,
4001                vocab,
4002                reduction: *reduction,
4003                ignore_index: *ignore_index,
4004            }
4005        }
4006        // CausalConv1d: derive (batch, channels, seq_in, seq_out, kernel)
4007        // from the input layouts. x is `[batch, channels, seq_in]`
4008        // (caller pre-pads with kernel-1 zeros), weight is
4009        // `[channels, 1, kernel]`. seq_out = seq_in - (kernel - 1).
4010        Op::Fused(_, fuel_graph::registry::FusedOpParams::CausalConv1d { use_silu }) => {
4011            if node.inputs.len() != 3 {
4012                return Err(Error::Msg(format!(
4013                    "CausalConv1d expects 3 inputs (x, weight, bias), got {}",
4014                    node.inputs.len(),
4015                ))
4016                .bt());
4017            }
4018            let x_layout = input_layout(node.inputs[0]);
4019            let w_layout = input_layout(node.inputs[1]);
4020            let x_dims = x_layout.shape().dims();
4021            let w_dims = w_layout.shape().dims();
4022            if x_dims.len() != 3 {
4023                return Err(Error::Msg(format!(
4024                    "CausalConv1d: x must be rank 3 [batch, channels, seq+pad], got {x_dims:?}",
4025                ))
4026                .bt());
4027            }
4028            if w_dims.len() != 3 {
4029                return Err(Error::Msg(format!(
4030                    "CausalConv1d: weight must be rank 3 [channels, 1, kernel], got {w_dims:?}",
4031                ))
4032                .bt());
4033            }
4034            let batch = x_dims[0];
4035            let channels = x_dims[1];
4036            let seq_in = x_dims[2];
4037            let kernel = w_dims[2];
4038            if seq_in < kernel - 1 {
4039                return Err(Error::Msg(format!(
4040                    "CausalConv1d: x time dim {seq_in} must be ≥ kernel-1 = {} \
4041                     (caller must pre-pad with kernel-1 zeros)",
4042                    kernel - 1,
4043                ))
4044                .bt());
4045            }
4046            let seq_out = seq_in - (kernel - 1);
4047            OpParams::CausalConv1d {
4048                batch,
4049                channels,
4050                seq_in,
4051                seq_out,
4052                kernel,
4053                use_silu: *use_silu,
4054            }
4055        }
4056        // SelectiveScan: derive (batch, seqlen, dim, dstate) from the
4057        // input layouts. u: [batch, seqlen, dim]; a: [dim, dstate].
4058        Op::Fused(_, fuel_graph::registry::FusedOpParams::SelectiveScan { delta_softplus }) => {
4059            if node.inputs.len() != 5 {
4060                return Err(Error::Msg(format!(
4061                    "SelectiveScan expects 5 inputs (u, delta, a, b, c), got {}",
4062                    node.inputs.len(),
4063                ))
4064                .bt());
4065            }
4066            let u_layout = input_layout(node.inputs[0]);
4067            let a_layout = input_layout(node.inputs[2]);
4068            let u_dims = u_layout.shape().dims();
4069            let a_dims = a_layout.shape().dims();
4070            if u_dims.len() != 3 {
4071                return Err(Error::Msg(format!(
4072                    "SelectiveScan: u must be rank 3 [batch, seqlen, dim], got {u_dims:?}",
4073                ))
4074                .bt());
4075            }
4076            if a_dims.len() != 2 {
4077                return Err(Error::Msg(format!(
4078                    "SelectiveScan: a must be rank 2 [dim, dstate], got {a_dims:?}",
4079                ))
4080                .bt());
4081            }
4082            let batch = u_dims[0];
4083            let seqlen = u_dims[1];
4084            let dim = u_dims[2];
4085            let dstate = a_dims[1];
4086            if a_dims[0] != dim {
4087                return Err(Error::Msg(format!(
4088                    "SelectiveScan: a's first dim {} must equal dim {dim}",
4089                    a_dims[0],
4090                ))
4091                .bt());
4092            }
4093            OpParams::SelectiveScan {
4094                batch,
4095                seqlen,
4096                dim,
4097                dstate,
4098                delta_softplus: *delta_softplus,
4099            }
4100        }
4101        // SsdChunkScan: derive (batch, seqlen, heads, head_dim,
4102        // state_dim) from x and b layouts. x: [batch, seqlen, heads,
4103        // head_dim]; b: [batch, seqlen, heads, state_dim].
4104        Op::Fused(_, fuel_graph::registry::FusedOpParams::SsdChunkScan { chunk_size }) => {
4105            if node.inputs.len() != 5 {
4106                return Err(Error::Msg(format!(
4107                    "SsdChunkScan expects 5 inputs (x, dt, a, b, c), got {}",
4108                    node.inputs.len(),
4109                ))
4110                .bt());
4111            }
4112            let x_layout = input_layout(node.inputs[0]);
4113            let b_layout = input_layout(node.inputs[3]);
4114            let x_dims = x_layout.shape().dims();
4115            let b_dims = b_layout.shape().dims();
4116            if x_dims.len() != 4 {
4117                return Err(Error::Msg(format!(
4118                    "SsdChunkScan: x must be rank 4 [batch, seqlen, heads, head_dim], got {x_dims:?}",
4119                ))
4120                .bt());
4121            }
4122            if b_dims.len() != 4 {
4123                return Err(Error::Msg(format!(
4124                    "SsdChunkScan: b must be rank 4 [batch, seqlen, heads, state_dim], got {b_dims:?}",
4125                ))
4126                .bt());
4127            }
4128            let batch = x_dims[0];
4129            let seqlen = x_dims[1];
4130            let heads = x_dims[2];
4131            let head_dim = x_dims[3];
4132            let state_dim = b_dims[3];
4133            OpParams::SsdChunkScan {
4134                batch,
4135                seqlen,
4136                heads,
4137                head_dim,
4138                state_dim,
4139                chunk_size: *chunk_size,
4140            }
4141        }
4142        // Nf4Matmul: derive (batch, m, n, k) from activations + w_packed
4143        // layouts. activations: [..., m, k] (leading dims flatten into
4144        // batch); w_packed: [n, k/2] U8.
4145        Op::Fused(_, fuel_graph::registry::FusedOpParams::Nf4Matmul { block_size }) => {
4146            if node.inputs.len() != 3 {
4147                return Err(Error::Msg(format!(
4148                    "Nf4Matmul expects 3 inputs (activations, w_packed, absmax), got {}",
4149                    node.inputs.len(),
4150                ))
4151                .bt());
4152            }
4153            let a_layout = input_layout(node.inputs[0]);
4154            let w_layout = input_layout(node.inputs[1]);
4155            let a_dims = a_layout.shape().dims();
4156            let w_dims = w_layout.shape().dims();
4157            if a_dims.len() < 2 {
4158                return Err(Error::Msg(format!(
4159                    "Nf4Matmul: activations must be rank ≥ 2, got {a_dims:?}",
4160                ))
4161                .bt());
4162            }
4163            if w_dims.len() != 2 {
4164                return Err(Error::Msg(format!(
4165                    "Nf4Matmul: w_packed must be rank 2 [n, k/2], got {w_dims:?}",
4166                ))
4167                .bt());
4168            }
4169            let m = a_dims[a_dims.len() - 2];
4170            let k = a_dims[a_dims.len() - 1];
4171            let n = w_dims[0];
4172            let batch: usize = a_dims[..a_dims.len() - 2].iter().product::<usize>().max(1);
4173            if k % 2 != 0 {
4174                return Err(Error::Msg(format!(
4175                    "Nf4Matmul: k={k} must be even (w_packed holds 2 nibbles per byte along k)",
4176                ))
4177                .bt());
4178            }
4179            if k % *block_size != 0 {
4180                return Err(Error::Msg(format!(
4181                    "Nf4Matmul: k={k} must be a multiple of block_size={block_size}",
4182                ))
4183                .bt());
4184            }
4185            if w_dims[1] != k / 2 {
4186                return Err(Error::Msg(format!(
4187                    "Nf4Matmul: w_packed second dim {} must equal k/2 = {}",
4188                    w_dims[1],
4189                    k / 2,
4190                ))
4191                .bt());
4192            }
4193            OpParams::Nf4Matmul {
4194                batch,
4195                m,
4196                n,
4197                k,
4198                block_size: *block_size,
4199            }
4200        }
4201        // AwqMatmul: (batch, m, n, k) from activations [..., m, k] and the
4202        // kernel-layout weight [n, k/8]; the padded zeros/scales widths are the
4203        // op's own build-time invariant (checked by `awq_matmul`).
4204        Op::Fused(
4205            _,
4206            fuel_graph::registry::FusedOpParams::AwqMatmul {
4207                group_size,
4208                split_k_iters,
4209            },
4210        ) => {
4211            if node.inputs.len() != 4 {
4212                return Err(Error::Msg(format!(
4213                    "AwqMatmul expects 4 inputs (activations, weight, zeros, scales), got {}",
4214                    node.inputs.len(),
4215                ))
4216                .bt());
4217            }
4218            let a_layout = input_layout(node.inputs[0]);
4219            let w_layout = input_layout(node.inputs[1]);
4220            let a_dims = a_layout.shape().dims();
4221            let w_dims = w_layout.shape().dims();
4222            if a_dims.len() < 2 {
4223                return Err(Error::Msg(format!(
4224                    "AwqMatmul: activations must be rank ≥ 2, got {a_dims:?}",
4225                ))
4226                .bt());
4227            }
4228            if w_dims.len() != 2 {
4229                return Err(Error::Msg(format!(
4230                    "AwqMatmul: weight must be rank 2 [n, k/8], got {w_dims:?}",
4231                ))
4232                .bt());
4233            }
4234            let m = a_dims[a_dims.len() - 2];
4235            let k = a_dims[a_dims.len() - 1];
4236            let n = w_dims[0];
4237            let batch: usize = a_dims[..a_dims.len() - 2].iter().product::<usize>().max(1);
4238            if k % 8 != 0 || w_dims[1] != k / 8 {
4239                return Err(Error::Msg(format!(
4240                    "AwqMatmul: weight second dim {} must equal k/8 for k={k} (a multiple of 8)",
4241                    w_dims[1],
4242                ))
4243                .bt());
4244            }
4245            OpParams::AwqMatmul {
4246                batch,
4247                m,
4248                n,
4249                k,
4250                group_size: *group_size,
4251                split_k_iters: *split_k_iters,
4252            }
4253        }
4254        // Phase 7.6 step 3: SoftmaxLastDim flows through
4255        // `Op::Fused(FusedOps::SOFTMAX_LAST_DIM, _)`. The
4256        // SOFTMAX_LAST_DIM_BACKWARD variant added in step 6
4257        // follow-up shares the same `outer × last_dim` shape
4258        // contract (input 0 is `y` for forward / forward-output
4259        // for backward; both rank-≥1 with last-dim as the
4260        // reduction axis).
4261        op if op_is_softmax_last_dim(op)
4262            || matches!(op, Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM_BACKWARD) =>
4263        {
4264            let il = input_layout(node.inputs[0]);
4265            let dims = il.shape().dims();
4266            if dims.is_empty() {
4267                return Err(Error::Msg("Op::SoftmaxLastDim requires rank ≥ 1".to_string()).bt());
4268            }
4269            let last_dim = *dims.last().unwrap();
4270            let outer_count: usize = dims[..dims.len() - 1].iter().product();
4271            OpParams::SoftmaxLastDim {
4272                outer_count,
4273                last_dim,
4274            }
4275        }
4276        Op::Flip { dim } => {
4277            // Single input. Precompute the flat-3-axis split
4278            // (outer × dim × inner) from the input shape.
4279            if node.inputs.len() != 1 {
4280                return Err(Error::Msg(format!(
4281                    "Op::Flip expects 1 input, got {}",
4282                    node.inputs.len(),
4283                ))
4284                .bt());
4285            }
4286            let in_layout = input_layout(node.inputs[0]);
4287            let in_dims = in_layout.shape().dims();
4288            if *dim >= in_dims.len() {
4289                return Err(Error::Msg(format!(
4290                    "Op::Flip: dim {dim} out of range for rank {}",
4291                    in_dims.len(),
4292                ))
4293                .bt());
4294            }
4295            let outer_count: usize = in_dims[..*dim].iter().product();
4296            let dim_size = in_dims[*dim];
4297            let inner_count: usize = in_dims[*dim + 1..].iter().product();
4298            OpParams::Flip {
4299                outer_count,
4300                dim_size,
4301                inner_count,
4302                axis: *dim,
4303            }
4304        }
4305        Op::Roll { dim, shift } => {
4306            if node.inputs.len() != 1 {
4307                return Err(Error::Msg(format!(
4308                    "Op::Roll expects 1 input, got {}",
4309                    node.inputs.len(),
4310                ))
4311                .bt());
4312            }
4313            let in_layout = input_layout(node.inputs[0]);
4314            let in_dims = in_layout.shape().dims();
4315            if *dim >= in_dims.len() {
4316                return Err(Error::Msg(format!(
4317                    "Op::Roll: dim {dim} out of range for rank {}",
4318                    in_dims.len(),
4319                ))
4320                .bt());
4321            }
4322            let outer_count: usize = in_dims[..*dim].iter().product();
4323            let dim_size = in_dims[*dim];
4324            let inner_count: usize = in_dims[*dim + 1..].iter().product();
4325            OpParams::Roll {
4326                outer_count,
4327                dim_size,
4328                inner_count,
4329                shift: *shift,
4330                axis: *dim,
4331            }
4332        }
4333        Op::CumSum { dim } => {
4334            if node.inputs.len() != 1 {
4335                return Err(Error::Msg(format!(
4336                    "Op::CumSum expects 1 input, got {}",
4337                    node.inputs.len(),
4338                ))
4339                .bt());
4340            }
4341            let in_layout = input_layout(node.inputs[0]);
4342            let in_dims = in_layout.shape().dims();
4343            if *dim >= in_dims.len() {
4344                return Err(Error::Msg(format!(
4345                    "Op::CumSum: dim {dim} out of range for rank {}",
4346                    in_dims.len(),
4347                ))
4348                .bt());
4349            }
4350            let outer_count: usize = in_dims[..*dim].iter().product();
4351            let dim_size = in_dims[*dim];
4352            let inner_count: usize = in_dims[*dim + 1..].iter().product();
4353            OpParams::CumSum {
4354                outer_count,
4355                dim_size,
4356                inner_count,
4357                axis: *dim,
4358            }
4359        }
4360        Op::Triu { diagonal } | Op::Tril { diagonal } => {
4361            if node.inputs.len() != 1 {
4362                return Err(Error::Msg(format!(
4363                    "Op::Triu/Tril expects 1 input, got {}",
4364                    node.inputs.len(),
4365                ))
4366                .bt());
4367            }
4368            let in_layout = input_layout(node.inputs[0]);
4369            let in_dims = in_layout.shape().dims();
4370            if in_dims.len() < 2 {
4371                return Err(Error::Msg(format!(
4372                    "Op::Triu/Tril requires rank >= 2, got {}",
4373                    in_dims.len(),
4374                ))
4375                .bt());
4376            }
4377            let rows = in_dims[in_dims.len() - 2];
4378            let cols = in_dims[in_dims.len() - 1];
4379            let batch_count: usize = in_dims[..in_dims.len() - 2]
4380                .iter()
4381                .product::<usize>()
4382                .max(1);
4383            OpParams::Triangular {
4384                batch_count,
4385                rows,
4386                cols,
4387                diagonal: *diagonal,
4388            }
4389        }
4390        Op::LogSoftmaxLastDim => {
4391            if node.inputs.len() != 1 {
4392                return Err(Error::Msg(format!(
4393                    "Op::LogSoftmaxLastDim expects 1 input, got {}",
4394                    node.inputs.len(),
4395                ))
4396                .bt());
4397            }
4398            let in_layout = input_layout(node.inputs[0]);
4399            let in_dims = in_layout.shape().dims();
4400            if in_dims.is_empty() {
4401                return Err(Error::Msg("Op::LogSoftmaxLastDim requires rank ≥ 1".to_string()).bt());
4402            }
4403            let last_dim = *in_dims.last().unwrap();
4404            let outer_count: usize = in_dims[..in_dims.len() - 1].iter().product();
4405            OpParams::LogSoftmaxLastDim {
4406                outer_count,
4407                last_dim,
4408            }
4409        }
4410        Op::LogSoftmaxLastDimBackward => {
4411            // Inputs: (forward_output_y, upstream_grad). Same shape contract
4412            // as SoftmaxLastDimBackward — last-dim row-wise dispatch.
4413            if node.inputs.len() != 2 {
4414                return Err(Error::Msg(format!(
4415                    "Op::LogSoftmaxLastDimBackward expects 2 inputs, got {}",
4416                    node.inputs.len(),
4417                ))
4418                .bt());
4419            }
4420            let in_layout = input_layout(node.inputs[0]);
4421            let in_dims = in_layout.shape().dims();
4422            if in_dims.is_empty() {
4423                return Err(Error::Msg(
4424                    "Op::LogSoftmaxLastDimBackward requires rank ≥ 1".to_string(),
4425                )
4426                .bt());
4427            }
4428            let last_dim = *in_dims.last().unwrap();
4429            let outer_count: usize = in_dims[..in_dims.len() - 1].iter().product();
4430            OpParams::LogSoftmaxLastDim {
4431                outer_count,
4432                last_dim,
4433            }
4434        }
4435        Op::MaskedFill { value } => {
4436            if node.inputs.len() != 2 {
4437                return Err(Error::Msg(format!(
4438                    "Op::MaskedFill expects 2 inputs (x, mask), got {}",
4439                    node.inputs.len(),
4440                ))
4441                .bt());
4442            }
4443            let fill_bytes = scalar_to_bytes(*value);
4444            OpParams::MaskedFill { fill_bytes }
4445        }
4446        // Op::MaskedFillInplace tracked by the parallel in-place
4447        // binary family session — not in HEAD's Op enum right now.
4448        Op::PadBackward {
4449            in_shape,
4450            padding,
4451            mode,
4452        } => {
4453            // Single input is the upstream gradient; output is the
4454            // input gradient (shape == `in_shape`).
4455            if node.inputs.len() != 1 {
4456                return Err(Error::Msg(format!(
4457                    "Op::PadBackward expects 1 input, got {}",
4458                    node.inputs.len(),
4459                ))
4460                .bt());
4461            }
4462            let in_dims: Vec<usize> = in_shape.dims().to_vec();
4463            // Output of the original forward Pad is the input shape
4464            // of the backward (== upstream's shape).
4465            let out_dims: Vec<usize> = in_dims
4466                .iter()
4467                .zip(padding.iter())
4468                .map(|(&d, &(b, a))| d + b + a)
4469                .collect();
4470            let mode_tag: u8 = match mode {
4471                fuel_graph::PadMode::Constant => 0,
4472                fuel_graph::PadMode::Reflect => 1,
4473                fuel_graph::PadMode::Replicate => 2,
4474            };
4475            OpParams::PadBackward {
4476                in_shape: in_dims,
4477                out_shape: out_dims,
4478                padding: padding.clone(),
4479                mode_tag,
4480            }
4481        }
4482        Op::Pad {
4483            padding,
4484            mode,
4485            value,
4486        } => {
4487            if node.inputs.len() != 1 {
4488                return Err(Error::Msg(format!(
4489                    "Op::Pad expects 1 input, got {}",
4490                    node.inputs.len(),
4491                ))
4492                .bt());
4493            }
4494            let in_layout = input_layout(node.inputs[0]);
4495            let in_dims: Vec<usize> = in_layout.shape().dims().to_vec();
4496            if padding.len() != in_dims.len() {
4497                return Err(Error::Msg(format!(
4498                    "Op::Pad: padding.len() ({}) != input rank ({})",
4499                    padding.len(),
4500                    in_dims.len(),
4501                ))
4502                .bt());
4503            }
4504            let out_dims: Vec<usize> = in_dims
4505                .iter()
4506                .zip(padding.iter())
4507                .map(|(&d, &(b, a))| d + b + a)
4508                .collect();
4509            let mode_tag: u8 = match mode {
4510                fuel_graph::PadMode::Constant => 0,
4511                fuel_graph::PadMode::Reflect => 1,
4512                fuel_graph::PadMode::Replicate => 2,
4513            };
4514            // Encode fill value as bytes for the output dtype. The
4515            // kernel is dtype-agnostic — it just memcopies the
4516            // pattern. Conversion happens once here per node, not
4517            // per element in the kernel.
4518            let fill_bytes = encode_value_to_bytes(node.dtype, *value)?;
4519            OpParams::Pad {
4520                in_shape: in_dims,
4521                out_shape: out_dims,
4522                padding: padding.clone(),
4523                mode_tag,
4524                fill_bytes,
4525            }
4526        }
4527        Op::IndexAdd { dim } => {
4528            // Inputs: (base, indices, src). All same dtype except
4529            // indices is U32. Output shape == base shape.
4530            if node.inputs.len() != 3 {
4531                return Err(Error::Msg(format!(
4532                    "Op::IndexAdd expects 3 inputs (base, indices, src), got {}",
4533                    node.inputs.len(),
4534                ))
4535                .bt());
4536            }
4537            let base_layout = input_layout(node.inputs[0]);
4538            let idx_layout = input_layout(node.inputs[1]);
4539            let src_layout = input_layout(node.inputs[2]);
4540            let base_dims = base_layout.shape().dims();
4541            let idx_dims = idx_layout.shape().dims();
4542            let src_dims = src_layout.shape().dims();
4543            if *dim >= base_dims.len() {
4544                return Err(Error::Msg(format!(
4545                    "Op::IndexAdd: dim {dim} out of range for base rank {}",
4546                    base_dims.len(),
4547                ))
4548                .bt());
4549            }
4550            if idx_dims.len() != 1 {
4551                return Err(Error::Msg(format!(
4552                    "Op::IndexAdd: indices must be rank 1, got {idx_dims:?}",
4553                ))
4554                .bt());
4555            }
4556            if base_dims.len() != src_dims.len() {
4557                return Err(Error::Msg(format!(
4558                    "Op::IndexAdd: base rank ({}) != src rank ({})",
4559                    base_dims.len(),
4560                    src_dims.len(),
4561                ))
4562                .bt());
4563            }
4564            let outer_count: usize = base_dims[..*dim].iter().product();
4565            let base_dim_size = base_dims[*dim];
4566            let inner_count: usize = base_dims[*dim + 1..].iter().product();
4567            let n_indices = idx_dims[0];
4568            OpParams::IndexAdd {
4569                outer_count,
4570                base_dim_size,
4571                n_indices,
4572                inner_count,
4573            }
4574        }
4575        Op::ScatterAdd { dim } => {
4576            if node.inputs.len() != 3 {
4577                return Err(Error::Msg(format!(
4578                    "Op::ScatterAdd expects 3 inputs (base, indices, src), got {}",
4579                    node.inputs.len(),
4580                ))
4581                .bt());
4582            }
4583            let base_layout = input_layout(node.inputs[0]);
4584            let src_layout = input_layout(node.inputs[2]);
4585            let base_shape: Vec<usize> = base_layout.shape().dims().to_vec();
4586            let src_shape: Vec<usize> = src_layout.shape().dims().to_vec();
4587            if base_shape.len() != src_shape.len() {
4588                return Err(Error::Msg(format!(
4589                    "Op::ScatterAdd: base rank ({}) != src rank ({})",
4590                    base_shape.len(),
4591                    src_shape.len(),
4592                ))
4593                .bt());
4594            }
4595            if *dim >= base_shape.len() {
4596                return Err(Error::Msg(format!(
4597                    "Op::ScatterAdd: dim {dim} out of range for rank {}",
4598                    base_shape.len(),
4599                ))
4600                .bt());
4601            }
4602            OpParams::ScatterAdd {
4603                base_shape,
4604                src_shape,
4605                dim: *dim,
4606            }
4607        }
4608        // Phase 7.6 step 5: Rope routes through the registry; the
4609        // legacy `Op::Rope` arm was retired with the variant.
4610        Op::Fused(_, fuel_graph::registry::FusedOpParams::Rope) => {
4611            // Inputs: (x, cos, sin). x is [..., seq, head_dim];
4612            // cos/sin are [seq, head_dim] (validated at graph build).
4613            if node.inputs.len() != 3 {
4614                return Err(Error::Msg(format!(
4615                    "Op::Rope expects 3 inputs (x, cos, sin), got {}",
4616                    node.inputs.len(),
4617                ))
4618                .bt());
4619            }
4620            let x_layout = input_layout(node.inputs[0]);
4621            let x_dims = x_layout.shape().dims();
4622            if x_dims.len() < 2 {
4623                return Err(
4624                    Error::Msg(format!("Op::Rope: x must have rank ≥ 2, got {x_dims:?}",)).bt(),
4625                );
4626            }
4627            let head_dim = *x_dims.last().unwrap();
4628            let seq = x_dims[x_dims.len() - 2];
4629            let outer_count: usize = x_dims[..x_dims.len() - 2].iter().product();
4630            OpParams::Rope {
4631                outer_count,
4632                seq,
4633                head_dim,
4634            }
4635        }
4636        Op::Gather { dim } => {
4637            // inputs[0] = source, inputs[1] = U32 indices (same rank).
4638            if node.inputs.len() != 2 {
4639                return Err(Error::Msg(format!(
4640                    "Op::Gather expects 2 inputs (source, indices), got {}",
4641                    node.inputs.len(),
4642                ))
4643                .bt());
4644            }
4645            let src_layout = input_layout(node.inputs[0]);
4646            let idx_layout = input_layout(node.inputs[1]);
4647            let source_shape: Vec<usize> = src_layout.shape().dims().to_vec();
4648            let output_shape: Vec<usize> = idx_layout.shape().dims().to_vec();
4649            if source_shape.len() != output_shape.len() {
4650                return Err(Error::Msg(format!(
4651                    "Op::Gather: source rank ({}) != indices rank ({})",
4652                    source_shape.len(),
4653                    output_shape.len(),
4654                ))
4655                .bt());
4656            }
4657            if *dim >= source_shape.len() {
4658                return Err(Error::Msg(format!(
4659                    "Op::Gather: dim {dim} out of range for rank {}",
4660                    source_shape.len(),
4661                ))
4662                .bt());
4663            }
4664            OpParams::Gather {
4665                source_shape,
4666                output_shape,
4667                dim: *dim,
4668            }
4669        }
4670        Op::NonZeroIndices { count_sym } => {
4671            // inputs[0] = x (the value tensor). capacity == x.elem_count();
4672            // the bundled output is [indices [capacity] U32 ; count [1] U32].
4673            if node.inputs.len() != 1 {
4674                return Err(Error::Msg(format!(
4675                    "Op::NonZeroIndices expects 1 input, got {}",
4676                    node.inputs.len(),
4677                ))
4678                .bt());
4679            }
4680            let x_layout = input_layout(node.inputs[0]);
4681            let capacity = x_layout.shape().elem_count();
4682            OpParams::NonZeroIndices {
4683                capacity,
4684                count_sym: *count_sym,
4685            }
4686        }
4687        Op::IndexSelect { dim } => {
4688            // inputs[0] = source, inputs[1] = U32 indices (rank 1).
4689            if node.inputs.len() != 2 {
4690                return Err(Error::Msg(format!(
4691                    "Op::IndexSelect expects 2 inputs (source, indices), got {}",
4692                    node.inputs.len(),
4693                ))
4694                .bt());
4695            }
4696            let src_layout = input_layout(node.inputs[0]);
4697            let idx_layout = input_layout(node.inputs[1]);
4698            let src_dims = src_layout.shape().dims();
4699            let idx_dims = idx_layout.shape().dims();
4700            if *dim >= src_dims.len() {
4701                return Err(Error::Msg(format!(
4702                    "Op::IndexSelect: dim {dim} out of range for source rank {}",
4703                    src_dims.len(),
4704                ))
4705                .bt());
4706            }
4707            if idx_dims.len() != 1 {
4708                return Err(Error::Msg(format!(
4709                    "Op::IndexSelect: indices must be rank 1, got shape {idx_dims:?}",
4710                ))
4711                .bt());
4712            }
4713            let outer_count: usize = src_dims[..*dim].iter().product();
4714            let source_dim_size = src_dims[*dim];
4715            let inner_count: usize = src_dims[*dim + 1..].iter().product();
4716            let n_indices = idx_dims[0];
4717            OpParams::IndexSelect {
4718                outer_count,
4719                source_dim_size,
4720                n_indices,
4721                inner_count,
4722            }
4723        }
4724        // Phase 7.6 step 5: legacy `Op::RmsNormLastDim` /
4725        // `Op::LayerNormLastDim` arms retired with the variants;
4726        // both now route through `Op::Fused(NORM_LAST_DIM, _)`.
4727        // Step 6 follow-up extends this arm to also cover the
4728        // backward variants (same outer × last_dim + eps geometry).
4729        Op::Fused(fid, params)
4730            if *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM
4731                || *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM
4732                || *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM_BACKWARD
4733                || *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM_BACKWARD =>
4734        {
4735            let eps = match params {
4736                fuel_graph::registry::FusedOpParams::RmsNormLastDim { eps } => *eps,
4737                fuel_graph::registry::FusedOpParams::LayerNormLastDim { eps } => *eps,
4738                fuel_graph::registry::FusedOpParams::RmsNormLastDimBackward { eps } => *eps,
4739                fuel_graph::registry::FusedOpParams::LayerNormLastDimBackward { eps } => *eps,
4740                _ => {
4741                    return Err(Error::Msg(format!(
4742                        "Op::Fused(NORM_LAST_DIM[_BACKWARD], _) expected \
4743                     RmsNormLastDim[Backward] or LayerNormLastDim[Backward] params, got {params:?}",
4744                    ))
4745                    .bt());
4746                }
4747            };
4748            let il = input_layout(node.inputs[0]);
4749            let dims = il.shape().dims();
4750            if dims.is_empty() {
4751                return Err(Error::Msg(
4752                    "Op::Fused(NORM_LAST_DIM[_BACKWARD], _) requires rank ≥ 1".to_string(),
4753                )
4754                .bt());
4755            }
4756            let last_dim = *dims.last().unwrap();
4757            let outer_count: usize = dims[..dims.len() - 1].iter().product();
4758            OpParams::NormLastDim {
4759                outer_count,
4760                last_dim,
4761                eps,
4762            }
4763        }
4764        // ReduceMaxToBackward: shape pair via the new
4765        // OpParams::ReduceMaxToBackward variant. x's shape is
4766        // `input_shape`; upstream's shape is `output_shape`.
4767        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::REDUCE_MAX_TO_BACKWARD => {
4768            if node.inputs.len() != 2 {
4769                return Err(Error::Msg(format!(
4770                    "Op::Fused(REDUCE_MAX_TO_BACKWARD) expects 2 inputs, got {}",
4771                    node.inputs.len(),
4772                ))
4773                .bt());
4774            }
4775            let x_layout = input_layout(node.inputs[0]);
4776            let up_layout = input_layout(node.inputs[1]);
4777            let input_shape: Vec<usize> = x_layout.shape().dims().to_vec();
4778            let output_shape: Vec<usize> = up_layout.shape().dims().to_vec();
4779            OpParams::ReduceMaxToBackward {
4780                input_shape,
4781                output_shape,
4782            }
4783        }
4784        Op::Concat { dim } => {
4785            // Output's shape: [..., total_dim, ...]. Compute outer
4786            // and inner counts from output_shape[..dim] and
4787            // [dim+1..]; per-input dim sizes from each input's
4788            // layout shape at index `dim`.
4789            if node.inputs.is_empty() {
4790                return Err(Error::Msg("Op::Concat requires at least 1 input".to_string()).bt());
4791            }
4792            let out_dims = node.shape.dims();
4793            if *dim >= out_dims.len() {
4794                return Err(Error::Msg(format!(
4795                    "Op::Concat: dim {dim} out of range for output rank {}",
4796                    out_dims.len(),
4797                ))
4798                .bt());
4799            }
4800            let outer_count: usize = out_dims[..*dim].iter().product();
4801            let inner_count: usize = out_dims[*dim + 1..].iter().product();
4802            let mut input_dim_sizes: Vec<usize> = Vec::with_capacity(node.inputs.len());
4803            for in_id in &node.inputs {
4804                let il = input_layout(*in_id);
4805                let il_dims = il.shape().dims();
4806                if *dim >= il_dims.len() {
4807                    return Err(Error::Msg(format!(
4808                        "Op::Concat: input {in_id:?} has rank {} but concat dim is {dim}",
4809                        il_dims.len(),
4810                    ))
4811                    .bt());
4812                }
4813                input_dim_sizes.push(il_dims[*dim]);
4814            }
4815            OpParams::Concat {
4816                outer_count,
4817                input_dim_sizes,
4818                inner_count,
4819                axis: *dim,
4820            }
4821        }
4822        Op::AddScalar(c) => OpParams::Affine { mul: 1.0, add: *c },
4823        Op::MulScalar(c) => OpParams::Affine { mul: *c, add: 0.0 },
4824        Op::Clamp { min, max } => OpParams::Clamp {
4825            min: *min,
4826            max: *max,
4827        },
4828        Op::PowI(exp) => OpParams::PowI { exp: *exp },
4829        Op::ClampInplace { min, max } => OpParams::Clamp {
4830            min: *min,
4831            max: *max,
4832        },
4833        Op::PowIInplace(exp) => OpParams::PowI { exp: *exp },
4834        // PowI backward — `(x, upstream) → grad_x = exp · x^(exp-1) ·
4835        // upstream`. Pulls the same `exp` as the forward through
4836        // FusedOpParams::PowIBackward (autograd carries it across).
4837        Op::Fused(_, fuel_graph::registry::FusedOpParams::PowIBackward { exp }) => {
4838            OpParams::PowI { exp: *exp }
4839        }
4840        // In-place affine (Phase 3 of the in-place ops infrastructure):
4841        // reuse the existing `OpParams::Affine` payload — the kernel
4842        // side doesn't care whether the destination is fresh or aliases
4843        // the input; the structural decision lives in the executor's
4844        // dedicated `WorkItemKind::InplaceKernel` arm.
4845        Op::Fused(_, fuel_graph::registry::FusedOpParams::InplaceAffine { mul, add }) => {
4846            OpParams::Affine {
4847                mul: *mul,
4848                add: *add,
4849            }
4850        }
4851        // Phase 7.6 step 5: legacy `Op::Conv2D` arm retired with the
4852        // variant; Conv2D routes through `Op::Fused(CONV2D, _)`.
4853        Op::Fused(
4854            _,
4855            fuel_graph::registry::FusedOpParams::Conv2D {
4856                stride,
4857                padding,
4858                groups,
4859            },
4860        ) => {
4861            // Inputs[0] = x [N, Cin, Hin, Win]; inputs[1] = weight
4862            // [Cout, Cin/groups, Kh, Kw]; inputs[2] (optional) = bias [Cout].
4863            // Output (this Node's shape) = [N, Cout, Hout, Wout].
4864            if node.inputs.len() != 2 && node.inputs.len() != 3 {
4865                return Err(Error::Msg(format!(
4866                    "Op::Conv2D expects 2 or 3 inputs, got {}",
4867                    node.inputs.len(),
4868                ))
4869                .bt());
4870            }
4871            let x_layout = input_layout(node.inputs[0]);
4872            let w_layout = input_layout(node.inputs[1]);
4873            let x_dims = x_layout.shape().dims();
4874            let w_dims = w_layout.shape().dims();
4875            if x_dims.len() != 4 || w_dims.len() != 4 {
4876                return Err(Error::Msg(format!(
4877                    "Op::Conv2D requires rank-4 x and weight; got x={x_dims:?} w={w_dims:?}",
4878                ))
4879                .bt());
4880            }
4881            let out_dims = node.shape.dims();
4882            if out_dims.len() != 4 {
4883                return Err(Error::Msg(format!(
4884                    "Op::Conv2D output must be rank 4, got {out_dims:?}",
4885                ))
4886                .bt());
4887            }
4888            let x_shape = [x_dims[0], x_dims[1], x_dims[2], x_dims[3]];
4889            let w_shape = [w_dims[0], w_dims[1], w_dims[2], w_dims[3]];
4890            let out_shape = [out_dims[0], out_dims[1], out_dims[2], out_dims[3]];
4891            OpParams::Conv2D {
4892                x_shape,
4893                w_shape,
4894                out_shape,
4895                stride: *stride,
4896                padding: *padding,
4897                dilation: (1, 1),
4898                groups: *groups,
4899            }
4900        }
4901        // Phase 7.6 step 5 (final): legacy `Op::PagedAttn` arm dropped.
4902        Op::Fused(
4903            _,
4904            fuel_graph::registry::FusedOpParams::PagedAttn {
4905                softmax_scale,
4906                block_size,
4907                softcap,
4908            },
4909        ) => {
4910            // Inputs[0]=q [B,Hq,Sq,D], inputs[1]=k_cache [num_blocks,
4911            // block_size, Hkv, D], inputs[2]=v_cache same shape,
4912            // inputs[3]=block_table [B, max_blocks_per_seq] U32,
4913            // inputs[4]=context_lens [B] U32, inputs[5]=alibi [Hq] (optional).
4914            if node.inputs.len() != 5 && node.inputs.len() != 6 {
4915                return Err(Error::Msg(format!(
4916                    "Op::PagedAttn expects 5 or 6 inputs, got {}",
4917                    node.inputs.len(),
4918                ))
4919                .bt());
4920            }
4921            let q_layout = input_layout(node.inputs[0]);
4922            let kc_layout = input_layout(node.inputs[1]);
4923            let vc_layout = input_layout(node.inputs[2]);
4924            let bt_layout = input_layout(node.inputs[3]);
4925            let q_dims = q_layout.shape().dims();
4926            let kc_dims = kc_layout.shape().dims();
4927            let vc_dims = vc_layout.shape().dims();
4928            let bt_dims = bt_layout.shape().dims();
4929            if q_dims.len() != 4 || kc_dims.len() != 4 || vc_dims.len() != 4 {
4930                return Err(Error::Msg(format!(
4931                    "Op::PagedAttn requires rank-4 q/k_cache/v_cache; \
4932                     got q={q_dims:?} k_cache={kc_dims:?} v_cache={vc_dims:?}",
4933                ))
4934                .bt());
4935            }
4936            if kc_dims != vc_dims {
4937                return Err(Error::Msg(format!(
4938                    "Op::PagedAttn: k_cache {kc_dims:?} and v_cache {vc_dims:?} must match",
4939                ))
4940                .bt());
4941            }
4942            if bt_dims.len() != 2 {
4943                return Err(Error::Msg(format!(
4944                    "Op::PagedAttn: block_table must be rank 2 [B, max_blocks_per_seq], got {bt_dims:?}",
4945                ))
4946                .bt());
4947            }
4948            if kc_dims[1] != *block_size {
4949                return Err(Error::Msg(format!(
4950                    "Op::PagedAttn: k_cache block_size dim ({}) must equal Op's block_size ({})",
4951                    kc_dims[1], block_size,
4952                ))
4953                .bt());
4954            }
4955            OpParams::PagedAttn {
4956                b: q_dims[0],
4957                hq: q_dims[1],
4958                hkv: kc_dims[2],
4959                sq: q_dims[2],
4960                d: q_dims[3],
4961                block_size: *block_size,
4962                max_blocks_per_seq: bt_dims[1],
4963                num_blocks: kc_dims[0],
4964                softmax_scale: *softmax_scale,
4965                softcap: *softcap,
4966            }
4967        }
4968        // Phase 7.6 step 5 (final): legacy `Op::FlashAttn` arm dropped.
4969        Op::Fused(
4970            _,
4971            fuel_graph::registry::FusedOpParams::FlashAttn {
4972                softmax_scale,
4973                causal,
4974                window_size_left,
4975                window_size_right,
4976                softcap,
4977                k_len,
4978            },
4979        ) => {
4980            // Inputs[0]=q [B,Hq,Sq,D], inputs[1]=k [B,Hkv,Sk,D],
4981            // inputs[2]=v [B,Hkv,Sk,D], inputs[3]=alibi_slopes [Hq] (optional).
4982            // `sk` is the PHYSICAL K extent (capacity, for strides/bytes);
4983            // `k_len` (resolved below) is the LOGICAL attended length.
4984            if node.inputs.len() != 3 && node.inputs.len() != 4 {
4985                return Err(Error::Msg(format!(
4986                    "Op::FlashAttn expects 3 or 4 inputs, got {}",
4987                    node.inputs.len(),
4988                ))
4989                .bt());
4990            }
4991            let q_layout = input_layout(node.inputs[0]);
4992            let k_layout = input_layout(node.inputs[1]);
4993            let v_layout = input_layout(node.inputs[2]);
4994            let q_dims = q_layout.shape().dims();
4995            let k_dims = k_layout.shape().dims();
4996            let v_dims = v_layout.shape().dims();
4997            if q_dims.len() != 4 || k_dims.len() != 4 || v_dims.len() != 4 {
4998                return Err(Error::Msg(format!(
4999                    "Op::FlashAttn requires rank-4 q/k/v; got q={q_dims:?} k={k_dims:?} v={v_dims:?}",
5000                ))
5001                .bt());
5002            }
5003            if k_dims != v_dims {
5004                return Err(Error::Msg(format!(
5005                    "Op::FlashAttn: k {k_dims:?} and v {v_dims:?} must share shape",
5006                ))
5007                .bt());
5008            }
5009            if q_dims[0] != k_dims[0] || q_dims[3] != k_dims[3] {
5010                return Err(Error::Msg(format!(
5011                    "Op::FlashAttn: q {q_dims:?} and k {k_dims:?} must share B and D",
5012                ))
5013                .bt());
5014            }
5015            let sk = k_dims[2];
5016            // Resolve the logical attended length. `None` ⇒ attend the
5017            // full K extent (today's behavior). `Some(dyn)` ⇒ resolve
5018            // against the per-pass SymEnv; the resolved length must fit
5019            // the capacity and cover Sq (a valid causal prefix).
5020            let attended_k_len = match k_len {
5021                None => sk,
5022                Some(dyn_k) => {
5023                    let kl = dyn_k.resolve(sym_env).ok_or_else(|| {
5024                        Error::Msg(format!(
5025                            "Op::FlashAttn: dynamic k_len {dyn_k:?} is unbound in the SymEnv at realize",
5026                        ))
5027                        .bt()
5028                    })?;
5029                    if kl > sk {
5030                        return Err(Error::Msg(format!(
5031                            "Op::FlashAttn: resolved k_len ({kl}) exceeds K capacity ({sk})",
5032                        ))
5033                        .bt());
5034                    }
5035                    if kl < q_dims[2] {
5036                        return Err(Error::Msg(format!(
5037                            "Op::FlashAttn: resolved k_len ({kl}) < Sq ({}) — not a valid causal prefix",
5038                            q_dims[2],
5039                        ))
5040                        .bt());
5041                    }
5042                    kl
5043                }
5044            };
5045            OpParams::FlashAttn {
5046                b: q_dims[0],
5047                hq: q_dims[1],
5048                hkv: k_dims[1],
5049                sq: q_dims[2],
5050                sk,
5051                d: q_dims[3],
5052                k_len: attended_k_len,
5053                softmax_scale: *softmax_scale,
5054                causal: *causal,
5055                window_size_left: *window_size_left,
5056                window_size_right: *window_size_right,
5057                softcap: *softcap,
5058            }
5059        }
5060        Op::ReduceSumTo(target_shape) => {
5061            if node.inputs.len() != 1 {
5062                return Err(Error::Msg(format!(
5063                    "Op::ReduceSumTo expects 1 input, got {}",
5064                    node.inputs.len(),
5065                ))
5066                .bt());
5067            }
5068            let in_layout = input_layout(node.inputs[0]);
5069            let input_shape: Vec<usize> = in_layout.shape().dims().to_vec();
5070            let output_shape: Vec<usize> = target_shape.dims().to_vec();
5071            OpParams::ReduceSumTo {
5072                input_shape,
5073                output_shape,
5074            }
5075        }
5076        Op::ReduceMaxTo(target_shape) => {
5077            if node.inputs.len() != 1 {
5078                return Err(Error::Msg(format!(
5079                    "Op::ReduceMaxTo expects 1 input, got {}",
5080                    node.inputs.len(),
5081                ))
5082                .bt());
5083            }
5084            let in_layout = input_layout(node.inputs[0]);
5085            let input_shape: Vec<usize> = in_layout.shape().dims().to_vec();
5086            let output_shape: Vec<usize> = target_shape.dims().to_vec();
5087            OpParams::ReduceMaxTo {
5088                input_shape,
5089                output_shape,
5090            }
5091        }
5092        // Phase 7.6 step 5 (final): legacy `Op::ConvTranspose2D` arm dropped.
5093        Op::Fused(
5094            _,
5095            fuel_graph::registry::FusedOpParams::ConvTranspose2D {
5096                stride,
5097                padding,
5098                output_padding,
5099                dilation,
5100                groups,
5101            },
5102        ) => {
5103            // Inputs[0] = x [N, Cin, Hin, Win]; inputs[1] = weight
5104            // [Cin, Cout/groups, Kh, Kw]; inputs[2] (optional) = bias [Cout].
5105            // Output (this Node's shape) = [N, Cout, Hout, Wout].
5106            if node.inputs.len() != 2 && node.inputs.len() != 3 {
5107                return Err(Error::Msg(format!(
5108                    "Op::ConvTranspose2D expects 2 or 3 inputs, got {}",
5109                    node.inputs.len(),
5110                ))
5111                .bt());
5112            }
5113            let x_layout = input_layout(node.inputs[0]);
5114            let w_layout = input_layout(node.inputs[1]);
5115            let x_dims = x_layout.shape().dims();
5116            let w_dims = w_layout.shape().dims();
5117            if x_dims.len() != 4 || w_dims.len() != 4 {
5118                return Err(Error::Msg(format!(
5119                    "Op::ConvTranspose2D requires rank-4 x and weight; got x={x_dims:?} w={w_dims:?}",
5120                ))
5121                .bt());
5122            }
5123            let out_dims = node.shape.dims();
5124            if out_dims.len() != 4 {
5125                return Err(Error::Msg(format!(
5126                    "Op::ConvTranspose2D output must be rank 4, got {out_dims:?}",
5127                ))
5128                .bt());
5129            }
5130            let x_shape = [x_dims[0], x_dims[1], x_dims[2], x_dims[3]];
5131            let w_shape = [w_dims[0], w_dims[1], w_dims[2], w_dims[3]];
5132            let out_shape = [out_dims[0], out_dims[1], out_dims[2], out_dims[3]];
5133            OpParams::ConvTranspose2D {
5134                x_shape,
5135                w_shape,
5136                out_shape,
5137                stride: *stride,
5138                padding: *padding,
5139                output_padding: *output_padding,
5140                dilation: *dilation,
5141                groups: *groups,
5142            }
5143        }
5144        Op::WriteSlice { ranges, dyn_offset } => {
5145            // inputs[0] = destination (its shape == this node's shape
5146            // since WriteSlice's output adopts the destination's
5147            // Layout). inputs[1] = source slab; its shape is implied
5148            // by `ranges`. The kernel needs the destination shape to
5149            // compute strides for the slab walk.
5150            if node.inputs.len() != 2 {
5151                return Err(Error::Msg(format!(
5152                    "Op::WriteSlice expects 2 inputs (destination, source), got {}",
5153                    node.inputs.len(),
5154                ))
5155                .bt());
5156            }
5157            let dest_dims = node.shape.dims().to_vec();
5158            if ranges.len() != dest_dims.len() {
5159                return Err(Error::Msg(format!(
5160                    "Op::WriteSlice: ranges.len() ({}) must equal destination rank ({})",
5161                    ranges.len(),
5162                    dest_dims.len(),
5163                ))
5164                .bt());
5165            }
5166            // Phase D symbolic extents: when present, resolve the runtime
5167            // start offset against the per-pass SymEnv, overriding
5168            // `ranges[axis].0`. The slab WIDTH on that axis stays
5169            // `ranges[axis].1 - ranges[axis].0`, so the effective range
5170            // becomes `(base, base + width)`. `None` ⇒ fully static, and
5171            // the SymEnv is never consulted (empty-env realize unchanged).
5172            //
5173            // DUAL-PATH (increment 2b — data-determined dynamic shapes):
5174            //  - The offset resolves in the compile-time `sym_env` (static,
5175            //    or an INPUT-determined `cached_len`): bake it into `ranges`
5176            //    now, exactly as before.
5177            //  - It is UNBOUND at compile AND a producer in this graph binds
5178            //    it (`Op::NonZeroIndices`'s count, etc.): it is
5179            //    DATA-DETERMINED — leave `ranges[axis]` as the static
5180            //    placeholder and DEFER, carrying the `DynScalar` in
5181            //    `deferred_dyn_offset`. The `WorkItemKind::WriteSlice`
5182            //    executor arm resolves it from `produced_syms` (after the
5183            //    producer runs) and bounds-checks the resolved range there.
5184            //  - It is unbound AND no producer binds it: a genuine caller
5185            //    error → surface it here (preserves the unbound-error path).
5186            let mut ranges = ranges.clone();
5187            let mut deferred_dyn_offset: Option<(usize, fuel_ir::DynScalar)> = None;
5188            if let Some((axis, off)) = dyn_offset {
5189                if *axis >= ranges.len() {
5190                    return Err(Error::Msg(format!(
5191                        "Op::WriteSlice: dyn_offset axis ({axis}) out of bounds for rank {}",
5192                        ranges.len(),
5193                    ))
5194                    .bt());
5195                }
5196                match off.resolve(sym_env) {
5197                    Some(base) => {
5198                        let (start, end) = ranges[*axis];
5199                        let width = end - start;
5200                        ranges[*axis] = (base, base + width);
5201                    }
5202                    None => {
5203                        let is_data_determined = matches!(off, fuel_ir::DynScalar::Sym(s)
5204                            if graph.binds_data_determined_sym(*s));
5205                        if is_data_determined {
5206                            deferred_dyn_offset = Some((*axis, *off));
5207                        } else {
5208                            return Err(Error::Msg(format!(
5209                                "Op::WriteSlice: dynamic offset {off:?} on axis {axis} is \
5210                                 unbound in the SymEnv at realize (and no producer in the \
5211                                 graph binds it, so it is not data-determined)",
5212                            ))
5213                            .bt());
5214                        }
5215                    }
5216                }
5217            }
5218            for (i, &(start, end)) in ranges.iter().enumerate() {
5219                // The deferred axis still holds its static placeholder; the
5220                // executor bounds-checks the resolved range after producing
5221                // the count. Every other axis is fully known now.
5222                if deferred_dyn_offset.is_some_and(|(a, _)| a == i) {
5223                    continue;
5224                }
5225                if end < start || end > dest_dims[i] {
5226                    return Err(Error::Msg(format!(
5227                        "Op::WriteSlice: ranges[{i}] = ({start}, {end}) invalid \
5228                         for destination dim {i} = {}",
5229                        dest_dims[i],
5230                    ))
5231                    .bt());
5232                }
5233            }
5234            OpParams::WriteSlice {
5235                dest_shape: dest_dims,
5236                ranges,
5237                deferred_dyn_offset,
5238            }
5239        }
5240        Op::WriteSliceRotating {
5241            axis,
5242            modulus,
5243            ranges,
5244        } => {
5245            // inputs[0] = destination, inputs[1] = source slab,
5246            // inputs[2] = dynamic position scalar (U32). The builder
5247            // already validated rank / dtype / shape parity; the
5248            // exec-time check below mirrors WriteSlice for the
5249            // structural invariants the executor depends on.
5250            if node.inputs.len() != 3 {
5251                return Err(Error::Msg(format!(
5252                    "Op::WriteSliceRotating expects 3 inputs (destination, source, position), got {}",
5253                    node.inputs.len(),
5254                ))
5255                .bt());
5256            }
5257            let dest_dims = node.shape.dims().to_vec();
5258            if ranges.len() != dest_dims.len() {
5259                return Err(Error::Msg(format!(
5260                    "Op::WriteSliceRotating: ranges.len() ({}) must equal destination rank ({})",
5261                    ranges.len(),
5262                    dest_dims.len(),
5263                ))
5264                .bt());
5265            }
5266            if *axis >= dest_dims.len() {
5267                return Err(Error::Msg(format!(
5268                    "Op::WriteSliceRotating: axis {axis} out of bounds for rank {}",
5269                    dest_dims.len(),
5270                ))
5271                .bt());
5272            }
5273            if *modulus == 0 || *modulus > dest_dims[*axis] {
5274                return Err(Error::Msg(format!(
5275                    "Op::WriteSliceRotating: modulus {modulus} invalid for dest_shape[{axis}] = {}",
5276                    dest_dims[*axis],
5277                ))
5278                .bt());
5279            }
5280            OpParams::WriteSliceRotating {
5281                dest_shape: dest_dims,
5282                axis: *axis,
5283                modulus: *modulus,
5284                ranges: ranges.clone(),
5285            }
5286        }
5287        Op::WriteSliceDoff { axis, ranges } => {
5288            // inputs[0] = destination, inputs[1] = source slab,
5289            // inputs[2] = device-resident I64 offset scalar. The
5290            // builder validated rank / dtype / static-width parity; the
5291            // exec-time check below mirrors WriteSliceRotating minus the
5292            // modulus (no wrap). Bounds on the *dynamic* offset are the
5293            // caller's contract (device-only, un-checkable here).
5294            if node.inputs.len() != 3 {
5295                return Err(Error::Msg(format!(
5296                    "Op::WriteSliceDoff expects 3 inputs (destination, source, offset), got {}",
5297                    node.inputs.len(),
5298                ))
5299                .bt());
5300            }
5301            let dest_dims = node.shape.dims().to_vec();
5302            if ranges.len() != dest_dims.len() {
5303                return Err(Error::Msg(format!(
5304                    "Op::WriteSliceDoff: ranges.len() ({}) must equal destination rank ({})",
5305                    ranges.len(),
5306                    dest_dims.len(),
5307                ))
5308                .bt());
5309            }
5310            if *axis >= dest_dims.len() {
5311                return Err(Error::Msg(format!(
5312                    "Op::WriteSliceDoff: axis {axis} out of bounds for rank {}",
5313                    dest_dims.len(),
5314                ))
5315                .bt());
5316            }
5317            OpParams::WriteSliceDoff {
5318                dest_shape: dest_dims,
5319                axis: *axis,
5320                ranges: ranges.clone(),
5321            }
5322        }
5323        _ => OpParams::None,
5324    })
5325}
5326
5327/// Execute one work item. Three branches by `WorkItemKind`:
5328///
5329/// - `ConstAdopt` — verify cache has an entry pre-seeded by the
5330///   caller; record the layout from the WorkItem.
5331/// - `ViewOf { input }` — clone the input's Storage Arc into the
5332///   output slot (bytes are shared); record the strided layout
5333///   from the WorkItem.
5334/// - `Kernel` — gather input Arcs, allocate the output, run the
5335///   compiled kernel, store the result; record the contiguous
5336///   layout from the WorkItem.
5337///
5338/// Best-effort: prefix a realize-time node error with the failing node's graph
5339/// location — `Graph::describe_node` renders `Node#N (op, out shape, dtype,
5340/// inputs=[...])`, enough to grep-locate the offending op in a large graph. The
5341/// legacy per-node executors (`fuel-graph-executor`, the retired
5342/// `fuel-reference-backend`) wrapped panics this way; the PipelinedExecutor
5343/// surfaces the raw kernel error, so a dtype/shape/OOB failure deep in a model
5344/// arrived with no graph coordinate. On a graph read-lock failure the original
5345/// error passes through unchanged — the location is a navigation aid, never
5346/// worth masking the real error with a lock issue. Zero happy-path cost: only
5347/// the error branch touches the graph.
5348fn with_node_location(graph: &Arc<RwLock<Graph>>, node_id: NodeId, err: Error) -> Error {
5349    match graph.read() {
5350        Ok(g) => err.context(g.describe_node(node_id)),
5351        Err(_) => err,
5352    }
5353}
5354
5355/// Execute one [`WorkItem`] against the cache, returning the node's
5356/// [`CompletionHandle`].
5357///
5358/// Step E A4b-1: the producing arms (Kernel / WriteSlice / WriteSliceRotating /
5359/// in-place / cross-device Copy alloc) return the handle from `execute_compiled`
5360/// *without* waiting it inline — the realize loop stores it in its per-node
5361/// handle map and drains at realize-end. Non-producing arms (const adopt, view,
5362/// slot projection, release marker, contiguize) are pure Arc-clones / host
5363/// allocs whose work is already complete → [`CompletionHandle::Ready`].
5364/// Read a data-determined runtime count from bundle slot 1 of a
5365/// just-realized producer and bind it into the per-pass `SymEnv` under
5366/// `count_sym` — the data-dependent dynamic-shapes seam (increment 2a).
5367/// The producer's bundle is `[indices [capacity] U32 ; count [1] U32]`;
5368/// slot 1's single U32 starts at byte `capacity * 4` (after the
5369/// `capacity`-element U32 primary slot). CPU only for now — device
5370/// backends need a D2H after the completion handle is waited (a documented
5371/// follow-up; the whole data-dependent path is CPU-first). Called AFTER
5372/// `execute_compiled`, whose CPU path returns a `Ready` handle, so the
5373/// bytes are already valid.
5374fn bind_data_determined_count(
5375    arc: &Arc<RwLock<Storage>>,
5376    capacity: usize,
5377    count_sym: fuel_ir::SymId,
5378    produced_syms: &mut SymEnv,
5379) -> Result<()> {
5380    let guard = arc
5381        .read()
5382        .map_err(|_| poisoned("NonZeroIndices output storage"))?;
5383    let count_byte_off = capacity * std::mem::size_of::<u32>();
5384    let end = count_byte_off + std::mem::size_of::<u32>();
5385    // The non-CPU `BackendStorage` variants are cfg-gated; with GPU
5386    // features off, `Cpu` is the only variant and the fallback arm is
5387    // unreachable (a documented CPU-first limitation, not dead logic).
5388    #[allow(unreachable_patterns)]
5389    let count = match &guard.inner {
5390        fuel_memory::BackendStorage::Cpu(cpu_bytes) => {
5391            let bytes = cpu_bytes.bytes();
5392            if end > bytes.len() {
5393                return Err(Error::Msg(format!(
5394                    "NonZeroIndices: count slot byte range [{count_byte_off}..{end}) \
5395                     exceeds bundle byte length {}",
5396                    bytes.len(),
5397                ))
5398                .bt());
5399            }
5400            u32::from_le_bytes(
5401                bytes[count_byte_off..end]
5402                    .try_into()
5403                    .expect("4 bytes → u32"),
5404            )
5405        }
5406        other => {
5407            return Err(Error::Msg(format!(
5408                "NonZeroIndices: data-determined count read is CPU-only today; got \
5409                 BackendStorage::{:?} (device backends need a D2H after the completion \
5410                 handle is waited — a documented follow-up)",
5411                std::mem::discriminant(other),
5412            ))
5413            .bt());
5414        }
5415    };
5416    produced_syms.bind(count_sym, count as usize)?;
5417    Ok(())
5418}
5419
5420/// Increment 2b — the consumer half of data-dependent dynamic shapes. When
5421/// a `WriteSlice`'s offset is DATA-DETERMINED (its `SymId` is produced
5422/// mid-pass, so `op_to_op_params` deferred it into
5423/// `OpParams::WriteSlice::deferred_dyn_offset` instead of baking it at
5424/// compile), resolve it HERE from `produced_syms` — populated by the
5425/// producer's execute step (single-threaded topological order guarantees
5426/// the producer already ran). Returns a patched clone of the `CompiledNode`
5427/// with the resolved `ranges` (and `deferred_dyn_offset` cleared) for the
5428/// kernel; `None` when there is nothing to defer (the common path — no
5429/// clone). Bounds-checks the resolved range (deferred past compile).
5430fn resolve_deferred_write_slice(
5431    compiled: &CompiledNode,
5432    produced_syms: &SymEnv,
5433    node_id: NodeId,
5434) -> Result<Option<CompiledNode>> {
5435    let OpParams::WriteSlice {
5436        dest_shape,
5437        ranges,
5438        deferred_dyn_offset,
5439    } = &compiled.op_params
5440    else {
5441        return Ok(None);
5442    };
5443    let Some((axis, off)) = deferred_dyn_offset else {
5444        return Ok(None);
5445    };
5446    let base = off.resolve(produced_syms).ok_or_else(|| {
5447        Error::Msg(format!(
5448            "Op::WriteSlice {node_id:?}: data-determined offset {off:?} on axis {axis} is \
5449             unbound in produced_syms at execute (its producer did not run / bind it)",
5450        ))
5451        .bt()
5452    })?;
5453    let mut ranges = ranges.clone();
5454    let (start, end) = ranges[*axis];
5455    let width = end - start;
5456    let resolved = (base, base + width);
5457    if resolved.1 > dest_shape[*axis] {
5458        return Err(Error::Msg(format!(
5459            "Op::WriteSlice {node_id:?}: resolved data-determined range {resolved:?} on axis \
5460             {axis} exceeds destination dim = {}",
5461            dest_shape[*axis],
5462        ))
5463        .bt());
5464    }
5465    ranges[*axis] = resolved;
5466    let mut patched = compiled.clone();
5467    patched.op_params = OpParams::WriteSlice {
5468        dest_shape: dest_shape.clone(),
5469        ranges,
5470        deferred_dyn_offset: None,
5471    };
5472    Ok(Some(patched))
5473}
5474
5475/// Dynamic-M matmul: when a matmul's row count is DATA-DETERMINED
5476/// (`MatmulM::Deferred`, deferred by `op_to_op_params` because a producer
5477/// binds its `SymId` mid-pass), resolve it HERE from `produced_syms` and
5478/// run the kernel against a patched clone whose `m_compute` is
5479/// `MatmulM::Rows(count)`. Mirrors `resolve_deferred_write_slice`. `None`
5480/// when nothing is deferred (the common path — no clone). The kernel then
5481/// computes exactly `count` rows of the `m`-row capacity buffer.
5482fn resolve_deferred_matmul(
5483    compiled: &CompiledNode,
5484    produced_syms: &SymEnv,
5485    node_id: NodeId,
5486) -> Result<Option<CompiledNode>> {
5487    let OpParams::Matmul {
5488        lhs_batch_dims,
5489        rhs_batch_dims,
5490        m,
5491        n,
5492        k,
5493        m_compute,
5494    } = &compiled.op_params
5495    else {
5496        return Ok(None);
5497    };
5498    let MatmulM::Deferred(dyn_m) = m_compute else {
5499        return Ok(None);
5500    };
5501    let rows = dyn_m.resolve(produced_syms).ok_or_else(|| {
5502        Error::Msg(format!(
5503            "Op::MatMul {node_id:?}: data-determined row count {dyn_m:?} is unbound in \
5504             produced_syms at execute (its producer did not run / bind it)",
5505        ))
5506        .bt()
5507    })?;
5508    if rows > *m {
5509        return Err(Error::Msg(format!(
5510            "Op::MatMul {node_id:?}: resolved row count {rows} exceeds capacity {m}",
5511        ))
5512        .bt());
5513    }
5514    let mut patched = compiled.clone();
5515    patched.op_params = OpParams::Matmul {
5516        lhs_batch_dims: lhs_batch_dims.clone(),
5517        rhs_batch_dims: rhs_batch_dims.clone(),
5518        m: *m,
5519        n: *n,
5520        k: *k,
5521        m_compute: MatmulM::Rows(rows),
5522    };
5523    Ok(Some(patched))
5524}
5525
5526fn execute_work_item(
5527    item: &WorkItem,
5528    cache: &mut StorageCache,
5529    layout_cache: &mut HashMap<NodeId, Layout>,
5530    produced_syms: &mut SymEnv,
5531    // Step E A4b open question #4 — "event only where waited": whether
5532    // THIS item's node id is in the realize's `WaitSet` (`will_be_waited`
5533    // in `pipelined.rs`, computed once per item by the caller). Forwarded
5534    // to every `execute_compiled_with_wait_hint` call below so a CUDA
5535    // kernel with no mid-walk reader skips its `Event` entirely.
5536    will_be_waited: bool,
5537    // CapturedRun executor build-out: persistent-output mode. `None` on
5538    // every existing realize path ⇒ byte-identical (fresh alloc, nothing
5539    // recorded). `Some(Record)` records each Kernel output's fixed Arc;
5540    // `Some(Reuse)` reuses the recorded buffer (no alloc — capture-safe)
5541    // and the write-into kernel path writes into it in place. Only the
5542    // `Kernel` arm consults it; every other arm ignores it.
5543    mut persistent: Option<&mut PersistentOutputs>,
5544) -> Result<CompletionHandle> {
5545    match &item.kind {
5546        WorkItemKind::ConstAdopt => {
5547            if !cache.contains_key(&item.node_id) {
5548                return Err(Error::Msg(format!(
5549                    "PipelinedExecutor: Const node {:?} not in input cache",
5550                    item.node_id
5551                ))
5552                .bt());
5553            }
5554            // Layout for input cache entries was seeded at realize
5555            // start; refresh from the WorkItem in case the side-table
5556            // was set after seeding.
5557            layout_cache.insert(item.node_id, item.output_layout.clone());
5558            Ok(CompletionHandle::Ready)
5559        }
5560        WorkItemKind::ViewOf { input } => {
5561            let input_arc = cache.get(input).cloned().ok_or_else(|| {
5562                Error::Msg(format!(
5563                    "PipelinedExecutor: view-op input {:?} of {:?} not realized",
5564                    input, item.node_id,
5565                ))
5566                .bt()
5567            })?;
5568            cache.insert(item.node_id, input_arc);
5569            layout_cache.insert(item.node_id, item.output_layout.clone());
5570            Ok(CompletionHandle::Ready)
5571        }
5572        WorkItemKind::SlotView { producer } => {
5573            // Op::View — multi-output projection. Same realization
5574            // shape as ViewOf: clone the producer's Storage Arc into
5575            // the View's cache slot. The WorkItem's output_layout was
5576            // computed at graph-build time by `Tensor::view`, with
5577            // the slot's byte_offset baked into start_offset (in
5578            // slot-dtype-element units). Downstream kernels reading
5579            // the producer's bytes as the slot's dtype starting at
5580            // that offset see the slot's typed window.
5581            let producer_arc = cache.get(producer).cloned().ok_or_else(|| {
5582                Error::Msg(format!(
5583                    "PipelinedExecutor: Op::View producer {:?} of {:?} not realized",
5584                    producer, item.node_id,
5585                ))
5586                .bt()
5587            })?;
5588            cache.insert(item.node_id, producer_arc);
5589            layout_cache.insert(item.node_id, item.output_layout.clone());
5590            Ok(CompletionHandle::Ready)
5591        }
5592        WorkItemKind::SlotOwn { producer, slot } => {
5593            // Op::ViewOwned — allocate a fresh Storage of the slot's
5594            // (shape, dtype) on the producer's device and copy the
5595            // slot's bytes in. Per-backend fast paths:
5596            //   - CPU:    direct &[u8]→&mut[u8] memcpy via CpuStorageBytes
5597            //   - CUDA:   D2D via CudaStorageBytes::slot_copy_to_new
5598            //             (cuMemcpyDtoDAsync with offset src pointer)
5599            //   - Vulkan: vkCmdCopyBuffer via
5600            //             VulkanBackend::slot_copy_to_new_handle
5601            //             (srcOffset/dstOffset/size)
5602            // For backends without a copy-with-offset hook we fall
5603            // back to a host round-trip (`to_host_buffer_dyn` →
5604            // slice → `storage_from_host_buffer_owned_dyn`), which
5605            // works but is wasteful.
5606            let producer_arc = cache.get(producer).cloned().ok_or_else(|| {
5607                Error::Msg(format!(
5608                    "PipelinedExecutor: Op::ViewOwned producer {:?} of {:?} not realized",
5609                    producer, item.node_id,
5610                ))
5611                .bt()
5612            })?;
5613            let new_storage = {
5614                let guard = producer_arc
5615                    .read()
5616                    .map_err(|_| poisoned("ViewOwned producer storage"))?;
5617                let bundle = guard.bundle().ok_or_else(|| {
5618                    Error::Msg(format!(
5619                        "Op::ViewOwned: producer {:?} has no bundle side-table \
5620                         — the multi-output authoring contract requires \
5621                         Storage::with_bundle / new_bundled at allocation \
5622                         time. Node {:?} slot {} cannot resolve its source.",
5623                        producer, item.node_id, slot,
5624                    ))
5625                    .bt()
5626                })?;
5627                let sv = bundle.get(*slot as usize).cloned().ok_or_else(|| {
5628                    Error::Msg(format!(
5629                        "Op::ViewOwned: slot {} out of range for producer {:?} \
5630                         (bundle has {} slots)",
5631                        slot,
5632                        producer,
5633                        bundle.len(),
5634                    ))
5635                    .bt()
5636                })?;
5637                use fuel_memory::BackendStorage;
5638                match &guard.inner {
5639                    BackendStorage::Cpu(cpu_bytes) => {
5640                        let src_bytes = cpu_bytes.bytes();
5641                        let end = sv.byte_offset + sv.len_bytes();
5642                        if end > src_bytes.len() {
5643                            return Err(Error::Msg(format!(
5644                                "Op::ViewOwned: slot {} byte range [{}..{}) \
5645                                 exceeds producer's CPU byte length {}",
5646                                slot,
5647                                sv.byte_offset,
5648                                end,
5649                                src_bytes.len(),
5650                            ))
5651                            .bt());
5652                        }
5653                        let owned = fuel_cpu_backend::CpuStorageBytes::from_bytes(
5654                            &src_bytes[sv.byte_offset..end],
5655                        );
5656                        fuel_memory::Storage::new(BackendStorage::Cpu(owned), sv.dtype)
5657                    }
5658                    #[cfg(feature = "cuda")]
5659                    BackendStorage::Cuda(cuda_bytes) => {
5660                        let dst = cuda_bytes.slot_copy_to_new(sv.byte_offset, sv.len_bytes())?;
5661                        fuel_memory::Storage::new(BackendStorage::Cuda(dst), sv.dtype)
5662                    }
5663                    #[cfg(feature = "vulkan")]
5664                    BackendStorage::Vulkan(vk_bytes) => {
5665                        let backend = vk_bytes.backend().ok_or_else(|| {
5666                            Error::Msg(format!(
5667                                "Op::ViewOwned: producer {:?} is on Vulkan but \
5668                                 its storage has no VulkanBackend handle. \
5669                                 Storages flowing through the pipelined executor \
5670                                 must be constructed via alloc_bytes_handle / \
5671                                 upload_bytes_handle so the bundle's slot extraction \
5672                                 path can reach the backend.",
5673                                producer,
5674                            ))
5675                            .bt()
5676                        })?;
5677                        let dst = backend.slot_copy_to_new_handle(
5678                            vk_bytes,
5679                            sv.byte_offset,
5680                            sv.len_bytes(),
5681                        )?;
5682                        fuel_memory::Storage::new(BackendStorage::Vulkan(dst), sv.dtype)
5683                    }
5684                    #[allow(unreachable_patterns)]
5685                    _ => {
5686                        return Err(Error::Msg(format!(
5687                            "Op::ViewOwned: producer {:?} is on a backend \
5688                             without a slot-copy-with-offset hook \
5689                             (CPU + CUDA + Vulkan wired). Add a per-backend \
5690                             `slot_copy_to_new`-equivalent and extend the \
5691                             match arm.",
5692                            producer,
5693                        ))
5694                        .bt());
5695                    }
5696                }
5697            };
5698            cache.insert(item.node_id, Arc::new(RwLock::new(new_storage)));
5699            layout_cache.insert(item.node_id, item.output_layout.clone());
5700            // A4b-1: Op::ViewOwned's slot copy (CUDA D2D) is same-stream; its
5701            // completion is carried by the realize-end full-stream sync in
5702            // `to_cpu_bytes` (unchanged) — `Ready` here is behavior-preserving.
5703            Ok(CompletionHandle::Ready)
5704        }
5705        WorkItemKind::WriteSlice { dest, source } => {
5706            let compiled = item.compiled.as_ref().ok_or_else(|| {
5707                Error::Msg(format!(
5708                    "PipelinedExecutor: WriteSlice work item {:?} has no compiled node",
5709                    item.node_id,
5710                ))
5711                .bt()
5712            })?;
5713            // Increment 2b: if the offset is DATA-DETERMINED, resolve it from
5714            // the producer-bound `produced_syms` and run the kernel against
5715            // the patched (resolved-range) node. `None` on the common path.
5716            let patched_ws = resolve_deferred_write_slice(compiled, produced_syms, item.node_id)?;
5717            let compiled = patched_ws.as_ref().unwrap_or(compiled);
5718            let dest_arc = cache.get(dest).cloned().ok_or_else(|| {
5719                Error::Msg(format!(
5720                    "PipelinedExecutor: WriteSlice destination {:?} of {:?} not realized",
5721                    dest, item.node_id,
5722                ))
5723                .bt()
5724            })?;
5725            let source_arc = cache.get(source).cloned().ok_or_else(|| {
5726                Error::Msg(format!(
5727                    "PipelinedExecutor: WriteSlice source {:?} of {:?} not realized",
5728                    source, item.node_id,
5729                ))
5730                .bt()
5731            })?;
5732            let dest_layout = layout_cache.get(dest).cloned().ok_or_else(|| {
5733                Error::Msg(format!(
5734                    "PipelinedExecutor: WriteSlice destination {:?} of {:?} has no cached layout",
5735                    dest, item.node_id,
5736                ))
5737                .bt()
5738            })?;
5739            let source_layout = layout_cache.get(source).cloned().ok_or_else(|| {
5740                Error::Msg(format!(
5741                    "PipelinedExecutor: WriteSlice source {:?} of {:?} has no cached layout",
5742                    source, item.node_id,
5743                ))
5744                .bt()
5745            })?;
5746            // v1 contract: destination must be contiguous + zero
5747            // offset. Strided dests would force the kernel to walk
5748            // both source and dest strides; defer until KV cache
5749            // exposes a non-contig dest. Source CAN be non-contig —
5750            // we auto-contiguize it here so the kernel sees a flat
5751            // slab.
5752            if !dest_layout.is_contiguous() || dest_layout.start_offset() != 0 {
5753                return Err(Error::Msg(format!(
5754                    "Op::WriteSlice (Phase E.3.2 v1): destination {:?} must be \
5755                     contiguous + zero-offset; got Layout {:?}",
5756                    dest, dest_layout,
5757                ))
5758                .bt());
5759            }
5760            let source_arc_contig = {
5761                let s_dtype = source_arc
5762                    .read()
5763                    .map_err(|_| poisoned("WriteSlice source storage"))?
5764                    .dtype;
5765                let s_len_bytes = source_arc
5766                    .read()
5767                    .map_err(|_| poisoned("WriteSlice source storage"))?
5768                    .inner
5769                    .len_bytes();
5770                let layout_bytes = source_layout.shape().elem_count() * s_dtype.size_in_bytes();
5771                let bytes_match_shape = s_len_bytes == layout_bytes;
5772                let already_contig = source_layout.is_contiguous()
5773                    && source_layout.start_offset() == 0
5774                    && bytes_match_shape;
5775                if already_contig {
5776                    source_arc
5777                } else {
5778                    auto_contiguize(&source_arc, &source_layout)?
5779                }
5780            };
5781            let source_layout_kernel = fuel_ir::Layout::contiguous(source_layout.shape().clone());
5782            // The kernel sees inputs=[source] and outputs=[dest_arc].
5783            // The dest input slot is intentionally absent — the kernel
5784            // doesn't read from dest; it only writes to its bytes
5785            // through the output slot's write lock.
5786            let input_arcs = vec![source_arc_contig];
5787            let mut output_arcs = vec![dest_arc.clone()];
5788            let kernel_layouts = vec![source_layout_kernel, dest_layout.clone()];
5789            // A4b-1: defer the wait — return the handle to the realize loop.
5790            let handle = execute_compiled_with_wait_hint(
5791                compiled,
5792                &input_arcs,
5793                &mut output_arcs,
5794                &kernel_layouts,
5795                will_be_waited,
5796            )?;
5797            // Adopt the dest Arc at this WriteSlice node's slot. The
5798            // realize loop's destructive_input cleanup evicts the
5799            // dest's own NodeId from the cache afterward — downstream
5800            // readers go through this node's NodeId.
5801            cache.insert(item.node_id, dest_arc);
5802            layout_cache.insert(item.node_id, item.output_layout.clone());
5803            Ok(handle)
5804        }
5805        WorkItemKind::WriteSliceRotating {
5806            dest,
5807            source,
5808            position,
5809        } => {
5810            // Same shape as WriteSlice but with a position input.
5811            // Kernel sees `[source, position]` as inputs; `dest` is the
5812            // pre-allocated output buffer (in-place adoption).
5813            let compiled = item.compiled.as_ref().ok_or_else(|| {
5814                Error::Msg(format!(
5815                    "PipelinedExecutor: WriteSliceRotating work item {:?} has no compiled node",
5816                    item.node_id,
5817                ))
5818                .bt()
5819            })?;
5820            let dest_arc = cache.get(dest).cloned().ok_or_else(|| {
5821                Error::Msg(format!(
5822                    "PipelinedExecutor: WriteSliceRotating destination {:?} of {:?} not realized",
5823                    dest, item.node_id,
5824                ))
5825                .bt()
5826            })?;
5827            let source_arc = cache.get(source).cloned().ok_or_else(|| {
5828                Error::Msg(format!(
5829                    "PipelinedExecutor: WriteSliceRotating source {:?} of {:?} not realized",
5830                    source, item.node_id,
5831                ))
5832                .bt()
5833            })?;
5834            let position_arc = cache.get(position).cloned().ok_or_else(|| {
5835                Error::Msg(format!(
5836                    "PipelinedExecutor: WriteSliceRotating position {:?} of {:?} not realized",
5837                    position, item.node_id,
5838                ))
5839                .bt()
5840            })?;
5841            let dest_layout = layout_cache.get(dest).cloned().ok_or_else(|| {
5842                Error::Msg(format!(
5843                    "PipelinedExecutor: WriteSliceRotating destination {:?} of {:?} has no cached layout",
5844                    dest, item.node_id,
5845                ))
5846                .bt()
5847            })?;
5848            let source_layout = layout_cache.get(source).cloned().ok_or_else(|| {
5849                Error::Msg(format!(
5850                    "PipelinedExecutor: WriteSliceRotating source {:?} of {:?} has no cached layout",
5851                    source, item.node_id,
5852                ))
5853                .bt()
5854            })?;
5855            // v1: destination contiguous + zero offset (same as WriteSlice).
5856            if !dest_layout.is_contiguous() || dest_layout.start_offset() != 0 {
5857                return Err(Error::Msg(format!(
5858                    "Op::WriteSliceRotating (v1): destination {:?} must be \
5859                     contiguous + zero-offset; got Layout {:?}",
5860                    dest, dest_layout,
5861                ))
5862                .bt());
5863            }
5864            let source_arc_contig = {
5865                let s_dtype = source_arc
5866                    .read()
5867                    .map_err(|_| poisoned("WriteSliceRotating source storage"))?
5868                    .dtype;
5869                let s_len_bytes = source_arc
5870                    .read()
5871                    .map_err(|_| poisoned("WriteSliceRotating source storage"))?
5872                    .inner
5873                    .len_bytes();
5874                let layout_bytes = source_layout.shape().elem_count() * s_dtype.size_in_bytes();
5875                let bytes_match_shape = s_len_bytes == layout_bytes;
5876                let already_contig = source_layout.is_contiguous()
5877                    && source_layout.start_offset() == 0
5878                    && bytes_match_shape;
5879                if already_contig {
5880                    source_arc
5881                } else {
5882                    auto_contiguize(&source_arc, &source_layout)?
5883                }
5884            };
5885            let source_layout_kernel = fuel_ir::Layout::contiguous(source_layout.shape().clone());
5886            let position_layout = fuel_ir::Layout::contiguous(fuel_ir::Shape::from_dims(&[]));
5887            let input_arcs = vec![source_arc_contig, position_arc];
5888            let mut output_arcs = vec![dest_arc.clone()];
5889            let kernel_layouts = vec![source_layout_kernel, position_layout, dest_layout.clone()];
5890            // A4b-1: defer the wait — return the handle to the realize loop.
5891            let handle = execute_compiled_with_wait_hint(
5892                compiled,
5893                &input_arcs,
5894                &mut output_arcs,
5895                &kernel_layouts,
5896                will_be_waited,
5897            )?;
5898            cache.insert(item.node_id, dest_arc);
5899            layout_cache.insert(item.node_id, item.output_layout.clone());
5900            Ok(handle)
5901        }
5902        WorkItemKind::WriteSliceDoff {
5903            dest,
5904            source,
5905            offset,
5906        } => {
5907            // Same shape as WriteSliceRotating: kernel sees
5908            // `[source, offset]` as inputs; `dest` is the pre-allocated
5909            // output buffer (in-place adoption). The offset (rank-0
5910            // I64) is passed through as a kernel input — the CUDA
5911            // wrapper threads its device pointer straight to the kernel
5912            // (no D2H), which is what makes a captured graph replay at
5913            // the host-updated position.
5914            let compiled = item.compiled.as_ref().ok_or_else(|| {
5915                Error::Msg(format!(
5916                    "PipelinedExecutor: WriteSliceDoff work item {:?} has no compiled node",
5917                    item.node_id,
5918                ))
5919                .bt()
5920            })?;
5921            let dest_arc = cache.get(dest).cloned().ok_or_else(|| {
5922                Error::Msg(format!(
5923                    "PipelinedExecutor: WriteSliceDoff destination {:?} of {:?} not realized",
5924                    dest, item.node_id,
5925                ))
5926                .bt()
5927            })?;
5928            let source_arc = cache.get(source).cloned().ok_or_else(|| {
5929                Error::Msg(format!(
5930                    "PipelinedExecutor: WriteSliceDoff source {:?} of {:?} not realized",
5931                    source, item.node_id,
5932                ))
5933                .bt()
5934            })?;
5935            let offset_arc = cache.get(offset).cloned().ok_or_else(|| {
5936                Error::Msg(format!(
5937                    "PipelinedExecutor: WriteSliceDoff offset {:?} of {:?} not realized",
5938                    offset, item.node_id,
5939                ))
5940                .bt()
5941            })?;
5942            let dest_layout = layout_cache.get(dest).cloned().ok_or_else(|| {
5943                Error::Msg(format!(
5944                    "PipelinedExecutor: WriteSliceDoff destination {:?} of {:?} has no cached layout",
5945                    dest, item.node_id,
5946                ))
5947                .bt()
5948            })?;
5949            let source_layout = layout_cache.get(source).cloned().ok_or_else(|| {
5950                Error::Msg(format!(
5951                    "PipelinedExecutor: WriteSliceDoff source {:?} of {:?} has no cached layout",
5952                    source, item.node_id,
5953                ))
5954                .bt()
5955            })?;
5956            // v1: destination contiguous + zero offset (same as WriteSlice).
5957            if !dest_layout.is_contiguous() || dest_layout.start_offset() != 0 {
5958                return Err(Error::Msg(format!(
5959                    "Op::WriteSliceDoff (v1): destination {:?} must be \
5960                     contiguous + zero-offset; got Layout {:?}",
5961                    dest, dest_layout,
5962                ))
5963                .bt());
5964            }
5965            let source_arc_contig = {
5966                let s_dtype = source_arc
5967                    .read()
5968                    .map_err(|_| poisoned("WriteSliceDoff source storage"))?
5969                    .dtype;
5970                let s_len_bytes = source_arc
5971                    .read()
5972                    .map_err(|_| poisoned("WriteSliceDoff source storage"))?
5973                    .inner
5974                    .len_bytes();
5975                let layout_bytes = source_layout.shape().elem_count() * s_dtype.size_in_bytes();
5976                let bytes_match_shape = s_len_bytes == layout_bytes;
5977                let already_contig = source_layout.is_contiguous()
5978                    && source_layout.start_offset() == 0
5979                    && bytes_match_shape;
5980                if already_contig {
5981                    source_arc
5982                } else {
5983                    auto_contiguize(&source_arc, &source_layout)?
5984                }
5985            };
5986            let source_layout_kernel = fuel_ir::Layout::contiguous(source_layout.shape().clone());
5987            let offset_layout = fuel_ir::Layout::contiguous(fuel_ir::Shape::from_dims(&[]));
5988            let input_arcs = vec![source_arc_contig, offset_arc];
5989            let mut output_arcs = vec![dest_arc.clone()];
5990            let kernel_layouts = vec![source_layout_kernel, offset_layout, dest_layout.clone()];
5991            // A4b-1: defer the wait — return the handle to the realize loop.
5992            let handle = execute_compiled_with_wait_hint(
5993                compiled,
5994                &input_arcs,
5995                &mut output_arcs,
5996                &kernel_layouts,
5997                will_be_waited,
5998            )?;
5999            cache.insert(item.node_id, dest_arc);
6000            layout_cache.insert(item.node_id, item.output_layout.clone());
6001            Ok(handle)
6002        }
6003        WorkItemKind::Alloc { target_location } => {
6004            // Op::Alloc { target }: allocate a fresh, zero-init storage
6005            // on target_location. No inputs, no kernel call — direct
6006            // executor dispatch. For non-CPU targets we derive the
6007            // per-backend device handle by searching the input cache
6008            // for any storage on the target backend (callers seed this
6009            // via `pipelined_bridge::device_seed_storage`).
6010            // Used only by the Vulkan arm below (alloc_bytes_handle); a
6011            // default-feature build sees it unused. GAP-229: 68161981's
6012            // unused_variables --fix renamed it `_n_bytes` at default
6013            // features and broke `--features vulkan` (E0425). Guard the
6014            // decline instead of the name so the binding stays usable.
6015            #[cfg_attr(not(feature = "vulkan"), allow(unused_variables))]
6016            let n_bytes = item.elem_count * item.dtype.size_in_bytes();
6017            let alloced: Storage = match target_location {
6018                // CPU has no separate uninit alloc primitive in safe
6019                // Rust (`vec![0; n]` is the canonical path). Op::Alloc
6020                // on CPU returns zero-init storage; the following
6021                // Op::ZeroFill is a redundant memset the optimizer
6022                // can elide and LLVM folds away regardless.
6023                DeviceLocation::Cpu => fuel_memory::alloc_cpu_zeroed(item.dtype, item.elem_count)?,
6024                #[cfg(feature = "cuda")]
6025                DeviceLocation::Cuda { gpu_id } => {
6026                    let cuda_dev = find_cuda_device_in_cache(cache, *gpu_id).ok_or_else(|| {
6027                        Error::Msg(format!(
6028                            "Op::Alloc on Cuda {{ gpu_id: {} }}: no CUDA \
6029                             storage in input cache to derive the device \
6030                             handle from. The caller must seed the cache \
6031                             (e.g. via `fuel-core::pipelined_bridge::\
6032                             device_seed_storage`) before realizing.",
6033                            gpu_id,
6034                        ))
6035                        .bt()
6036                    })?;
6037                    // Phase 3a follow-up: true uninit alloc via
6038                    // baracuda alpha.30's unsafe alloc. The bytes are
6039                    // uninit until a subsequent Op::ZeroFill or full-
6040                    // overwrite op runs. The byte-storage Arc has no
6041                    // typed-slice accessor that would dereference
6042                    // uninit bytes.
6043                    let cuda_bytes =
6044                        fuel_cuda_backend::CudaStorageBytes::alloc_uninit(&cuda_dev, n_bytes)?;
6045                    Storage::new(fuel_memory::BackendStorage::Cuda(cuda_bytes), item.dtype)
6046                }
6047                #[cfg(not(feature = "cuda"))]
6048                DeviceLocation::Cuda { .. } => {
6049                    return Err(Error::Msg(
6050                        "Op::Alloc on Cuda but fuel-storage wasn't built \
6051                         with --features cuda"
6052                            .to_string(),
6053                    )
6054                    .bt());
6055                }
6056                #[cfg(feature = "vulkan")]
6057                DeviceLocation::Vulkan { gpu_id } => {
6058                    let backend =
6059                        find_vulkan_backend_in_cache(cache, *gpu_id).ok_or_else(|| {
6060                            Error::Msg(format!(
6061                                "Op::Alloc on Vulkan {{ gpu_id: {} }}: no Vulkan \
6062                             storage in input cache to derive the backend \
6063                             handle from. The caller must seed the cache \
6064                             (e.g. via `fuel-core::pipelined_bridge::\
6065                             device_seed_storage`) before realizing.",
6066                                gpu_id,
6067                            ))
6068                            .bt()
6069                        })?;
6070                    // Phase 3a follow-up: true uninit alloc. The old
6071                    // `upload_bytes_handle(vec![0u8; n])` host-staged
6072                    // zeros (~2× the bandwidth of a device-side fill);
6073                    // we now allocate uninit and rely on a paired
6074                    // Op::ZeroFill (vkCmdFillBuffer) for the
6075                    // initialization. Faster KV-cache init on Vulkan.
6076                    let vk_bytes = backend.alloc_bytes_handle(n_bytes)?;
6077                    Storage::new(fuel_memory::BackendStorage::Vulkan(vk_bytes), item.dtype)
6078                }
6079                #[cfg(not(feature = "vulkan"))]
6080                DeviceLocation::Vulkan { .. } => {
6081                    return Err(Error::Msg(
6082                        "Op::Alloc on Vulkan but fuel-storage wasn't built \
6083                         with --features vulkan"
6084                            .to_string(),
6085                    )
6086                    .bt());
6087                }
6088                other => {
6089                    return Err(Error::Msg(format!(
6090                        "Op::Alloc on {:?}: target not yet wired (CPU + \
6091                         CUDA + Vulkan land in Phase 3a of bridge-retirement; \
6092                         Metal extends when its byte-storage substrate is \
6093                         ready).",
6094                        other,
6095                    ))
6096                    .bt());
6097                }
6098            };
6099            cache.insert(item.node_id, Arc::new(RwLock::new(alloced)));
6100            layout_cache.insert(item.node_id, item.output_layout.clone());
6101            Ok(CompletionHandle::Ready)
6102        }
6103        WorkItemKind::Iota { len } => {
6104            // Op::Iota { len }: 0-input F32 position generator
6105            // [0.0, 1.0, …, (len-1)]. Direct executor dispatch (no kernel /
6106            // binding-table lookup), like WorkItemKind::Alloc. CPU-only
6107            // today — GPU flash-attn keeps its fused kernel, so the alibi
6108            // decomposition (the sole Iota consumer) realizes on CPU.
6109            if item.target_backend != BackendId::Cpu {
6110                return Err(Error::Msg(format!(
6111                    "WorkItemKind::Iota: only CPU is wired today, got {:?}",
6112                    item.target_backend,
6113                ))
6114                .bt());
6115            }
6116            let v: Vec<f32> = (0..*len).map(|i| i as f32).collect();
6117            let iota = fuel_memory::from_slice_cpu(&v);
6118            cache.insert(item.node_id, Arc::new(RwLock::new(iota)));
6119            layout_cache.insert(item.node_id, item.output_layout.clone());
6120            Ok(CompletionHandle::Ready)
6121        }
6122        WorkItemKind::ZeroFill => {
6123            // Op::ZeroFill: in-place zero the input's bytes. Output
6124            // adopts the input's Storage Arc (same Storage; bytes
6125            // are mutated). Direct per-backend dispatch — no kernel
6126            // call, no binding-table lookup.
6127            if item.inputs.len() != 1 {
6128                return Err(Error::Msg(format!(
6129                    "PipelinedExecutor: ZeroFill work item {:?} expects \
6130                     1 input, got {}",
6131                    item.node_id,
6132                    item.inputs.len(),
6133                ))
6134                .bt());
6135            }
6136            let src_id = item.inputs[0];
6137            let src_arc = cache.get(&src_id).cloned().ok_or_else(|| {
6138                Error::Msg(format!(
6139                    "PipelinedExecutor: ZeroFill input {:?} of {:?} \
6140                     not realized",
6141                    src_id, item.node_id,
6142                ))
6143                .bt()
6144            })?;
6145            // Per-backend in-place fill. Acquired the write lock once
6146            // for the duration of the fill — kernels on async backends
6147            // (CUDA / Vulkan) issue the memset and return; the fence
6148            // happens when downstream readers acquire the read lock
6149            // through the executor's standard synchronization path.
6150            {
6151                let mut guard = src_arc
6152                    .write()
6153                    .map_err(|_| poisoned("ZeroFill destination storage"))?;
6154                match &mut guard.inner {
6155                    fuel_memory::BackendStorage::Cpu(c) => {
6156                        let bytes = c.bytes_mut();
6157                        bytes.fill(0);
6158                    }
6159                    #[cfg(feature = "cuda")]
6160                    fuel_memory::BackendStorage::Cuda(c) => {
6161                        c.zero_async()?;
6162                    }
6163                    #[cfg(feature = "vulkan")]
6164                    fuel_memory::BackendStorage::Vulkan(v) => {
6165                        let backend = v
6166                            .backend()
6167                            .ok_or_else(|| {
6168                                Error::Msg(
6169                                    "Op::ZeroFill on Vulkan: input has no \
6170                                 attached backend handle. Storage must \
6171                                 come from VulkanBackend::alloc_bytes_handle \
6172                                 / upload_bytes_handle."
6173                                        .to_string(),
6174                                )
6175                                .bt()
6176                            })?
6177                            .clone();
6178                        backend.fill_bytes_zero(v)?;
6179                    }
6180                    #[allow(unreachable_patterns)]
6181                    other => {
6182                        return Err(Error::Msg(format!(
6183                            "Op::ZeroFill: backend not wired ({other:?}); \
6184                             CPU + CUDA + Vulkan covered, Metal extends \
6185                             when its byte-storage substrate is ready.",
6186                        ))
6187                        .bt());
6188                    }
6189                }
6190            }
6191            // Adopt the (now-zero) Storage Arc at this node's slot.
6192            // Downstream readers go through `node_id`; the original
6193            // input's NodeId is evicted from the cache by the
6194            // realize loop's destructive_input cleanup.
6195            cache.insert(item.node_id, src_arc);
6196            layout_cache.insert(item.node_id, item.output_layout.clone());
6197            // A4b-1: ZeroFill's CUDA memset is same-stream (and Op::Alloc
6198            // typically zero-inits, so this is usually elided). Its completion
6199            // is carried by the realize-end full-stream sync in `to_cpu_bytes`
6200            // (unchanged) and same-stream ordering — `Ready` is behavior-preserving.
6201            Ok(CompletionHandle::Ready)
6202        }
6203        WorkItemKind::Copy { target_location } | WorkItemKind::Move { target_location } => {
6204            // Op::Copy / Op::Move { target }: kernel lookup at
6205            // (OpKind::Copy, [dt, dt], source_backend) — the wrapper
6206            // downloads from its own residency into a freshly-
6207            // allocated output on `target_location`. We auto-
6208            // contiguize the input first so the kernel always sees
6209            // the logical view's bytes (a transpose-view source
6210            // materializes into a contiguous buffer before download).
6211            //
6212            // Move shares this entire data-movement half; its
6213            // destructive half (release the source) is driven by the
6214            // realize loop's `destructive_input` cleanup after this
6215            // arm returns — see `WorkItemKind::Move`.
6216            let op_label = if matches!(item.kind, WorkItemKind::Move { .. }) {
6217                "Move"
6218            } else {
6219                "Copy"
6220            };
6221            let compiled = item.compiled.as_ref().ok_or_else(|| {
6222                Error::Msg(format!(
6223                    "PipelinedExecutor: {op_label} work item {:?} has no compiled node",
6224                    item.node_id,
6225                ))
6226                .bt()
6227            })?;
6228            if item.inputs.len() != 1 {
6229                return Err(Error::Msg(format!(
6230                    "PipelinedExecutor: {op_label} work item {:?} expects 1 input, got {}",
6231                    item.node_id,
6232                    item.inputs.len(),
6233                ))
6234                .bt());
6235            }
6236            let src_id = item.inputs[0];
6237            let src_arc = cache.get(&src_id).cloned().ok_or_else(|| {
6238                Error::Msg(format!(
6239                    "PipelinedExecutor: {op_label} input {:?} of {:?} not realized",
6240                    src_id, item.node_id,
6241                ))
6242                .bt()
6243            })?;
6244            // Multi-output Option C guard: Op::Copy on a bundled
6245            // producer would silently drop the bundle metadata on
6246            // the destination, and the auto-contiguize step below
6247            // would treat the bundle as a flat slot-0-shaped buffer
6248            // and corrupt non-primary slots. Until the per-backend
6249            // whole-bundle-Copy hook lands, point callers at the
6250            // supported per-slot path:
6251            // Op::View → Op::Copy → Op::ViewOwned.
6252            //
6253            // Exception: when the immediate input is an Op::View
6254            // projection (its layout's byte extent is strictly less
6255            // than the bundle's total bytes), the View has already
6256            // narrowed the slab. auto-contiguize walks the View's
6257            // layout and produces a flat slot-shaped buffer that's
6258            // correctly sized — no data loss, no slot corruption.
6259            // The guard only fires when the Copy targets the bundle
6260            // root directly.
6261            {
6262                let guard = src_arc
6263                    .read()
6264                    .map_err(|_| poisoned("Copy source storage"))?;
6265                if guard.is_bundled() {
6266                    let layout_bytes_for_guard = layout_cache
6267                        .get(&src_id)
6268                        .map(|l| l.shape().elem_count() * guard.dtype.size_in_bytes())
6269                        .unwrap_or(usize::MAX);
6270                    let bundle_bytes = guard.inner.len_bytes();
6271                    let is_whole_bundle = layout_bytes_for_guard >= bundle_bytes;
6272                    if is_whole_bundle {
6273                        return Err(Error::Msg(format!(
6274                            "PipelinedExecutor: Op::{op_label} on a bundled producer \
6275                             ({:?}) is not yet supported (Option C followup). \
6276                             Use Op::View → Op::Copy → Op::ViewOwned for \
6277                             per-slot cross-device moves, or wait for the \
6278                             per-backend whole-bundle-Copy hook.",
6279                            src_id,
6280                        ))
6281                        .bt());
6282                    }
6283                }
6284            }
6285            let src_layout = layout_cache.get(&src_id).cloned().ok_or_else(|| {
6286                Error::Msg(format!(
6287                    "PipelinedExecutor: {op_label} input {:?} of {:?} has no cached layout",
6288                    src_id, item.node_id,
6289                ))
6290                .bt()
6291            })?;
6292            let src_dtype = src_arc
6293                .read()
6294                .map_err(|_| poisoned("Copy source storage"))?
6295                .dtype;
6296            let src_len_bytes = src_arc
6297                .read()
6298                .map_err(|_| poisoned("Copy source storage"))?
6299                .inner
6300                .len_bytes();
6301            let layout_bytes = src_layout.shape().elem_count() * src_dtype.size_in_bytes();
6302            let bytes_match_shape = src_len_bytes == layout_bytes;
6303            let already_contig =
6304                src_layout.is_contiguous() && src_layout.start_offset() == 0 && bytes_match_shape;
6305            let src_input = if already_contig {
6306                src_arc
6307            } else {
6308                auto_contiguize(&src_arc, &src_layout)?
6309            };
6310            let kernel_input_layout = fuel_ir::Layout::contiguous(src_layout.shape().clone());
6311            // CapturedRun build-out (4b-ζ): in Reuse (capture/replay) mode,
6312            // reuse the fixed-address buffer recorded during the warm run
6313            // instead of allocating — device allocation is illegal inside a
6314            // capture scope. Only a same-device CUDA target_location ever
6315            // reaches Reuse mode for a Copy node in practice: capture_decode's
6316            // validation loop rejects every Cpu/Vulkan target_location before
6317            // a capture scope is ever entered (Move is rejected unconditionally
6318            // there too), so this arm trusts that invariant rather than
6319            // re-deriving it — the `DeviceLocation::Cuda` guard below is just
6320            // belt-and-suspenders for any other Reuse-mode caller.
6321            let reuse_arc = match &persistent {
6322                Some(p) if p.mode == PersistentMode::Reuse => match target_location {
6323                    DeviceLocation::Cuda { .. } => p.map.get(&item.node_id).cloned(),
6324                    _ => None,
6325                },
6326                _ => None,
6327            };
6328            // Allocate the output on `target_location`. Phase 2
6329            // covered D2H (target=Cpu); Phase 3b extends to H2D
6330            // (target=Cuda / Vulkan from a CPU source). For non-CPU
6331            // targets the executor's Op::Alloc-style device-handle
6332            // search applies (find_cuda_device_in_cache /
6333            // find_vulkan_backend_in_cache); callers seed the cache
6334            // (e.g. `pipelined_bridge::device_seed_storage`) before
6335            // realizing.
6336            // Used only by the Vulkan arm below (alloc_bytes_handle); a
6337            // default-feature build sees it unused. GAP-229: 68161981's
6338            // unused_variables --fix renamed it `_n_bytes` at default
6339            // features and broke `--features vulkan` (E0425). Guard the
6340            // decline instead of the name so the binding stays usable.
6341            #[cfg_attr(not(feature = "vulkan"), allow(unused_variables))]
6342            let n_bytes = item.elem_count * item.dtype.size_in_bytes();
6343            let input_arcs = vec![src_input];
6344            let mut output_arcs = if let Some(arc) = reuse_arc {
6345                vec![arc]
6346            } else {
6347                let output = match target_location {
6348                    DeviceLocation::Cpu => {
6349                        fuel_memory::alloc_cpu_zeroed(item.dtype, item.elem_count)?
6350                    }
6351                    #[cfg(feature = "cuda")]
6352                    DeviceLocation::Cuda { gpu_id } => {
6353                        let cuda_dev =
6354                            find_cuda_device_in_cache(cache, *gpu_id).ok_or_else(|| {
6355                                Error::Msg(format!(
6356                                    "Op::{op_label} on Cuda {{ gpu_id: {} }}: no CUDA \
6357                                 storage in input cache to derive the device \
6358                                 handle from. The caller must seed the cache \
6359                                 (e.g. via `fuel-core::pipelined_bridge::\
6360                                 device_seed_storage`) before realizing an \
6361                                 H2D Op::{op_label}.",
6362                                    gpu_id,
6363                                ))
6364                                .bt()
6365                            })?;
6366                        let cuda_bytes =
6367                            fuel_cuda_backend::CudaStorageBytes::alloc_uninit(&cuda_dev, n_bytes)?;
6368                        Storage::new(fuel_memory::BackendStorage::Cuda(cuda_bytes), item.dtype)
6369                    }
6370                    #[cfg(not(feature = "cuda"))]
6371                    DeviceLocation::Cuda { .. } => {
6372                        return Err(Error::Msg(format!(
6373                            "Op::{op_label} target Cuda but fuel-storage wasn't built \
6374                             with --features cuda",
6375                        ))
6376                        .bt());
6377                    }
6378                    #[cfg(feature = "vulkan")]
6379                    DeviceLocation::Vulkan { gpu_id } => {
6380                        let backend =
6381                            find_vulkan_backend_in_cache(cache, *gpu_id).ok_or_else(|| {
6382                                Error::Msg(format!(
6383                                    "Op::{op_label} on Vulkan {{ gpu_id: {} }}: no Vulkan \
6384                                 storage in input cache to derive the backend \
6385                                 handle from. The caller must seed the cache \
6386                                 (e.g. via `fuel-core::pipelined_bridge::\
6387                                 device_seed_storage`) before realizing an \
6388                                 H2D Op::{op_label}.",
6389                                    gpu_id,
6390                                ))
6391                                .bt()
6392                            })?;
6393                        let vk_bytes = backend.alloc_bytes_handle(n_bytes)?;
6394                        Storage::new(fuel_memory::BackendStorage::Vulkan(vk_bytes), item.dtype)
6395                    }
6396                    #[cfg(not(feature = "vulkan"))]
6397                    DeviceLocation::Vulkan { .. } => {
6398                        return Err(Error::Msg(format!(
6399                            "Op::{op_label} target Vulkan but fuel-storage wasn't built \
6400                             with --features vulkan",
6401                        ))
6402                        .bt());
6403                    }
6404                    other => {
6405                        return Err(Error::Msg(format!(
6406                            "PipelinedExecutor: Op::{op_label} target_location {:?} not yet \
6407                             wired (CPU + CUDA + Vulkan covered; Metal extends when \
6408                             its byte-storage substrate is ready).",
6409                            other
6410                        ))
6411                        .bt());
6412                    }
6413                };
6414                vec![Arc::new(RwLock::new(output))]
6415            };
6416            let kernel_layouts = vec![kernel_input_layout, item.output_layout.clone()];
6417            // A4b-1: defer the wait — return the handle to the realize loop.
6418            let handle = execute_compiled_with_wait_hint(
6419                compiled,
6420                &input_arcs,
6421                &mut output_arcs,
6422                &kernel_layouts,
6423                will_be_waited,
6424            )?;
6425            let arc = output_arcs.into_iter().next().expect("one output");
6426            // CapturedRun build-out (4b-ζ): Record (warm) mode remembers this
6427            // node's fixed output buffer so the capture run reuses the
6428            // identical device address. No-op in Reuse mode (the buffer came
6429            // FROM the map) and in None mode. Mirrors the Kernel arm's
6430            // Record-mode snapshot (above) exactly.
6431            if let Some(p) = persistent.as_deref_mut()
6432                && p.mode == PersistentMode::Record
6433            {
6434                p.map.insert(item.node_id, Arc::clone(&arc));
6435            }
6436            cache.insert(item.node_id, arc);
6437            layout_cache.insert(item.node_id, item.output_layout.clone());
6438            Ok(handle)
6439        }
6440        WorkItemKind::ReleaseMarker => {
6441            // Emit a zero-byte CPU storage at the Release node's
6442            // slot. Per Op::Release's contract the marker is never
6443            // read — this exists so any downstream cache lookup of
6444            // `release_id` resolves rather than failing. The actual
6445            // deallocation of `inputs[0]` is driven by the realize
6446            // loop's `destructive_input` cleanup (Phase B).
6447            let marker = fuel_memory::alloc_cpu_zeroed(item.dtype, 0)?;
6448            cache.insert(item.node_id, Arc::new(RwLock::new(marker)));
6449            layout_cache.insert(item.node_id, item.output_layout.clone());
6450            Ok(CompletionHandle::Ready)
6451        }
6452        WorkItemKind::ContiguizeOf { input } => {
6453            let input_arc = cache.get(input).cloned().ok_or_else(|| {
6454                Error::Msg(format!(
6455                    "PipelinedExecutor: reshape input {:?} of {:?} not realized",
6456                    input, item.node_id,
6457                ))
6458                .bt()
6459            })?;
6460            let input_layout = layout_cache.get(input).cloned().ok_or_else(|| {
6461                Error::Msg(format!(
6462                    "PipelinedExecutor: reshape input {:?} of {:?} has no cached layout",
6463                    input, item.node_id,
6464                ))
6465                .bt()
6466            })?;
6467            // CapturedRun build-out (4b-γ): in Reuse (capture/replay) mode,
6468            // reuse the fixed-address buffer recorded during the warm run —
6469            // device allocation is illegal inside a capture scope. Always
6470            // write-into when reusing (skip the zero-copy-vs-allocate
6471            // branch entirely): a given ContiguizeOf node's zero-copy-ness
6472            // is a static layout/stride property, identical across the warm
6473            // and capture passes (both replay the same compiled item list
6474            // with the same static layouts per capture_decode's own
6475            // design), so if this node ever needed the map entry it
6476            // allocated on warm too and the entry is guaranteed present.
6477            let reuse_arc = match &persistent {
6478                Some(p) if p.mode == PersistentMode::Reuse => p.map.get(&item.node_id).cloned(),
6479                _ => None,
6480            };
6481            let out_arc = if let Some(dest_arc) = reuse_arc {
6482                contiguize_into(&dest_arc, &input_arc, &input_layout)?;
6483                dest_arc
6484            } else if input_layout.is_contiguous() && input_layout.start_offset() == 0 {
6485                // Zero-copy when the input is already contiguous + zero
6486                // offset — never allocates, so Record mode has nothing to
6487                // record for this node (no fixed address to reuse).
6488                input_arc
6489            } else {
6490                // Allocate + copy via the contiguize kernel.
6491                let arc = auto_contiguize(&input_arc, &input_layout)?;
6492                if let Some(p) = persistent.as_deref_mut()
6493                    && p.mode == PersistentMode::Record
6494                {
6495                    p.map.insert(item.node_id, Arc::clone(&arc));
6496                }
6497                arc
6498            };
6499            cache.insert(item.node_id, out_arc);
6500            layout_cache.insert(item.node_id, item.output_layout.clone());
6501            // A4b-1: a materializing contiguize (CUDA) is same-stream; its
6502            // completion is carried by the realize-end full-stream sync in
6503            // `to_cpu_bytes` (unchanged) — `Ready` here is behavior-preserving.
6504            Ok(CompletionHandle::Ready)
6505        }
6506        WorkItemKind::Kernel => {
6507            let compiled = item.compiled.as_ref().ok_or_else(|| {
6508                Error::Msg(format!(
6509                    "PipelinedExecutor: Kernel work item {:?} has no compiled node",
6510                    item.node_id,
6511                ))
6512                .bt()
6513            })?;
6514            // Dynamic-M matmul (sparse MoE): resolve a DATA-DETERMINED row
6515            // count from the producer-bound `produced_syms` and run against
6516            // the patched (resolved-M) node. `None` on the common path.
6517            let patched_mm = resolve_deferred_matmul(compiled, produced_syms, item.node_id)?;
6518            let compiled = patched_mm.as_ref().unwrap_or(compiled);
6519            // Gather input Arcs from the cache, auto-contiguizing
6520            // any input whose layout is non-contiguous (typically
6521            // produced by an upstream metadata-only view op).
6522            // Today's kernels assume contiguous; this pass keeps
6523            // that invariant true at every kernel call site.
6524            //
6525            // We assemble a parallel `kernel_layouts` vec — the layout
6526            // of the bytes the kernel actually receives. After
6527            // auto-contiguize, that's `Layout::contiguous(shape)` for
6528            // the input's shape; for inputs already contiguous we use
6529            // the cached layout directly. Output layout comes last.
6530            let mut input_arcs: Vec<Arc<RwLock<Storage>>> = Vec::with_capacity(item.inputs.len());
6531            let mut kernel_layouts: Vec<fuel_ir::Layout> =
6532                Vec::with_capacity(item.inputs.len() + 1);
6533            // The kernel's `strided_input` cap lets non-contiguous
6534            // inputs (broadcast, transpose, etc.) flow through without
6535            // materialization — the kernel walks strides itself. Inputs
6536            // with non-zero `start_offset` still go through auto-
6537            // Contiguize today; offset honoring on the byte buffer is
6538            // a separate concern from stride support.
6539            let kernel_handles_strided = compiled.caps.strided_input;
6540            let t_gather = crate::compiled::op_profile::PhaseTimer::start("kernel.gather_inputs");
6541            for in_id in &item.inputs {
6542                let in_arc = cache.get(in_id).cloned().ok_or_else(|| {
6543                    Error::Msg(format!(
6544                        "PipelinedExecutor: input {:?} of {:?} not realized",
6545                        in_id, item.node_id,
6546                    ))
6547                    .bt()
6548                })?;
6549                let in_layout = layout_cache.get(in_id).cloned().ok_or_else(|| {
6550                    Error::Msg(format!(
6551                        "PipelinedExecutor: input {:?} of {:?} has no cached layout",
6552                        in_id, item.node_id,
6553                    ))
6554                    .bt()
6555                })?;
6556                // "Already contig" means more than `is_contiguous()`:
6557                // the LAYOUT's element count must also match the
6558                // STORAGE's byte count for shape-validating kernels
6559                // (concat_cpu, etc.) that read `storage.len_bytes()`.
6560                // A first-N slice view has `is_contiguous() == true`
6561                // (strides match canonical [1] for shape [N]) but its
6562                // storage is the parent's full bytes — too big. In
6563                // that case we auto-contiguize to materialize only
6564                // the view's portion as a fresh storage.
6565                //
6566                // Same constraint applies to strided_ok: kernels that
6567                // declare strided support can walk strided inputs, but
6568                // the byte count check at the kernel surface still
6569                // assumes storage.len_bytes() == layout.elem_count() *
6570                // dtype.size_bytes(). Until kernels universally trust
6571                // layout over storage, we conservatively materialize.
6572                let in_dtype = in_arc.read().map_err(|_| poisoned("input storage"))?.dtype;
6573                let in_len_bytes = in_arc
6574                    .read()
6575                    .map_err(|_| poisoned("input storage"))?
6576                    .inner
6577                    .len_bytes();
6578                let layout_bytes = in_layout.shape().elem_count() * in_dtype.size_in_bytes();
6579                let bytes_match_shape = in_len_bytes == layout_bytes;
6580                let already_contig =
6581                    in_layout.is_contiguous() && in_layout.start_offset() == 0 && bytes_match_shape;
6582                let strided_ok =
6583                    kernel_handles_strided && in_layout.start_offset() == 0 && bytes_match_shape;
6584                if already_contig || strided_ok {
6585                    input_arcs.push(in_arc);
6586                    kernel_layouts.push(in_layout);
6587                } else {
6588                    let contig_arc = auto_contiguize(&in_arc, &in_layout)?;
6589                    input_arcs.push(contig_arc);
6590                    kernel_layouts.push(fuel_ir::Layout::contiguous(in_layout.shape().clone()));
6591                }
6592            }
6593            drop(t_gather);
6594            kernel_layouts.push(item.output_layout.clone());
6595
6596            // Allocate output on the target backend. For GPU backends
6597            // we derive the device handle from the first input —
6598            // every kernel has ≥1 input (Op::Const is handled via
6599            // ConstAdopt, never via Kernel), and an input on the
6600            // target backend carries its own device. This avoids
6601            // threading a device handle through `realize`.
6602            //
6603            // Multi-output (Option C, item 3): when the WorkItem
6604            // carries an `output_bundle`, size the allocation to
6605            // span every slot's bytes (primary-dtype-element count
6606            // rounded up from the bundle's total byte span) and
6607            // attach the bundle metadata after allocation.
6608            let (alloc_elem_count, bundle_to_attach) = match &item.output_bundle {
6609                Some(bundle) => {
6610                    let dtype_bytes = item.dtype.size_in_bytes().max(1);
6611                    let total_bytes = bundle.iter().fold(0usize, |acc, s| {
6612                        let end = s.byte_offset.saturating_add(s.len_bytes());
6613                        acc.max(end)
6614                    });
6615                    let elems = total_bytes.div_ceil(dtype_bytes);
6616                    (elems, Some(Arc::clone(bundle)))
6617                }
6618                None => (item.elem_count, None),
6619            };
6620            // CapturedRun build-out: in Reuse (capture/replay) mode, reuse the
6621            // FIXED-ADDRESS buffer recorded during the warm run instead of
6622            // allocating — device allocation is illegal inside a capture scope,
6623            // and reusing the same address is what makes the captured graph's
6624            // baked kernel arguments valid on replay. In Record (warm) or None
6625            // mode, allocate as usual (below).
6626            let reuse_arc = match &persistent {
6627                Some(p) if p.mode == PersistentMode::Reuse => {
6628                    Some(p.map.get(&item.node_id).cloned().ok_or_else(|| {
6629                        Error::Msg(format!(
6630                            "PipelinedExecutor: capture (reuse) mode has no persistent \
6631                             output buffer for kernel node {:?}; the warm (record) run \
6632                             must realize every kernel node before capture",
6633                            item.node_id,
6634                        ))
6635                        .bt()
6636                    })?)
6637                }
6638                _ => None,
6639            };
6640            let t_alloc = crate::compiled::op_profile::PhaseTimer::start("kernel.alloc_output");
6641            let mut output_arcs = if let Some(arc) = reuse_arc {
6642                vec![arc]
6643            } else {
6644                let output = match item.target_backend {
6645                    BackendId::Cpu => fuel_memory::alloc_cpu_zeroed(item.dtype, alloc_elem_count)?,
6646                    #[cfg(feature = "cuda")]
6647                    BackendId::Cuda => {
6648                        let first_in = input_arcs.first().ok_or_else(|| {
6649                            Error::Msg(format!(
6650                                "PipelinedExecutor: kernel {:?} on Cuda has no inputs; \
6651                             cannot derive device for output allocation",
6652                                item.node_id,
6653                            ))
6654                            .bt()
6655                        })?;
6656                        let guard = first_in.read().map_err(|_| poisoned("input storage"))?;
6657                        let cuda_in = match &guard.inner {
6658                            fuel_memory::BackendStorage::Cuda(c) => c,
6659                            other => {
6660                                return Err(Error::Msg(format!(
6661                                    "PipelinedExecutor: kernel {:?} target_backend=Cuda but \
6662                                 input has BackendStorage::{:?}; mixed-backend kernels \
6663                                 require an explicit Op::Copy first",
6664                                    item.node_id,
6665                                    std::mem::discriminant(other),
6666                                ))
6667                                .bt());
6668                            }
6669                        };
6670                        let n_bytes = alloc_elem_count * item.dtype.size_in_bytes();
6671                        let cuda_bytes =
6672                            fuel_cuda_backend::CudaStorageBytes::alloc(cuda_in.device(), n_bytes)?;
6673                        fuel_memory::Storage::new(
6674                            fuel_memory::BackendStorage::Cuda(cuda_bytes),
6675                            item.dtype,
6676                        )
6677                    }
6678                    #[cfg(feature = "vulkan")]
6679                    BackendId::Vulkan => {
6680                        // Mirror the CUDA path: derive the backend handle
6681                        // from the first input's `VulkanStorageBytes::backend()`.
6682                        // Vulkan catch-up V.1.B (2026-05-21) — requires
6683                        // inputs constructed via `alloc_bytes_handle` /
6684                        // `upload_bytes_handle` so they carry the
6685                        // `Arc<VulkanBackend>` (mirroring CUDA's
6686                        // `Arc<CudaDevice>`).
6687                        let first_in = input_arcs.first().ok_or_else(|| {
6688                            Error::Msg(format!(
6689                                "PipelinedExecutor: kernel {:?} on Vulkan has no inputs; \
6690                             cannot derive backend handle for output allocation",
6691                                item.node_id,
6692                            ))
6693                            .bt()
6694                        })?;
6695                        let guard = first_in.read().map_err(|_| poisoned("input storage"))?;
6696                        let vk_in = match &guard.inner {
6697                            fuel_memory::BackendStorage::Vulkan(v) => v,
6698                            other => {
6699                                return Err(Error::Msg(format!(
6700                                    "PipelinedExecutor: kernel {:?} target_backend=Vulkan but \
6701                                 input has BackendStorage::{:?}; mixed-backend kernels \
6702                                 require an explicit Op::Copy first",
6703                                    item.node_id,
6704                                    std::mem::discriminant(other),
6705                                ))
6706                                .bt());
6707                            }
6708                        };
6709                        let backend = vk_in.backend().ok_or_else(|| {
6710                            Error::Msg(format!(
6711                                "PipelinedExecutor: Vulkan kernel {:?} input has no backend \
6712                             handle. Storages flowing through the pipelined executor's \
6713                             Vulkan path must be constructed via \
6714                             VulkanBackend::alloc_bytes_handle / upload_bytes_handle \
6715                             (not the legacy alloc_bytes / upload_bytes which leave \
6716                             VulkanStorageBytes::backend = None).",
6717                                item.node_id,
6718                            ))
6719                            .bt()
6720                        })?;
6721                        let n_bytes = alloc_elem_count * item.dtype.size_in_bytes();
6722                        let vk_bytes = backend.alloc_bytes_handle(n_bytes)?;
6723                        fuel_memory::Storage::new(
6724                            fuel_memory::BackendStorage::Vulkan(vk_bytes),
6725                            item.dtype,
6726                        )
6727                    }
6728                    other => {
6729                        return Err(Error::Msg(format!(
6730                            "PipelinedExecutor: target_backend {:?} output allocation \
6731                         not yet implemented (CPU + CUDA + Vulkan wired; Metal extends later)",
6732                            other
6733                        ))
6734                        .bt());
6735                    }
6736                };
6737                // Attach bundle metadata when this is a multi-output op.
6738                // The kernel sees the allocated bytes; the bundle lives
6739                // at the Storage wrapper level so downstream Op::View /
6740                // Op::ViewOwned can resolve their slot windows.
6741                let output = match bundle_to_attach {
6742                    Some(bundle) => output.with_bundle(bundle)?,
6743                    None => output,
6744                };
6745                vec![Arc::new(RwLock::new(output))]
6746            };
6747            drop(t_alloc);
6748
6749            // A4b-1: defer the wait — return the handle to the realize loop.
6750            let t_launch =
6751                crate::compiled::op_profile::PhaseTimer::start("kernel.execute_compiled");
6752            let handle = execute_compiled_with_wait_hint(
6753                compiled,
6754                &input_arcs,
6755                &mut output_arcs,
6756                &kernel_layouts,
6757                will_be_waited,
6758            )?;
6759            drop(t_launch);
6760
6761            let arc = output_arcs.into_iter().next().expect("one output");
6762
6763            // CapturedRun build-out: Record (warm) mode remembers this node's
6764            // fixed output buffer so the capture run reuses the identical
6765            // device address. No-op in Reuse mode (the buffer came FROM the
6766            // map) and in None mode.
6767            if let Some(p) = persistent
6768                && p.mode == PersistentMode::Record
6769            {
6770                p.map.insert(item.node_id, Arc::clone(&arc));
6771            }
6772
6773            // Data-determined dynamic-shapes seam (increment 2a): a
6774            // producer that computes a runtime count publishes it into the
6775            // per-pass `SymEnv` so downstream ops can consume it as a
6776            // dynamic extent. `Op::NonZeroIndices` writes its count into
6777            // bundle slot 1; read it back and bind `count_sym`. This is the
6778            // FIRST op to bind a *data-determined* symbol mid-realize (all
6779            // prior binds are host-known before realize). Single-threaded:
6780            // the executor runs items topologically, so this bind precedes
6781            // any consumer's execute-time resolution.
6782            if let OpParams::NonZeroIndices {
6783                capacity,
6784                count_sym,
6785            } = &compiled.op_params
6786            {
6787                bind_data_determined_count(&arc, *capacity, *count_sym, produced_syms)?;
6788            }
6789
6790            cache.insert(item.node_id, arc);
6791            layout_cache.insert(item.node_id, item.output_layout.clone());
6792            Ok(handle)
6793        }
6794        WorkItemKind::InplaceKernel { target_idx } => {
6795            let compiled = item.compiled.as_ref().ok_or_else(|| {
6796                Error::Msg(format!(
6797                    "PipelinedExecutor: InplaceKernel work item {:?} has no compiled node",
6798                    item.node_id,
6799                ))
6800                .bt()
6801            })?;
6802            let target_id = *item.inputs.get(*target_idx).ok_or_else(|| {
6803                Error::Msg(format!(
6804                    "PipelinedExecutor: InplaceKernel work item {:?} target_idx={} \
6805                     out of bounds (inputs.len()={})",
6806                    item.node_id,
6807                    target_idx,
6808                    item.inputs.len(),
6809                ))
6810                .bt()
6811            })?;
6812            let target_arc = cache.get(&target_id).cloned().ok_or_else(|| {
6813                Error::Msg(format!(
6814                    "PipelinedExecutor: InplaceKernel target {:?} of {:?} not realized",
6815                    target_id, item.node_id,
6816                ))
6817                .bt()
6818            })?;
6819            let target_layout = layout_cache.get(&target_id).cloned().ok_or_else(|| {
6820                Error::Msg(format!(
6821                    "PipelinedExecutor: InplaceKernel target {:?} of {:?} has no cached layout",
6822                    target_id, item.node_id,
6823                ))
6824                .bt()
6825            })?;
6826            // v1 contract: target must be contiguous + zero offset.
6827            // Strided in-place targets would force the kernel to walk
6828            // strides for writes too; defer until a concrete consumer
6829            // needs it (mirrors `Op::WriteSlice`'s v1 dest contract).
6830            if !target_layout.is_contiguous() || target_layout.start_offset() != 0 {
6831                return Err(Error::Msg(format!(
6832                    "InplaceKernel (Phase 3 v1): target {:?} must be contiguous + \
6833                     zero-offset; got Layout {:?}",
6834                    target_id, target_layout,
6835                ))
6836                .bt());
6837            }
6838            // Kernel sees inputs=[non-target IR inputs in order] and
6839            // outputs=[target_arc]. For unary in-place (1 IR input at
6840            // target_idx=0) the input vec is empty, matching the
6841            // original Phase 3e contract. For binary in-place
6842            // (target_idx=0, 2 IR inputs) the wrapper sees the
6843            // non-destructive RHS as `inputs[0]`. The wrapper acquires
6844            // outputs[0]'s write lock and mutates through its
6845            // bytes_mut(). Layout vector contains the kernel's
6846            // inputs+outputs layouts in that order.
6847            let mut input_arcs: Vec<Arc<RwLock<Storage>>> = Vec::new();
6848            let mut kernel_layouts: Vec<Layout> = Vec::new();
6849            for (i, &input_id) in item.inputs.iter().enumerate() {
6850                if i == *target_idx {
6851                    continue;
6852                }
6853                let arc = cache.get(&input_id).cloned().ok_or_else(|| {
6854                    Error::Msg(format!(
6855                        "PipelinedExecutor: InplaceKernel non-target input {:?} of {:?} \
6856                         not realized",
6857                        input_id, item.node_id,
6858                    ))
6859                    .bt()
6860                })?;
6861                let lay = layout_cache.get(&input_id).cloned().ok_or_else(|| {
6862                    Error::Msg(format!(
6863                        "PipelinedExecutor: InplaceKernel non-target input {:?} of {:?} \
6864                         has no cached layout",
6865                        input_id, item.node_id,
6866                    ))
6867                    .bt()
6868                })?;
6869                input_arcs.push(arc);
6870                kernel_layouts.push(lay);
6871            }
6872            let mut output_arcs = vec![target_arc.clone()];
6873            kernel_layouts.push(target_layout.clone());
6874            // A4b-1: defer the wait — return the handle to the realize loop.
6875            let handle = execute_compiled_with_wait_hint(
6876                compiled,
6877                &input_arcs,
6878                &mut output_arcs,
6879                &kernel_layouts,
6880                will_be_waited,
6881            )?;
6882            // Adopt the target Arc at this node's slot. The realize
6883            // loop's destructive_input cleanup evicts the target's own
6884            // NodeId from the cache afterward.
6885            cache.insert(item.node_id, target_arc);
6886            layout_cache.insert(item.node_id, item.output_layout.clone());
6887            Ok(handle)
6888        }
6889    }
6890}
6891
6892fn poisoned(what: &'static str) -> Error {
6893    Error::Msg(format!("PipelinedExecutor: {} poisoned", what)).bt()
6894}
6895
6896/// Step E A4b-1: record a node's [`CompletionHandle`] in the executor's
6897/// per-node handle map.
6898///
6899/// `Ready` handles (CPU / Vulkan / view-and-alloc arms) carry no async work, so
6900/// we DON'T store them — keeping the map to genuinely-pending entries makes the
6901/// realize-end empty-after-drain assert (open question #6) meaningful and keeps
6902/// the drain O(pending) rather than O(nodes). A re-used NodeId (in-place adopt
6903/// re-keys an existing slot) waits the prior handle first so nothing leaks.
6904#[inline]
6905fn store_handle(
6906    handles: &mut HashMap<NodeId, CompletionHandle>,
6907    node_id: NodeId,
6908    handle: CompletionHandle,
6909) {
6910    if matches!(handle, CompletionHandle::Ready) {
6911        // A prior pending handle at this slot must still be waited (don't drop a
6912        // Pending silently). In practice NodeIds are unique per realize, so this
6913        // is just defensive.
6914        if let Some(prev) = handles.remove(&node_id) {
6915            let _ = prev.wait();
6916        }
6917        return;
6918    }
6919    if let Some(prev) = handles.insert(node_id, handle) {
6920        let _ = prev.wait();
6921    }
6922}
6923
6924/// Step E A4b-3: the FINER cross-device producer wait.
6925///
6926/// Before dispatching a cross-device `Op::Copy` / `Op::Move` WorkItem, the
6927/// executor calls this on the copy's single source input. It removes the
6928/// source producer's [`CompletionHandle`] from the map and waits it — so the
6929/// specific producer P is complete before the D2H reads P's device buffer,
6930/// WITHOUT draining the whole source device (the conservative pre-A4b-3
6931/// behavior, where `to_cpu_bytes`'s `device.synchronize()` blocked on ALL
6932/// in-flight work on that device — including the OTHER sub-DAG's independent
6933/// work A4b-4 wants to overlap).
6934///
6935/// - **CUDA producer** → waits P's recorded `Event` (`cuEventSynchronize`):
6936///   fires after P + its already-ordered stream predecessors, nothing else.
6937/// - **Absent / `Ready` producer** (CPU producer, or a Vulkan producer — which
6938///   under A4b-2 is `Ready` mid-walk because nothing is submitted until
6939///   realize-end) → no-op. A Vulkan SOURCE's own ordering is handled inside
6940///   `download_bytes` (it `force_flush`es the open batch then reads), so there
6941///   is no mid-walk Vulkan handle to wait here; the cross-device Vulkan→CPU hop
6942///   stays correct without one.
6943///
6944/// Removing the handle here (rather than waiting it again at realize-end) keeps
6945/// `drain_handles`' post-drain empty-map assert meaningful and avoids a
6946/// double-wait. Waiting it twice would be harmless (`cuEventSynchronize` on an
6947/// already-signalled event is a fast no-op), but the consume-once contract is
6948/// cleaner. The producing node's *storage* stays in the cache for downstream
6949/// readers; only its completion handle is consumed.
6950fn wait_producer_handle(
6951    handles: &mut HashMap<NodeId, CompletionHandle>,
6952    producer: NodeId,
6953) -> Result<()> {
6954    if let Some(handle) = handles.remove(&producer) {
6955        handle.wait()?;
6956    }
6957    Ok(())
6958}
6959
6960/// Step E A4b-1: realize-end drain — wait every outstanding async handle, then
6961/// clear the map.
6962///
6963/// **Event-recording / wait strategy (A4b-1 §1.2).** CUDA has one stream per
6964/// device, and an `Event` recorded after a node's launch signals when that
6965/// node *and all prior stream work* have completed. So once the
6966/// latest-recorded event on a device has signalled, every earlier event on that
6967/// device is already signalled too: waiting them is a non-blocking
6968/// `cuEventQuery` fast-path, not N host stalls. We therefore wait every stored
6969/// handle (correct + simple).
6970///
6971/// **Open question #4 — "event only where waited" — RESOLVED.** Recording an
6972/// `Event` for every node was measured negligible on a 32-op synthetic, but
6973/// real decode graphs run 150-200+ ops; `pipelined`'s `WaitSet` pre-scan (see
6974/// `compiler_work_and_wait_set_for` / `build_wait_set`) now restricts event
6975/// production to the nodes some later cross-device `Copy`/`Move` will
6976/// individually wait — same-device-only ("elided") nodes get
6977/// `CompletionHandle::Ready` with no `cuEventCreate`/`cuEventRecord` at all
6978/// (`execute_compiled_with_wait_hint`). This drain therefore now retires only
6979/// the (typically few) wait-set handles that were never consumed mid-walk by
6980/// `wait_producer_handle`; it is no longer sufficient on its own to guarantee
6981/// every enqueued CUDA kernel has completed — `sync_active_cuda_devices` below
6982/// covers the elided remainder. We keep a per-node handle (rather than a
6983/// single per-device event) for the wait-set members because A4b-3's finer
6984/// cross-device wait needs to wait a *specific producer's* completion — the
6985/// per-node handle is that seam.
6986fn drain_handles(handles: &mut HashMap<NodeId, CompletionHandle>) -> Result<()> {
6987    for (_node, handle) in handles.drain() {
6988        handle.wait()?;
6989    }
6990    // Open question #6: once handles are stored instead of `wait`ed inline, the
6991    // `#[must_use]` on `CompletionHandle` can't catch a leaked (never-waited)
6992    // handle at the call site. The drain consumes the whole map, so it is empty
6993    // here by construction; assert it to catch a future leak (e.g. a new
6994    // dispatch path that forgets to thread its handle through `store_handle`).
6995    debug_assert!(
6996        handles.is_empty(),
6997        "A4b-1: handle map must be empty after drain"
6998    );
6999    Ok(())
7000}
7001
7002/// Step E A4b open question #4 step 3 — the realize-end complement to the
7003/// "event only where waited" elision. Because most CUDA nodes in a long
7004/// single-device chain no longer record an `Event` (see `drain_handles`'s
7005/// doc), this does ONE blanket `cuStreamSynchronize` per CUDA device that
7006/// still holds LIVE storage in `cache` — the realize target(s) plus any
7007/// surviving intermediates — instead of relying on per-node handles to cover
7008/// them.
7009///
7010/// **Why this is safe + sufficient.** CUDA has one stream per device, and
7011/// this executor dispatches strictly sequentially (one work item at a time,
7012/// in topological order) — so by the time a live node's own kernel was
7013/// launched, every same-device ancestor it depends on was ALREADY enqueued
7014/// earlier on the SAME stream. Stream ordering (not a host wait) guarantees
7015/// those ancestors run to completion no later than the live node's own
7016/// kernel. Syncing the live node's device therefore flushes its entire
7017/// same-device dependency chain, elided or not. Cross-device ancestors are
7018/// unaffected by elision — they always went through an `Op::Copy`/`Move`,
7019/// whose producer is in the `WaitSet` and was already waited explicitly at
7020/// the cross-device boundary (`wait_producer_handle`), mid-walk.
7021///
7022/// **Why evicted (non-live) intermediates don't need this.** A node whose
7023/// storage was evicted before realize-end (the `destructive_input` cleanup)
7024/// is never read by anything this realize returns; A3's stream-ordered
7025/// alloc/free already makes its eventual completion safe without a host
7026/// wait (the driver serializes the free after the freeing stream position,
7027/// same as any other stream-ordered op) — nothing to synchronize for.
7028///
7029/// No-op when `cache` holds no CUDA storage (CPU/Vulkan-only realize).
7030#[cfg(feature = "cuda")]
7031fn sync_active_cuda_devices(cache: &StorageCache) -> Result<()> {
7032    let mut devices: HashMap<fuel_ir::DeviceLocation, fuel_cuda_backend::CudaDevice> =
7033        HashMap::new();
7034    for arc in cache.values() {
7035        let guard = arc
7036            .read()
7037            .map_err(|_| poisoned("cache storage (cuda realize-end sync scan)"))?;
7038        if let fuel_memory::BackendStorage::Cuda(c) = &guard.inner {
7039            devices
7040                .entry(c.device().location())
7041                .or_insert_with(|| c.device().clone());
7042        }
7043    }
7044    for dev in devices.values() {
7045        dev.synchronize()?;
7046    }
7047    Ok(())
7048}
7049
7050/// Non-CUDA builds never produce CUDA storage, so there is nothing to sync —
7051/// keeps the call site unconditional across both feature configurations.
7052#[cfg(not(feature = "cuda"))]
7053fn sync_active_cuda_devices(_cache: &StorageCache) -> Result<()> {
7054    Ok(())
7055}
7056
7057/// Search the input cache for any `BackendStorage::Cuda(s)` whose
7058/// device matches `gpu_id`. Returns a clone of the `CudaDevice` Arc
7059/// the storage carries — the caller uses it to call
7060/// `CudaStorageBytes::alloc` for `Op::Alloc` on Cuda. Returns `None`
7061/// if no matching storage exists.
7062///
7063/// Phase 3a of bridge-retirement: callers seed the cache with a 0-byte
7064/// CUDA storage (`fuel-tensor::pipelined_bridge::device_seed_storage`)
7065/// so this lookup succeeds for the first Op::Alloc; subsequent
7066/// Op::Allocs see prior Op::Alloc outputs in the cache.
7067#[cfg(feature = "cuda")]
7068fn find_cuda_device_in_cache(
7069    cache: &StorageCache,
7070    gpu_id: usize,
7071) -> Option<fuel_cuda_backend::CudaDevice> {
7072    for arc in cache.values() {
7073        let guard = arc.read().ok()?;
7074        if let fuel_memory::BackendStorage::Cuda(c) = &guard.inner {
7075            // CudaDevice carries its DeviceLocation (gpu_id ordinal)
7076            // through `location()`; match against the target gpu_id.
7077            // Multi-GPU future work can refine the match; today's
7078            // single-GPU setups always match.
7079            if matches!(c.device().location(), DeviceLocation::Cuda { gpu_id: g } if g == gpu_id) {
7080                return Some(c.device().clone());
7081            }
7082        }
7083    }
7084    None
7085}
7086
7087/// Step E A4b-2: a Vulkan [`Completion`](crate::compiled::Completion) over an
7088/// in-flight (submitted, not-yet-waited) batch. `wait` blocks on the batch's
7089/// fence (`vkWaitForFences`) — which fires when the whole submitted command
7090/// buffer has retired on the single compute queue — then releases the batch
7091/// (frees the CB / descriptor sets / transient buffers / retired pool, all now
7092/// idle on the GPU).
7093///
7094/// The fence is per-BATCH, not per-node: one `submit_pending` flushes every op
7095/// recorded since the last submit, so this single handle covers a contiguous run
7096/// of Vulkan nodes (the A2 batching win, preserved — fewer fences, larger
7097/// submissions). `backend` keeps the [`VulkanBackend`] alive so the
7098/// post-fence pool retire + the `DeviceInner` the batch's resources reference
7099/// outlive the wait.
7100///
7101/// `Send` (required by `Completion`): every owned field is `Send` — `Fence` /
7102/// `CommandBuffer` / `DescriptorSet` / `Buffer` / `Allocation` / `CommandPool`
7103/// are all `Send` in vulkane (Arc-of-`DeviceInner` + explicit `unsafe impl`s),
7104/// and `Arc<VulkanBackend>` is `Send + Sync`.
7105/// Step E B1: `batch` is an `Option` ONLY so [`Drop`] can coexist with the
7106/// by-value `into_wait` consume. A type with a `Drop` impl cannot be
7107/// destructured by move (`let VulkanCompletion { backend, batch } = self`,
7108/// E0509), so `into_wait` `take()`s the batch out of the `Option` instead of
7109/// moving it out of the struct, then lets the normal `Drop` run. In every
7110/// reachable state the batch is `Some` until exactly one `into_wait` consumes it.
7111#[cfg(feature = "vulkan")]
7112struct VulkanCompletion {
7113    backend: Arc<fuel_vulkan_backend::VulkanBackend>,
7114    batch: Option<fuel_vulkan_backend::SubmittedBatch>,
7115    /// The device this submitted batch counts against in the in-flight counter
7116    /// (Step E B1). `Drop` decrements this slot.
7117    loc: fuel_ir::DeviceLocation,
7118}
7119
7120/// Step E A4b-4: the element type of the executor's in-flight-Vulkan-batch list.
7121/// A [`VulkanCompletion`] on a Vulkan build; a zero-sized placeholder otherwise
7122/// so the realize loops carry one `Vec<InflightVulkan>` local without `cfg` on
7123/// every use site (the helpers `eager_submit_all_vulkan` / `drain_inflight_vulkan`
7124/// are the only code that ever pushes/drains it, and they are `cfg`-gated).
7125#[cfg(feature = "vulkan")]
7126type InflightVulkan = VulkanCompletion;
7127#[cfg(not(feature = "vulkan"))]
7128type InflightVulkan = ();
7129
7130/// Step E A4b-4: is the cross-device copy's SOURCE buffer Vulkan-resident?
7131///
7132/// Used at the cross-device `Op::Copy`/`Op::Move` boundary to decide whether the
7133/// executor must wait the in-flight Vulkan batches before the copy. A Vulkan→CPU
7134/// D2H reads the source on the host, and the Vulkan `download` path only
7135/// `force_flush`es the OPEN batch (never the executor's eagerly-submitted
7136/// in-flight ones), so for a VULKAN source we must `drain_inflight_vulkan` first
7137/// to read completed data. For a CUDA / CPU source we must NOT wait Vulkan — the
7138/// copy doesn't read any Vulkan buffer, and waiting Vulkan there would needlessly
7139/// serialize the independent Vulkan sub-DAG (killing the overlap A4b-4 exists to
7140/// win). Returns `false` when the producer's storage isn't in the cache (treated
7141/// as not-Vulkan → no Vulkan wait; the CUDA/CPU producer handle still covers it).
7142#[cfg(feature = "vulkan")]
7143fn copy_source_is_vulkan(cache: &StorageCache, producer: NodeId) -> Result<bool> {
7144    if let Some(arc) = cache.get(&producer) {
7145        let guard = arc
7146            .read()
7147            .map_err(|_| poisoned("storage lock probing copy-source backend"))?;
7148        return Ok(matches!(
7149            guard.inner,
7150            fuel_memory::BackendStorage::Vulkan(_)
7151        ));
7152    }
7153    Ok(false)
7154}
7155
7156#[cfg(not(feature = "vulkan"))]
7157#[inline]
7158fn copy_source_is_vulkan(_cache: &StorageCache, _producer: NodeId) -> Result<bool> {
7159    Ok(false)
7160}
7161
7162#[cfg(feature = "vulkan")]
7163impl crate::compiled::Completion for VulkanCompletion {
7164    fn wait(self: Box<Self>) -> Result<()> {
7165        // Move the whole `VulkanCompletion` out of the `Box` (allowed even with a
7166        // `Drop` impl — it's a full move, not a destructure) and consume by value.
7167        (*self).into_wait()
7168    }
7169}
7170
7171#[cfg(feature = "vulkan")]
7172impl VulkanCompletion {
7173    /// Build the handle for an eagerly-submitted Vulkan batch and register it as
7174    /// one in-flight batch on `loc` (Step E B1). The matching decrement is in
7175    /// [`Drop`]. `loc` is the backend's `DeviceLocation::Vulkan { gpu_id }`.
7176    fn new(
7177        backend: Arc<fuel_vulkan_backend::VulkanBackend>,
7178        batch: fuel_vulkan_backend::SubmittedBatch,
7179        loc: fuel_ir::DeviceLocation,
7180    ) -> Self {
7181        crate::dispatch::inflight_inc(loc);
7182        Self {
7183            backend,
7184            batch: Some(batch),
7185            loc,
7186        }
7187    }
7188
7189    /// Block on this batch's fence, retire pools, then free the batch. Consumes
7190    /// `self` by value (the by-value sibling of the boxed `Completion::wait`),
7191    /// used by the executor's `inflight_vulkan` drain (A4b-4) where we hold the
7192    /// `VulkanCompletion` unboxed in a `Vec`.
7193    ///
7194    /// Step E B1: `take()`s the batch out of the `Option` (NOT a destructure
7195    /// move — that's illegal with a `Drop` impl) and waits it; the in-flight
7196    /// decrement then rides `self`'s `Drop` as this returns. So a wait-consume
7197    /// and a bare drop (e.g. an error unwinding before the wait) BOTH decrement
7198    /// exactly once, and `into_wait` never double-counts.
7199    fn into_wait(mut self) -> Result<()> {
7200        // `wait_submitted` consumes the batch by value: waits the fence, retires
7201        // pools, then drops the batch (UAF-safe — nothing the in-flight CB
7202        // references frees before the fence signals). After a `new` the batch is
7203        // always `Some`; `take` leaves `None` so `Drop` doesn't touch it again.
7204        if let Some(batch) = self.batch.take() {
7205            self.backend.wait_submitted(batch)?;
7206        }
7207        Ok(())
7208        // `self` drops here → `inflight_dec(self.loc)`.
7209    }
7210
7211    /// Step E A2.1 (deferred-deletion): retain an evicted DATA buffer until THIS
7212    /// in-flight batch's fence signals, then free it post-fence (on the batch's
7213    /// `Drop` — guaranteed post-fence by follow-on #2). Delegates to
7214    /// [`fuel_vulkan_backend::SubmittedBatch::retain_buffer`].
7215    ///
7216    /// The executor calls this for every in-flight batch when it evicts a Vulkan
7217    /// buffer those batches' CBs may read, INSTEAD of host-blocking on a drain.
7218    /// `batch` is `Some` in every reachable mid-walk state (it is `take`n only by
7219    /// `into_wait`/`wait`, which consume the whole `VulkanCompletion`), so the
7220    /// retain always lands on a live in-flight batch.
7221    fn retain_data(&mut self, buf: std::sync::Arc<fuel_vulkan_backend::VulkanBuffer>) {
7222        if let Some(batch) = self.batch.as_mut() {
7223            batch.retain_buffer(buf);
7224        }
7225    }
7226}
7227
7228#[cfg(feature = "vulkan")]
7229impl Drop for VulkanCompletion {
7230    fn drop(&mut self) {
7231        // The single in-flight decrement for a Vulkan batch — fires whether the
7232        // batch was waited (`into_wait` / `wait`) or merely dropped (error
7233        // unwind), so the per-device count returns to baseline. Relaxed +
7234        // saturating (a scheduling hint, never a correctness gate).
7235        crate::dispatch::inflight_dec(self.loc);
7236    }
7237}
7238
7239/// Step E A4b-4 — eager Vulkan submission during the walk (the OVERLAP enabler).
7240///
7241/// Submits each DISTINCT Vulkan backend's currently-open batch WITHOUT waiting,
7242/// pushing the resulting in-flight [`VulkanCompletion`]s onto `inflight` so the
7243/// executor waits them later (at the in-flight-lifetime guard / realize-end). An
7244/// empty open batch yields `None` and is skipped (idempotent).
7245///
7246/// This is what makes a Vulkan sub-DAG actually START on the iGPU while the
7247/// executor records/dispatches the next (CUDA) chunk — without it the Vulkan
7248/// batch sits merely *recorded* until realize-end and never overlaps the CUDA
7249/// stream (design §5). Called ONLY on a genuinely multi-backend realize (gated by
7250/// the executor's `multi_backend` flag); on a single-device graph it is never
7251/// reached, so pure-Vulkan stays byte-identical to A4b-2 (one realize-end submit).
7252///
7253/// **Whole-chunk granularity (UAF/race-safety, design §4 + the Vulkan
7254/// single-queue OOO-completion semantics).** We submit only at chunk boundaries
7255/// and before a cross-device wait — never mid-chunk — so the batch handed to the
7256/// GPU is a COMPLETE contiguous run of Vulkan nodes with all its intra-CB
7257/// dependency barriers (`recorder.rs` `vkCmdPipelineBarrier`) already in place.
7258/// Vulkan only guarantees that batches on one queue BEGIN in submission order;
7259/// they may overlap / complete out of order, so a split mid-chunk would lose the
7260/// write-before-read ordering for ops that read an earlier op's buffer in the
7261/// SAME chunk. By submitting whole chunks and re-syncing (`drain_inflight_vulkan`)
7262/// before any later Vulkan op records, before any cross-device copy, and before
7263/// any Vulkan-referenced eviction, no in-flight batch is ever read or freed while
7264/// still running.
7265#[cfg(feature = "vulkan")]
7266fn eager_submit_all_vulkan(
7267    cache: &StorageCache,
7268    inflight: &mut Vec<VulkanCompletion>,
7269) -> Result<()> {
7270    // Collect distinct Vulkan backends referenced by the cache (dedup by gpu_id).
7271    let mut seen: Vec<usize> = Vec::new();
7272    let mut backends: Vec<Arc<fuel_vulkan_backend::VulkanBackend>> = Vec::new();
7273    for arc in cache.values() {
7274        let guard = arc
7275            .read()
7276            .map_err(|_| poisoned("storage lock during eager vulkan submit"))?;
7277        if let fuel_memory::BackendStorage::Vulkan(v) = &guard.inner
7278            && let Some(backend) = v.backend()
7279            && !seen.contains(&backend.gpu_id)
7280        {
7281            seen.push(backend.gpu_id);
7282            backends.push(backend.clone());
7283        }
7284    }
7285    for backend in backends {
7286        // Step E B1: the per-device location for the in-flight counter. A batch
7287        // submitted here is one in-flight unit on this iGPU until its handle's
7288        // `Drop` (after `drain_inflight_vulkan` / realize-end).
7289        let loc = DeviceLocation::Vulkan {
7290            gpu_id: backend.gpu_id,
7291        };
7292        if let Some(batch) = backend.submit_pending()? {
7293            inflight.push(VulkanCompletion::new(backend, batch, loc));
7294        }
7295    }
7296    Ok(())
7297}
7298
7299#[cfg(not(feature = "vulkan"))]
7300#[inline]
7301fn eager_submit_all_vulkan(
7302    _cache: &StorageCache,
7303    _inflight: &mut Vec<InflightVulkan>,
7304) -> Result<()> {
7305    Ok(())
7306}
7307
7308/// Step E A4b-4 — wait every in-flight (eagerly-submitted) Vulkan batch, then
7309/// clear the list. The re-sync half of [`eager_submit_all_vulkan`].
7310///
7311/// Each `into_wait` blocks on the batch fence (`vkWaitForFences`), retires the
7312/// backend's descriptor pools, and frees the batch (CB / descriptor sets /
7313/// transient buffers / retired command pool — all now idle on the GPU). After
7314/// this returns, NO submitted Vulkan command buffer is still executing, so it is
7315/// safe to (a) record a new Vulkan op that may read a just-produced buffer,
7316/// (b) D2H-copy a Vulkan buffer on the host, or (c) free a buffer a batch read.
7317///
7318/// Because the eager submit happened at the PRIOR chunk boundary and an
7319/// intervening (e.g. CUDA) chunk has since been recorded/dispatched, the fence is
7320/// typically already signalled here — the wait is a fast no-op, and the iGPU work
7321/// genuinely overlapped the other device's stream. Waiting the Vulkan fence does
7322/// NOT touch the CUDA stream, so the other device keeps running (concurrency
7323/// preserved — design §5 "the per-device guards don't cross-stall").
7324#[cfg(feature = "vulkan")]
7325fn drain_inflight_vulkan(inflight: &mut Vec<VulkanCompletion>) -> Result<()> {
7326    for vc in inflight.drain(..) {
7327        vc.into_wait()?;
7328    }
7329    Ok(())
7330}
7331
7332#[cfg(not(feature = "vulkan"))]
7333#[inline]
7334fn drain_inflight_vulkan(_inflight: &mut Vec<InflightVulkan>) -> Result<()> {
7335    Ok(())
7336}
7337
7338/// Step E A4b-2: the realize-end Vulkan drain, SPLIT into submit-then-wait.
7339///
7340/// Replaces A2's `force_flush_all_vulkan` (which submitted + waited atomically
7341/// inside `force_flush`). For each DISTINCT Vulkan backend referenced by the
7342/// cache, `submit_pending` submits the still-open batch WITHOUT waiting (→ a
7343/// `SubmittedBatch`), wraps it in the executor's [`VulkanCompletion`] handle, and
7344/// `wait`s it. Net for a pure-Vulkan realize: the batch still accumulates across
7345/// the whole walk (the per-op path keeps returning `Ready`; no eager submit —
7346/// that is A4b-4) and is submitted ONCE here, then waited — **byte-identical to
7347/// A2**, same single submission at realize-end, just split through the handle.
7348///
7349/// Idempotent across repeated cache arcs: the first `submit_pending` on a backend
7350/// returns `Some(batch)`; subsequent calls on the same backend see an empty batch
7351/// and return `None` (skipped) — exactly the `force_flush` idempotence A2 relied
7352/// on. No-op for a non-Vulkan build.
7353#[cfg(feature = "vulkan")]
7354fn drain_vulkan_pending(cache: &StorageCache) -> Result<()> {
7355    use crate::compiled::CompletionHandle;
7356    for arc in cache.values() {
7357        let backend = {
7358            let guard = arc
7359                .read()
7360                .map_err(|_| poisoned("storage lock during vulkan submit_pending"))?;
7361            match &guard.inner {
7362                fuel_memory::BackendStorage::Vulkan(v) => v.backend().cloned(),
7363                _ => None,
7364            }
7365        };
7366        let Some(backend) = backend else { continue };
7367        // Submit the open batch (if any) without waiting, then wait via the
7368        // completion handle. Empty batch → None → nothing to wait.
7369        // Step E B1: `new` increments the in-flight counter for this device;
7370        // `handle.wait()` waits + drops the `VulkanCompletion`, decrementing it
7371        // — a balanced submit/retire even on this transient realize-end path.
7372        let loc = DeviceLocation::Vulkan {
7373            gpu_id: backend.gpu_id,
7374        };
7375        if let Some(batch) = backend.submit_pending()? {
7376            let handle: CompletionHandle =
7377                CompletionHandle::Pending(Box::new(VulkanCompletion::new(backend, batch, loc)));
7378            handle.wait()?;
7379        }
7380    }
7381    Ok(())
7382}
7383
7384#[cfg(not(feature = "vulkan"))]
7385fn drain_vulkan_pending(_cache: &StorageCache) -> Result<()> {
7386    Ok(())
7387}
7388
7389/// Step E A2: force the Vulkan backend behind `arc` (if any) to submit + WAIT
7390/// its open batch — the blocking drain before freeing a buffer the batch may
7391/// reference (a destructive eviction) so a recorded-but-unsubmitted command never
7392/// reads freed memory. No-op for non-Vulkan storage, an empty batch, or a
7393/// non-Vulkan build.
7394///
7395/// **Retained for the SINGLE-DEVICE path (byte-identical to pre-A2.1).** A2.1's
7396/// deferred-deletion ([`defer_evicted_vulkan_buffer`]) replaces this only on a
7397/// MULTI-backend realize, where eager-submit + in-flight tracking + the
7398/// realize-end `drain_inflight_vulkan` are all live. On a single-device Vulkan
7399/// realize the A4b machinery is gated off (`multi_backend == false`): the
7400/// cross-batch RAW guard (`pipelined.rs:832`) does not run, so a later Vulkan op
7401/// reading a buffer an eager-submitted batch wrote could race (separate
7402/// submissions only BEGIN in order, may overlap). The blocking `force_flush`
7403/// (submit + wait) is the coherent eviction drain there — exactly the original
7404/// behavior — so single-device stays byte-identical and UAF-safe.
7405#[cfg(feature = "vulkan")]
7406fn force_flush_vulkan(arc: &Arc<RwLock<Storage>>) -> Result<()> {
7407    let guard = arc
7408        .read()
7409        .map_err(|_| poisoned("storage lock during vulkan force_flush"))?;
7410    if let fuel_memory::BackendStorage::Vulkan(v) = &guard.inner
7411        && let Some(backend) = v.backend()
7412    {
7413        backend.force_flush()?;
7414    }
7415    Ok(())
7416}
7417
7418#[cfg(not(feature = "vulkan"))]
7419fn force_flush_vulkan(_arc: &Arc<RwLock<Storage>>) -> Result<()> {
7420    Ok(())
7421}
7422
7423/// Step E A2.1 — DEFERRED-DELETION of a Vulkan data buffer evicted while Vulkan
7424/// work is in flight (the throughput refinement that REPLACES the eviction-time
7425/// drain on a MULTI-backend realize). Called at the per-NodeId destructive
7426/// eviction (`Op::Release`/`Op::Move` cleanup) for the buffer about to leave the
7427/// cache, INSTEAD of `drain_inflight_vulkan` + `force_flush` (two host-blocking
7428/// fence waits) — so the iGPU work the executor was overlapping with CUDA is not
7429/// stalled at every eviction.
7430///
7431/// Two classes of Vulkan reader can hold a reference to `destroyed`'s buffer at
7432/// the eviction:
7433///   1. the **in-flight** `SubmittedBatch`es in `inflight` (submitted CBs, each
7434///      fenced), and
7435///   2. the **open**, not-yet-submitted recorder batch (recorded commands, NO
7436///      fence yet).
7437///
7438/// We make BOTH fence-gated without blocking the host:
7439///   - `eager_submit_all_vulkan` submits the open batch WITHOUT waiting, turning
7440///     it into one more in-flight `SubmittedBatch` (now fenced) pushed onto
7441///     `inflight`. (Whole-chunk granularity — UAF/race-safe per its contract; at a
7442///     destructive eviction the open batch is a contiguous Vulkan run.)
7443///   - We then move a refcount clone of the evicted buffer's `Arc<VulkanBuffer>`
7444///     into EVERY in-flight batch (conservative: we cannot cheaply map
7445///     buffer→batch, exactly the reason the old drain waited *all* of them). Each
7446///     batch frees its retained clone POST-fence on `Drop` (follow-on #2).
7447///
7448/// After this returns the caller `cache.remove`s `destroyed`; the cache's
7449/// `Arc<RwLock<Storage>>` drops, but the buffer's recycler
7450/// (`VulkanBuffer::drop`) reclaims it only when its LAST `Arc` drops — and the
7451/// retained clones keep it alive until their owning batches' fences signal. So the
7452/// GPU's last read of the buffer strictly precedes the free (NO use-after-free),
7453/// the host never blocks at the eviction (the iGPU keeps overlapping CUDA — the
7454/// throughput win), and every batch (hence every retained buffer) is drained by
7455/// realize-end at the latest (`drain_inflight_vulkan`, `pipelined.rs:916/1238`,
7456/// runs unconditionally → NO leak).
7457///
7458/// **Multi-backend only** (the call site gates `if multi_backend`). On a
7459/// single-device realize the open batch is drained by the blocking
7460/// [`force_flush_vulkan`] instead (byte-identical to pre-A2.1; see its doc for
7461/// why the deferred path is unsafe without the cross-batch RAW guard). No-op for a
7462/// non-Vulkan storage, an empty open + no in-flight batches, or a non-Vulkan build.
7463/// Open-batch size (dispatches) at which a deferred eviction submits the batch so the
7464/// GPU runs it while the host keeps recording.
7465#[cfg(feature = "vulkan")]
7466const EVICT_SUBMIT_MIN_DISPATCHES: usize = 48;
7467
7468#[cfg(feature = "vulkan")]
7469fn defer_evicted_vulkan_buffer(
7470    cache: &StorageCache,
7471    destroyed: NodeId,
7472    inflight: &mut Vec<VulkanCompletion>,
7473) -> Result<()> {
7474    // Pull the evicted buffer's device Arc (and its backend) out of the cache BEFORE
7475    // it is removed. Non-Vulkan storage, a host-evicted (no device buffer) Vulkan
7476    // storage, or an absent entry → nothing to retain (no Vulkan reader can hold a
7477    // device buffer).
7478    let (buf, backend) = {
7479        let Some(arc) = cache.get(&destroyed) else {
7480            return Ok(());
7481        };
7482        let guard = arc
7483            .read()
7484            .map_err(|_| poisoned("storage lock during deferred-eviction retain"))?;
7485        match &guard.inner {
7486            fuel_memory::BackendStorage::Vulkan(v) => (v.device_buffer_arc(), v.backend().cloned()),
7487            _ => (None, None),
7488        }
7489    };
7490    let Some(buf) = buf else { return Ok(()) };
7491
7492    // The OPEN batch may hold recorded-but-unsubmitted commands that read `destroyed`:
7493    // retain the buffer on the open batch itself (freed post-fence once that batch is
7494    // submitted and waited). This neither submits nor waits — it used to eager-submit
7495    // here, i.e. one queue submit per eviction (61 per Qwen3 decode step).
7496    if let Some(backend) = &backend {
7497        backend.retain_in_open_batch(buf.clone());
7498    }
7499    // Retain a clone of the evicted buffer in EVERY in-flight batch. Each frees it
7500    // POST-fence on `Drop` — the buffer outlives the GPU's last read with no host
7501    // block. Conservative over all batches (no cheap buffer→batch map); over-retention
7502    // only lengthens the lifetime, never a UAF, and all batches drain by realize-end.
7503    for vc in inflight.iter_mut() {
7504        vc.retain_data(buf.clone());
7505    }
7506    // Keep the GPU fed: submit the open batch once it has grown by a chunk.
7507    if let Some(backend) = backend
7508        && backend.open_batch_len() >= EVICT_SUBMIT_MIN_DISPATCHES
7509    {
7510        eager_submit_all_vulkan(cache, inflight)?;
7511    }
7512    // Step E A2.1 — throughput-observability. Count a DEFERRED retain that
7513    // actually replaced a host block: an evicted Vulkan buffer retained onto ≥1
7514    // in-flight batch (the open-batch eager-submit and/or pre-existing in-flight
7515    // batches). Pre-A2.1 every such site host-blocked (`force_flush` and/or
7516    // `drain_inflight_vulkan`); now it does not. A test reads
7517    // [`deferred_eviction_retains`] to assert the deferred path fired without a
7518    // drain (deterministic — no wall-clock, which is noisy on this box). When
7519    // `inflight` is empty here there was genuinely no in-flight/open Vulkan reader
7520    // to wait for, so no host block was avoided (and none was needed) — not counted.
7521    if !inflight.is_empty() {
7522        DEFERRED_EVICTION_RETAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7523    }
7524    Ok(())
7525}
7526
7527/// Step E A2.1 — cumulative count of deferred-deletion retains that replaced a
7528/// host-blocking eviction drain (an evicted Vulkan buffer retained onto ≥1
7529/// in-flight batch instead of waiting it). Process-global, `Relaxed` — a pure
7530/// test/telemetry observation, never a correctness gate (mirrors the B1 in-flight
7531/// counter idiom). Read by the live deferred-eviction throughput test.
7532#[cfg(feature = "vulkan")]
7533pub static DEFERRED_EVICTION_RETAINS: std::sync::atomic::AtomicUsize =
7534    std::sync::atomic::AtomicUsize::new(0);
7535
7536/// Read the A2.1 deferred-eviction-retain counter (see
7537/// [`DEFERRED_EVICTION_RETAINS`]). `pub` so the live throughput test can assert a
7538/// deferred retain fired (the eviction did NOT host-block on a Vulkan fence).
7539#[cfg(feature = "vulkan")]
7540pub fn deferred_eviction_retains() -> usize {
7541    DEFERRED_EVICTION_RETAINS.load(std::sync::atomic::Ordering::Relaxed)
7542}
7543
7544#[cfg(not(feature = "vulkan"))]
7545#[inline]
7546fn defer_evicted_vulkan_buffer(
7547    _cache: &StorageCache,
7548    _destroyed: NodeId,
7549    _inflight: &mut Vec<InflightVulkan>,
7550) -> Result<()> {
7551    Ok(())
7552}
7553
7554/// Vulkan counterpart of [`find_cuda_device_in_cache`]. Returns an
7555/// `Arc<VulkanBackend>` clone derived from any cached Vulkan storage
7556/// whose backend's `gpu_id` matches.
7557#[cfg(feature = "vulkan")]
7558fn find_vulkan_backend_in_cache(
7559    cache: &StorageCache,
7560    gpu_id: usize,
7561) -> Option<std::sync::Arc<fuel_vulkan_backend::VulkanBackend>> {
7562    for arc in cache.values() {
7563        let guard = arc.read().ok()?;
7564        if let fuel_memory::BackendStorage::Vulkan(v) = &guard.inner
7565            && let Some(backend) = v.backend()
7566            && backend.gpu_id == gpu_id
7567        {
7568            return Some(backend.clone());
7569        }
7570    }
7571    None
7572}
7573
7574/// Materialize a contiguous Storage Arc from a non-contiguous one.
7575/// Allocates a fresh buffer on the input's backend and copies the
7576/// strided / offset / broadcast input into it via the backend's
7577/// contiguize kernel. The returned Arc is a brand-new buffer; the
7578/// caller is responsible for replacing the cache entry only for the
7579/// duration of one kernel call (the upstream view op's output stays
7580/// in the cache so other consumers still see the strided view).
7581///
7582/// Stage 4 of Layout-on-Node — auto-Contiguize.
7583fn auto_contiguize(arc: &Arc<RwLock<Storage>>, layout: &Layout) -> Result<Arc<RwLock<Storage>>> {
7584    let in_guard = arc
7585        .read()
7586        .map_err(|_| poisoned("input storage lock during auto_contiguize"))?;
7587    let dtype = in_guard.dtype;
7588    let dtype_size = dtype.size_in_bytes();
7589    let new_storage = match &in_guard.inner {
7590        fuel_memory::BackendStorage::Cpu(c) => {
7591            let new_bytes = fuel_cpu_backend::byte_kernels::contiguize_cpu(c, layout, dtype_size)?;
7592            Storage::new(fuel_memory::BackendStorage::Cpu(new_bytes), dtype)
7593        }
7594        #[cfg(feature = "cuda")]
7595        fuel_memory::BackendStorage::Cuda(c) => {
7596            // Native baracuda contiguize (alpha.29). Byte-width-
7597            // dispatched: 1/2/4/8/16 byte elements all route to the
7598            // appropriate kernel. Handles signed strides (Flip),
7599            // zero strides (BroadcastTo), and non-zero element offset.
7600            //
7601            // Three host-side fast paths bake into the baracuda
7602            // launchers: already-contiguous → single cuMemcpyDtoDAsync;
7603            // innermost-stride-1 → per-outer-coord run copy; generic
7604            // → one thread per output element. Retires the prior
7605            // D2H → CPU contiguize_cpu → H2D fallback (two device
7606            // round-trips per non-contig input).
7607            let contig = fuel_cuda_backend::baracuda::contiguize::contiguize_to_fresh(
7608                c, layout, dtype_size,
7609            )?;
7610            Storage::new(fuel_memory::BackendStorage::Cuda(contig), dtype)
7611        }
7612        #[cfg(feature = "vulkan")]
7613        fuel_memory::BackendStorage::Vulkan(v) => {
7614            // Native `strided_copy_signed_*` kernel when it applies (2/4/8-byte
7615            // elements; see `contiguize_vulkan`). Otherwise the V.1.B host round trip:
7616            // D2H → CPU contiguize_cpu → H2D, which forces a flush and a wait
7617            // per call.
7618            let backend = v.backend().ok_or_else(|| {
7619                Error::Msg(
7620                    "auto_contiguize: Vulkan input has no backend handle. \
7621                     Storages flowing through the pipelined executor's Vulkan \
7622                     path must be constructed via VulkanBackend::alloc_bytes_handle \
7623                     / upload_bytes_handle (not the legacy alloc_bytes / \
7624                     upload_bytes which leave VulkanStorageBytes::backend = None)."
7625                        .to_string(),
7626                )
7627                .bt()
7628            })?;
7629            if let Some(native) = crate::vulkan_dispatch::contiguize_vulkan(v, layout, dtype_size)?
7630            {
7631                return Ok(Arc::new(RwLock::new(Storage::new(
7632                    fuel_memory::BackendStorage::Vulkan(native),
7633                    dtype,
7634                ))));
7635            }
7636            let _t = crate::compiled::op_profile::PhaseTimer::start(
7637                "auto_contiguize.vulkan_host_roundtrip",
7638            );
7639            let host_bytes = backend.download_bytes(v)?;
7640            let host_cpu = fuel_cpu_backend::byte_storage::CpuStorageBytes::from_bytes(&host_bytes);
7641            let contig_cpu =
7642                fuel_cpu_backend::byte_kernels::contiguize_cpu(&host_cpu, layout, dtype_size)?;
7643            let host_contig_bytes = contig_cpu.bytes().to_vec();
7644            let vk_bytes = backend.upload_bytes_handle(&host_contig_bytes)?;
7645            Storage::new(fuel_memory::BackendStorage::Vulkan(vk_bytes), dtype)
7646        }
7647        #[allow(unreachable_patterns)]
7648        _ => {
7649            return Err(Error::Msg(
7650                "auto_contiguize: backend not wired (CPU + CUDA + Vulkan are \
7651                 wired today; Metal extends this match when its byte-storage \
7652                 substrate lands)"
7653                    .to_string(),
7654            )
7655            .bt());
7656        }
7657    };
7658    Ok(Arc::new(RwLock::new(new_storage)))
7659}
7660
7661/// Write-into sibling of [`auto_contiguize`] (CapturedRun executor
7662/// build-out, 4b-γ): materializes a contiguous copy of `arc` at `layout`
7663/// INTO `dest`'s EXISTING buffer instead of allocating a fresh one — the
7664/// path `WorkItemKind::ContiguizeOf`'s Reuse-mode branch needs (device
7665/// allocation is illegal inside a capture scope). `dest` must already be
7666/// sized to the contiguized output's byte count — true by construction,
7667/// since the persistent map only ever holds a buffer THIS SAME code path
7668/// (the warm-run `auto_contiguize` allocation) sized.
7669///
7670/// CUDA-only today: `PersistentOutputs::reuse` (Reuse mode) is only ever
7671/// constructed inside [`PipelinedExecutor::capture_decode`], which is
7672/// `#[cfg(feature = "cuda")]`-gated and validates every compute node
7673/// targets `Cuda` — a CPU or Vulkan storage can never actually reach this
7674/// function in practice. Per this project's "never panic on production
7675/// paths" rule, the other backends still surface a typed gap rather than
7676/// silently mishandling it (never a crash).
7677#[cfg_attr(not(feature = "cuda"), allow(unused_variables))]
7678fn contiguize_into(
7679    dest: &Arc<RwLock<Storage>>,
7680    arc: &Arc<RwLock<Storage>>,
7681    layout: &Layout,
7682) -> Result<()> {
7683    let in_guard = arc
7684        .read()
7685        .map_err(|_| poisoned("input storage lock during contiguize_into"))?;
7686    match &in_guard.inner {
7687        #[cfg(feature = "cuda")]
7688        fuel_memory::BackendStorage::Cuda(src_cuda) => {
7689            let dtype_size = in_guard.dtype.size_in_bytes();
7690            let mut dest_guard = dest
7691                .write()
7692                .map_err(|_| poisoned("dest storage lock during contiguize_into"))?;
7693            let dest_cuda = match &mut dest_guard.inner {
7694                fuel_memory::BackendStorage::Cuda(d) => d,
7695                other => {
7696                    return Err(Error::Msg(format!(
7697                        "contiguize_into: dest is BackendStorage::{:?}, not Cuda",
7698                        std::mem::discriminant(other),
7699                    ))
7700                    .bt());
7701                }
7702            };
7703            fuel_cuda_backend::baracuda::contiguize::contiguize_into(
7704                src_cuda, layout, dest_cuda, dtype_size,
7705            )
7706        }
7707        #[allow(unreachable_patterns)]
7708        _ => Err(Error::Msg(
7709            "contiguize_into: only CUDA is wired (PersistentOutputs::reuse / \
7710             capture_decode is CUDA-only today — no CPU/Vulkan consumer exists \
7711             yet; extend this match if one appears)"
7712                .to_string(),
7713        )
7714        .bt()),
7715    }
7716}
7717
7718#[cfg(test)]
7719mod backend_neutral_tests {
7720    use super::*;
7721
7722    #[test]
7723    fn only_deviceless_items_are_backend_neutral() {
7724        let n = NodeId(0);
7725        // Adopting an input-cache entry or aliasing a producer touches no device.
7726        assert!(is_backend_neutral(&WorkItemKind::ConstAdopt));
7727        assert!(is_backend_neutral(&WorkItemKind::ViewOf { input: n }));
7728        assert!(is_backend_neutral(&WorkItemKind::SlotView { producer: n }));
7729        // Contiguize runs on its input's backend; its own `target_backend` is a
7730        // placeholder, so it must not count as a backend switch.
7731        assert!(is_backend_neutral(&WorkItemKind::ContiguizeOf { input: n }));
7732        // Sabotage siblings: anything that runs a kernel of its own or moves bytes
7733        // across devices is NOT, so a real backend switch still arms the
7734        // chunk-boundary logic.
7735        assert!(!is_backend_neutral(&WorkItemKind::Kernel));
7736        assert!(!is_backend_neutral(&WorkItemKind::Copy {
7737            target_location: DeviceLocation::Cpu
7738        }));
7739        assert!(!is_backend_neutral(&WorkItemKind::WriteSlice {
7740            dest: n,
7741            source: n
7742        }));
7743    }
7744}
7745
7746#[cfg(test)]
7747mod tests {
7748    use super::*;
7749    use fuel_graph::Node;
7750    use fuel_ir::Shape;
7751
7752    /// Task 5 (C6): `Op::Scan` has no native kernel in Phase 1 — it is
7753    /// always lowered/re-fused before execution — so `op_to_op_kind` must
7754    /// fall through its `_ => None` wildcard for it, exactly like any other
7755    /// not-yet-wired op. Regression lock, not born-red: this is expected to
7756    /// pass immediately.
7757    #[test]
7758    fn scan_has_no_dispatch_op_kind() {
7759        use fuel_graph::{Op, ScanEmit};
7760        assert_eq!(
7761            crate::pipelined::op_to_op_kind(&Op::Scan {
7762                n_carries: 1,
7763                n_xs: 0,
7764                bound: 2,
7765                emit: ScanEmit::All,
7766                early_exit: None
7767            }),
7768            None,
7769        );
7770    }
7771
7772    /// Step E A4b open question #4 — "event only where waited", step 1.
7773    /// `build_wait_set` collects exactly the producers of `Op::Copy`/`Move`
7774    /// nodes in the order: a same-device-only node (never copied/moved) must
7775    /// be ABSENT, and the Copy's own node id must not appear either (it is
7776    /// not its own producer).
7777    #[test]
7778    fn build_wait_set_collects_only_cross_device_copy_producers() {
7779        let mut g = Graph::new();
7780        let const_id = g.push(Node {
7781            op: Op::Const,
7782            inputs: vec![],
7783            shape: Shape::from_dims(&[4]),
7784            dtype: DType::F32,
7785        });
7786        // Same-device-only consumer of const_id — never fed into a Copy/Move.
7787        let same_device_id = g.push(Node {
7788            op: Op::Contiguize,
7789            inputs: vec![const_id],
7790            shape: Shape::from_dims(&[4]),
7791            dtype: DType::F32,
7792        });
7793        // A cross-device Copy whose producer is `same_device_id`.
7794        let copy_id = g.push(Node {
7795            op: Op::Copy {
7796                target: DeviceLocation::Cuda { gpu_id: 0 },
7797            },
7798            inputs: vec![same_device_id],
7799            shape: Shape::from_dims(&[4]),
7800            dtype: DType::F32,
7801        });
7802        let order = vec![const_id, same_device_id, copy_id];
7803
7804        let set = build_wait_set(&g, &order);
7805        assert!(
7806            set.contains(&same_device_id),
7807            "the Copy's producer must be in the wait set"
7808        );
7809        assert!(
7810            !set.contains(&const_id),
7811            "a node with no Copy/Move consumer must be absent from the wait set"
7812        );
7813        assert!(
7814            !set.contains(&copy_id),
7815            "the Copy node itself is not its own producer"
7816        );
7817        assert_eq!(
7818            set.len(),
7819            1,
7820            "only the one true cross-device producer is in the set"
7821        );
7822    }
7823
7824    /// A `Move` producer is collected the same way as a `Copy` producer.
7825    #[test]
7826    fn build_wait_set_collects_move_producers_too() {
7827        let mut g = Graph::new();
7828        let const_id = g.push(Node {
7829            op: Op::Const,
7830            inputs: vec![],
7831            shape: Shape::from_dims(&[4]),
7832            dtype: DType::F32,
7833        });
7834        let move_id = g.push(Node {
7835            op: Op::Move {
7836                target: DeviceLocation::Cpu,
7837            },
7838            inputs: vec![const_id],
7839            shape: Shape::from_dims(&[4]),
7840            dtype: DType::F32,
7841        });
7842        let order = vec![const_id, move_id];
7843
7844        let set = build_wait_set(&g, &order);
7845        assert!(
7846            set.contains(&const_id),
7847            "the Move's producer must be in the wait set"
7848        );
7849        assert_eq!(set.len(), 1);
7850    }
7851
7852    /// A CPU-only order (no `Op::Copy`/`Op::Move` anywhere) yields an empty
7853    /// wait set — every node in it is eligible for elision.
7854    #[test]
7855    fn build_wait_set_is_empty_for_cpu_only_order() {
7856        let mut g = Graph::new();
7857        let const_id = g.push(Node {
7858            op: Op::Const,
7859            inputs: vec![],
7860            shape: Shape::from_dims(&[4]),
7861            dtype: DType::F32,
7862        });
7863        let contig_id = g.push(Node {
7864            op: Op::Contiguize,
7865            inputs: vec![const_id],
7866            shape: Shape::from_dims(&[4]),
7867            dtype: DType::F32,
7868        });
7869        let order = vec![const_id, contig_id];
7870
7871        let set = build_wait_set(&g, &order);
7872        assert!(
7873            set.is_empty(),
7874            "a CPU-only order (no Copy/Move) yields an empty wait set"
7875        );
7876    }
7877
7878    /// `will_be_waited`'s two arms: the conservative `None` fallback (the
7879    /// `OrderSource::Streaming` case) is always `true`; a `Some(set)` checks
7880    /// membership.
7881    #[test]
7882    fn will_be_waited_none_is_conservative_true_for_any_node() {
7883        let ws: WaitSet = None;
7884        assert!(will_be_waited(&ws, NodeId(0)));
7885        assert!(will_be_waited(&ws, NodeId(12345)));
7886    }
7887
7888    #[test]
7889    fn will_be_waited_some_checks_membership() {
7890        let mut set = HashSet::new();
7891        set.insert(NodeId(3));
7892        let ws: WaitSet = Some(set);
7893        assert!(will_be_waited(&ws, NodeId(3)), "member must be waited");
7894        assert!(!will_be_waited(&ws, NodeId(4)), "non-member must be elided");
7895    }
7896
7897    /// A4b-1 test double: a `Completion` whose `wait` flips a shared flag, so a
7898    /// test can observe whether the drain actually waited it.
7899    struct FlagCompletion(std::sync::Arc<std::sync::atomic::AtomicUsize>);
7900    impl crate::compiled::Completion for FlagCompletion {
7901        fn wait(self: Box<Self>) -> Result<()> {
7902            self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
7903            Ok(())
7904        }
7905    }
7906
7907    /// A4b-1: `store_handle` keeps only `Pending` handles (so the post-drain
7908    /// empty-map assert is meaningful and the drain is O(pending)), and
7909    /// `drain_handles` waits each pending handle exactly once then empties the map.
7910    #[test]
7911    fn handle_map_stores_pending_and_drains_once() {
7912        use std::sync::Arc as StdArc;
7913        use std::sync::atomic::{AtomicUsize, Ordering};
7914
7915        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
7916
7917        // Ready handles are not stored.
7918        store_handle(&mut handles, NodeId(1), CompletionHandle::Ready);
7919        assert!(handles.is_empty(), "Ready handles must not be stored");
7920
7921        // Two pending handles are stored and each waited once on drain.
7922        let waited = StdArc::new(AtomicUsize::new(0));
7923        store_handle(
7924            &mut handles,
7925            NodeId(2),
7926            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
7927        );
7928        store_handle(
7929            &mut handles,
7930            NodeId(3),
7931            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
7932        );
7933        assert_eq!(handles.len(), 2);
7934
7935        drain_handles(&mut handles).expect("drain");
7936        assert_eq!(
7937            waited.load(Ordering::SeqCst),
7938            2,
7939            "each pending handle waited once"
7940        );
7941        assert!(handles.is_empty(), "map empty after drain");
7942    }
7943
7944    /// A4b-1: re-keying a NodeId with a new Pending handle waits the prior one
7945    /// (no leaked async work), and storing `Ready` over a prior Pending also
7946    /// waits it. Defensive — NodeIds are unique per realize in practice.
7947    #[test]
7948    fn handle_map_rekey_waits_previous() {
7949        use std::sync::Arc as StdArc;
7950        use std::sync::atomic::{AtomicUsize, Ordering};
7951
7952        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
7953        let waited = StdArc::new(AtomicUsize::new(0));
7954
7955        store_handle(
7956            &mut handles,
7957            NodeId(7),
7958            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
7959        );
7960        // Re-key with another Pending → prior is waited.
7961        store_handle(
7962            &mut handles,
7963            NodeId(7),
7964            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
7965        );
7966        assert_eq!(
7967            waited.load(Ordering::SeqCst),
7968            1,
7969            "rekey waited the prior pending"
7970        );
7971
7972        // Store Ready over the live Pending → it is waited too.
7973        store_handle(&mut handles, NodeId(7), CompletionHandle::Ready);
7974        assert_eq!(
7975            waited.load(Ordering::SeqCst),
7976            2,
7977            "Ready-over-Pending waited it"
7978        );
7979        assert!(handles.is_empty());
7980
7981        drain_handles(&mut handles).expect("drain empty");
7982    }
7983
7984    /// A4b-3: `wait_producer_handle` waits the named producer's handle EXACTLY
7985    /// once and removes it from the map (the finer cross-device source-drain
7986    /// consumes the producer's completion before the Copy reads its buffer), and
7987    /// is a no-op for an absent producer (CPU / Vulkan-`Ready` source, or an
7988    /// already-consumed handle). The realize-end drain then waits only what
7989    /// remains — no double-wait.
7990    #[test]
7991    fn wait_producer_handle_consumes_named_handle_once() {
7992        use std::sync::Arc as StdArc;
7993        use std::sync::atomic::{AtomicUsize, Ordering};
7994
7995        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
7996        let waited = StdArc::new(AtomicUsize::new(0));
7997
7998        // Two producers in flight; the Copy's source is NodeId(2).
7999        store_handle(
8000            &mut handles,
8001            NodeId(2),
8002            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8003        );
8004        store_handle(
8005            &mut handles,
8006            NodeId(5),
8007            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8008        );
8009
8010        // Absent producer → no-op (a CPU/Vulkan-Ready source has no handle).
8011        wait_producer_handle(&mut handles, NodeId(99)).expect("absent is no-op");
8012        assert_eq!(
8013            waited.load(Ordering::SeqCst),
8014            0,
8015            "absent producer waited nothing"
8016        );
8017        assert_eq!(handles.len(), 2);
8018
8019        // The cross-device copy's source: waited once, removed from the map.
8020        wait_producer_handle(&mut handles, NodeId(2)).expect("wait source");
8021        assert_eq!(
8022            waited.load(Ordering::SeqCst),
8023            1,
8024            "source producer waited once"
8025        );
8026        assert!(!handles.contains_key(&NodeId(2)), "source handle consumed");
8027        assert!(
8028            handles.contains_key(&NodeId(5)),
8029            "unrelated handle untouched"
8030        );
8031
8032        // Re-waiting the (now absent) source is a no-op — no double-wait.
8033        wait_producer_handle(&mut handles, NodeId(2)).expect("re-wait is no-op");
8034        assert_eq!(waited.load(Ordering::SeqCst), 1, "no double-wait");
8035
8036        // Realize-end drain waits only the remaining unrelated producer.
8037        drain_handles(&mut handles).expect("drain");
8038        assert_eq!(
8039            waited.load(Ordering::SeqCst),
8040            2,
8041            "drain waited the remaining one"
8042        );
8043        assert!(handles.is_empty());
8044    }
8045
8046    /// Op::Contiguize on a contiguous-already input is zero-copy:
8047    /// the executor adopts the input Storage Arc unchanged.
8048    #[test]
8049    fn op_contiguize_zero_copy_on_contiguous_input() {
8050        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
8051
8052        let graph = Arc::new(RwLock::new(Graph::new()));
8053        let (const_id, contig_id) = {
8054            let mut g = graph.write().unwrap();
8055            let const_id = g.push(Node {
8056                op: Op::Const,
8057                inputs: vec![],
8058                shape: Shape::from_dims(&[2, 2]),
8059                dtype: DType::F32,
8060            });
8061            let contig_id = g.push(Node {
8062                op: Op::Contiguize,
8063                inputs: vec![const_id],
8064                shape: Shape::from_dims(&[2, 2]),
8065                dtype: DType::F32,
8066            });
8067            // No need to set target_backend on Contiguize — the
8068            // executor inherits or defaults to CPU.
8069            (const_id, contig_id)
8070        };
8071
8072        let mut inputs = StorageCache::new();
8073        let input_arc = Arc::new(RwLock::new(storage));
8074        let input_arc_for_compare = Arc::clone(&input_arc);
8075        inputs.insert(const_id, input_arc);
8076
8077        let (result_arc, _) =
8078            PipelinedExecutor::realize(graph, contig_id, inputs).expect("realize");
8079
8080        // Same Arc → zero-copy adoption. Compare by raw pointer.
8081        assert!(
8082            Arc::ptr_eq(&result_arc, &input_arc_for_compare),
8083            "Op::Contiguize on contiguous input must adopt the input Arc (zero copy)",
8084        );
8085    }
8086
8087    /// Op::Contiguize on a strided input (here: a transposed view)
8088    /// materializes a fresh contiguous Storage. The output bytes
8089    /// reflect the strided view's logical content, not the input
8090    /// storage's underlying memory order.
8091    #[test]
8092    fn op_contiguize_materializes_on_strided_input() {
8093        // 2x3 row-major: [[1,2,3],[4,5,6]] → transpose → 3x2:
8094        // [[1,4],[2,5],[3,6]]. The transposed view shares the
8095        // original buffer; Op::Contiguize on the transpose
8096        // materializes contiguous bytes matching the transposed
8097        // logical order.
8098        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
8099
8100        let graph = Arc::new(RwLock::new(Graph::new()));
8101        let (const_id, _transpose_id, contig_id) = {
8102            let mut g = graph.write().unwrap();
8103            let const_id = g.push(Node {
8104                op: Op::Const,
8105                inputs: vec![],
8106                shape: Shape::from_dims(&[2, 3]),
8107                dtype: DType::F32,
8108            });
8109            let transpose_id = g.push(Node {
8110                op: Op::Transpose,
8111                inputs: vec![const_id],
8112                shape: Shape::from_dims(&[3, 2]),
8113                dtype: DType::F32,
8114            });
8115            let contig_id = g.push(Node {
8116                op: Op::Contiguize,
8117                inputs: vec![transpose_id],
8118                shape: Shape::from_dims(&[3, 2]),
8119                dtype: DType::F32,
8120            });
8121            (const_id, transpose_id, contig_id)
8122        };
8123
8124        let mut inputs = StorageCache::new();
8125        inputs.insert(const_id, Arc::new(RwLock::new(storage)));
8126
8127        let (result_arc, _) =
8128            PipelinedExecutor::realize(graph, contig_id, inputs).expect("realize");
8129
8130        let guard = result_arc.read().unwrap();
8131        let cpu = if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
8132            c
8133        } else {
8134            panic!("expected Cpu storage");
8135        };
8136        let typed: &[f32] = cpu.as_slice().expect("f32 cast");
8137        // Transposed logical order: [1,4,2,5,3,6].
8138        assert_eq!(
8139            typed,
8140            &[1.0, 4.0, 2.0, 5.0, 3.0, 6.0],
8141            "contiguized transpose must reflect logical (transposed) byte order",
8142        );
8143    }
8144
8145    /// E2E: 3-node graph (Const + Const + Add), pre-seeded inputs,
8146    /// realized through the compiler+executor thread pair, returns
8147    /// expected sum bytes.
8148    #[test]
8149    fn pipelined_realize_const_const_add() {
8150        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
8151        let rhs_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
8152
8153        let graph = Arc::new(RwLock::new(Graph::new()));
8154        let (lhs_id, rhs_id, add_id) = {
8155            let mut g = graph.write().unwrap();
8156            let lhs_id = g.push(Node {
8157                op: Op::Const,
8158                inputs: vec![],
8159                shape: Shape::from_dims(&[3]),
8160                dtype: DType::F32,
8161            });
8162            let rhs_id = g.push(Node {
8163                op: Op::Const,
8164                inputs: vec![],
8165                shape: Shape::from_dims(&[3]),
8166                dtype: DType::F32,
8167            });
8168            let add_id = g.push(Node {
8169                op: Op::Add,
8170                inputs: vec![lhs_id, rhs_id],
8171                shape: Shape::from_dims(&[3]),
8172                dtype: DType::F32,
8173            });
8174            g.set_target_backend(add_id, BackendId::Cpu);
8175            (lhs_id, rhs_id, add_id)
8176        };
8177
8178        let mut inputs = StorageCache::new();
8179        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
8180        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
8181
8182        let (result_arc, _result_layout) =
8183            PipelinedExecutor::realize(graph, add_id, inputs).expect("realize");
8184
8185        let guard = result_arc.read().unwrap();
8186        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
8187            let typed: &[f32] = c.as_slice().expect("f32 cast");
8188            assert_eq!(typed, &[11.0, 22.0, 33.0]);
8189        } else {
8190            panic!("expected CPU output");
8191        }
8192    }
8193
8194    /// CapturedRun executor build-out (Increment 1): capture a 2-op binary
8195    /// chain `z = (a + b) * c` THROUGH the pipelined executor's
8196    /// persistent-output mode, then prove the three capture guarantees on a
8197    /// live GPU:
8198    ///   1. after capture, the fixed output buffer holds the warm-run result
8199    ///      (capture RECORDS launches, it does not execute them);
8200    ///   2. `replay()` recomputes bit-exactly into the SAME fixed buffer;
8201    ///   3. replay reads the FIXED input addresses — overwriting an input
8202    ///      buffer in place and replaying yields the new result, matching an
8203    ///      independent uncaptured `realize`. This is the whole mechanism:
8204    ///      the write-into binary wrapper + the executor's reuse mode +
8205    ///      `capture_run` compose into a replayable decode-step graph.
8206    #[test]
8207    #[ignore = "requires a live CUDA device"]
8208    #[cfg(feature = "cuda")]
8209    fn capture_decode_binary_chain_replays_bit_exact_cuda() {
8210        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8211        use fuel_ir::Shape;
8212        use fuel_memory::BackendStorage;
8213
8214        let Ok(dev) = CudaDevice::new(0) else {
8215            return fuel_test_support::hardware::skip(
8216                fuel_test_support::hardware::Hardware::Cuda,
8217                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
8218            );
8219        };
8220
8221        // z = (a + b) * c, shape [4]. `y = a + b` is a persistent
8222        // INTERMEDIATE; `z` is the persistent target — both fixed-address.
8223        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId, NodeId, NodeId) {
8224            let graph = Arc::new(RwLock::new(Graph::new()));
8225            let (a, b, c, z) = {
8226                let mut g = graph.write().unwrap();
8227                let a = g.push(Node {
8228                    op: Op::Const,
8229                    inputs: vec![],
8230                    shape: Shape::from_dims(&[4]),
8231                    dtype: DType::F32,
8232                });
8233                let b = g.push(Node {
8234                    op: Op::Const,
8235                    inputs: vec![],
8236                    shape: Shape::from_dims(&[4]),
8237                    dtype: DType::F32,
8238                });
8239                let c = g.push(Node {
8240                    op: Op::Const,
8241                    inputs: vec![],
8242                    shape: Shape::from_dims(&[4]),
8243                    dtype: DType::F32,
8244                });
8245                let y = g.push(Node {
8246                    op: Op::Add,
8247                    inputs: vec![a, b],
8248                    shape: Shape::from_dims(&[4]),
8249                    dtype: DType::F32,
8250                });
8251                let z = g.push(Node {
8252                    op: Op::Mul,
8253                    inputs: vec![y, c],
8254                    shape: Shape::from_dims(&[4]),
8255                    dtype: DType::F32,
8256                });
8257                g.set_target_backend(y, BackendId::Cuda);
8258                g.set_target_backend(z, BackendId::Cuda);
8259                (a, b, c, z)
8260            };
8261            (graph, a, b, c, z)
8262        };
8263
8264        let up = |v: &[f32]| -> Arc<RwLock<Storage>> {
8265            let bytes: &[u8] = bytemuck::cast_slice(v);
8266            let cb = CudaStorageBytes::from_cpu_bytes(&dev, bytes).expect("h2d");
8267            Arc::new(RwLock::new(Storage::new(
8268                BackendStorage::Cuda(cb),
8269                DType::F32,
8270            )))
8271        };
8272        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8273            let g = arc.read().unwrap();
8274            let BackendStorage::Cuda(c) = &g.inner else {
8275                panic!("not cuda")
8276            };
8277            let host = c.to_cpu_bytes().expect("d2h");
8278            bytemuck::cast_slice(&host).to_vec()
8279        };
8280
8281        let a_data = [1.0_f32, 2.0, 3.0, 4.0];
8282        let b_data = [10.0_f32, 20.0, 30.0, 40.0];
8283        let c_data = [2.0_f32, 2.0, 2.0, 2.0];
8284        let expect0 = [22.0_f32, 44.0, 66.0, 88.0]; // (a+b)*c
8285
8286        // Fixed input Arcs (shared into capture; overwritten in place later).
8287        let a_arc = up(&a_data);
8288        let b_arc = up(&b_data);
8289        let c_arc = up(&c_data);
8290
8291        let (graph, a, b, c, z) = build();
8292        let mut inputs = StorageCache::new();
8293        inputs.insert(a, a_arc.clone());
8294        inputs.insert(b, b_arc.clone());
8295        inputs.insert(c, c_arc.clone());
8296
8297        let captured =
8298            PipelinedExecutor::capture_decode(Arc::clone(&graph), z, inputs, SymEnv::default())
8299                .expect("capture_decode");
8300
8301        // (1) warm-run result sits in the captured output buffer.
8302        assert_eq!(
8303            read(&captured.output),
8304            &expect0,
8305            "warm-run result after capture"
8306        );
8307
8308        // (2) replay with the same inputs recomputes bit-exactly.
8309        captured.run.replay(&dev).expect("replay");
8310        dev.synchronize().expect("sync");
8311        assert_eq!(read(&captured.output), &expect0, "replay reproduces result");
8312
8313        // (3) overwrite input `a` IN PLACE (same device address), replay ->
8314        //     the new result flows from the FIXED input address. Compare to
8315        //     an independent uncaptured realize with the same new input.
8316        let a2 = [100.0_f32, 200.0, 300.0, 400.0];
8317        {
8318            let g = a_arc.read().unwrap();
8319            let BackendStorage::Cuda(c) = &g.inner else {
8320                panic!("a not cuda")
8321            };
8322            c.write_from_host(bytemuck::cast_slice(&a2))
8323                .expect("in-place H2D");
8324        }
8325        captured.run.replay(&dev).expect("replay 2");
8326        dev.synchronize().expect("sync 2");
8327        let got = read(&captured.output);
8328
8329        let (graph_ref, ar, br, cr, zr) = build();
8330        let mut inputs_ref = StorageCache::new();
8331        inputs_ref.insert(ar, up(&a2));
8332        inputs_ref.insert(br, up(&b_data));
8333        inputs_ref.insert(cr, up(&c_data));
8334        let (ref_arc, _) =
8335            PipelinedExecutor::realize(graph_ref, zr, inputs_ref).expect("ref realize");
8336        let expect1 = read(&ref_arc); // (a2+b)*c = [220,440,660,880]
8337        assert_eq!(
8338            got, expect1,
8339            "replay after in-place input update matches uncaptured realize"
8340        );
8341        assert_eq!(expect1, vec![220.0, 440.0, 660.0, 880.0]);
8342    }
8343
8344    /// CapturedRun executor build-out (Increment 3): capture a DECODE-SHAPED
8345    /// graph — the full dense op-set composing in one capture — and prove it
8346    /// replays bit-exactly against an independent uncaptured realize.
8347    ///
8348    /// Graph (an FFN block + norms, batch=seq=1 like real decode):
8349    ///   n1 = rms_norm(x);  u = n1 · w_up;  s = silu(u);
8350    /// cuBLAS `gemm_dense` matmul IS graph-capturable (regression for the
8351    /// dangling-input bug that once masqueraded as "cuBLAS not replay-safe").
8352    /// Captures `y = a·w` where the caller does NOT retain `w`, FORCES the
8353    /// freed-`w` slot to be reused by garbage buffers, then replays 50× — all
8354    /// must equal the uncaptured realize. Passes iff `capture_decode` retains
8355    /// its input buffers (`CapturedDecode::retained_inputs`).
8356    #[test]
8357    #[ignore = "requires a live CUDA device"]
8358    #[cfg(feature = "cuda")]
8359    fn capture_decode_matmul_replays_bit_exact_cuda() {
8360        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8361        use fuel_ir::Shape;
8362        use fuel_memory::BackendStorage;
8363        let Ok(dev) = CudaDevice::new(0) else { return };
8364        const H: usize = 4;
8365        const F: usize = 8;
8366        let a_data: Vec<f32> = (0..H).map(|i| 0.5 + i as f32).collect();
8367        let w_data: Vec<f32> = (0..H * F).map(|i| 0.01 * (i as f32 + 1.0)).collect();
8368        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId, NodeId) {
8369            let graph = Arc::new(RwLock::new(Graph::new()));
8370            let (a, w, y) = {
8371                let mut g = graph.write().unwrap();
8372                let a = g.push(Node {
8373                    op: Op::Const,
8374                    inputs: vec![],
8375                    shape: Shape::from_dims(&[1, H]),
8376                    dtype: DType::F32,
8377                });
8378                let w = g.push(Node {
8379                    op: Op::Const,
8380                    inputs: vec![],
8381                    shape: Shape::from_dims(&[H, F]),
8382                    dtype: DType::F32,
8383                });
8384                let y = g.push(Node {
8385                    op: Op::MatMul,
8386                    inputs: vec![a, w],
8387                    shape: Shape::from_dims(&[1, F]),
8388                    dtype: DType::F32,
8389                });
8390                g.set_target_backend(y, BackendId::Cuda);
8391                (a, w, y)
8392            };
8393            (graph, a, w, y)
8394        };
8395        let up = |v: &[f32]| {
8396            let b: Vec<u8> = v.iter().flat_map(|f| f.to_le_bytes()).collect();
8397            Arc::new(RwLock::new(Storage::new(
8398                BackendStorage::Cuda(CudaStorageBytes::from_cpu_bytes(&dev, &b).unwrap()),
8399                DType::F32,
8400            )))
8401        };
8402        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8403            let g = arc.read().unwrap();
8404            let BackendStorage::Cuda(c) = &g.inner else {
8405                panic!("not cuda")
8406            };
8407            c.to_cpu_bytes()
8408                .unwrap()
8409                .chunks_exact(4)
8410                .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
8411                .collect()
8412        };
8413        // Reference (uncaptured).
8414        let (gr, ar, wr, yr) = build();
8415        let mut insr = StorageCache::new();
8416        insr.insert(ar, up(&a_data));
8417        insr.insert(wr, up(&w_data));
8418        let (refarc, _) = PipelinedExecutor::realize(gr, yr, insr).unwrap();
8419        let expect = read(&refarc);
8420        // Capture (a + w NOT retained by caller).
8421        let (graph, a, w, y) = build();
8422        let mut inputs = StorageCache::new();
8423        inputs.insert(a, up(&a_data));
8424        inputs.insert(w, up(&w_data));
8425        let captured =
8426            PipelinedExecutor::capture_decode(Arc::clone(&graph), y, inputs, SymEnv::default())
8427                .expect("capture");
8428        assert_eq!(read(&captured.output), expect, "warm result after capture");
8429        // FORCE freed-memory reuse: same-size (H*F) garbage buffers. If `w`
8430        // were dangling, replay would read 999.0s.
8431        let mut squatters = Vec::new();
8432        for _ in 0..8 {
8433            let g: Vec<u8> = (0..H * F).flat_map(|_| 999.0f32.to_le_bytes()).collect();
8434            squatters.push(CudaStorageBytes::from_cpu_bytes(&dev, &g).unwrap());
8435        }
8436        dev.synchronize().unwrap();
8437        let mut bad = 0usize;
8438        for _ in 0..50 {
8439            captured.run.replay(&dev).unwrap();
8440            dev.synchronize().unwrap();
8441            if read(&captured.output) != expect {
8442                bad += 1;
8443            }
8444        }
8445        assert_eq!(
8446            bad, 0,
8447            "cuBLAS matmul capture replays bit-exact ({bad}/50 wrong)"
8448        );
8449    }
8450
8451    /// `Op::MulScalar` / `OpKind::Affine` (the `1/√d` attention scale) is
8452    /// capture-safe (write-into variant + forced-reuse regression).
8453    #[test]
8454    #[ignore = "requires a live CUDA device"]
8455    #[cfg(feature = "cuda")]
8456    fn capture_decode_affine_replays_bit_exact_cuda() {
8457        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8458        use fuel_ir::Shape;
8459        use fuel_memory::BackendStorage;
8460        let Ok(dev) = CudaDevice::new(0) else { return };
8461        const N: usize = 6;
8462        let x_data: Vec<f32> = (0..N).map(|i| 1.0 + i as f32).collect();
8463        let expect: Vec<f32> = x_data.iter().map(|v| v * 0.5).collect();
8464        let graph = Arc::new(RwLock::new(Graph::new()));
8465        let (x, y) = {
8466            let mut g = graph.write().unwrap();
8467            let x = g.push(Node {
8468                op: Op::Const,
8469                inputs: vec![],
8470                shape: Shape::from_dims(&[1, N]),
8471                dtype: DType::F32,
8472            });
8473            let y = g.push(Node {
8474                op: Op::MulScalar(0.5),
8475                inputs: vec![x],
8476                shape: Shape::from_dims(&[1, N]),
8477                dtype: DType::F32,
8478            });
8479            g.set_target_backend(y, BackendId::Cuda);
8480            (x, y)
8481        };
8482        let up = |v: &[f32]| {
8483            let b: Vec<u8> = v.iter().flat_map(|f| f.to_le_bytes()).collect();
8484            Arc::new(RwLock::new(Storage::new(
8485                BackendStorage::Cuda(CudaStorageBytes::from_cpu_bytes(&dev, &b).unwrap()),
8486                DType::F32,
8487            )))
8488        };
8489        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8490            let g = arc.read().unwrap();
8491            let BackendStorage::Cuda(c) = &g.inner else {
8492                panic!("not cuda")
8493            };
8494            c.to_cpu_bytes()
8495                .unwrap()
8496                .chunks_exact(4)
8497                .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
8498                .collect()
8499        };
8500        let mut inputs = StorageCache::new();
8501        inputs.insert(x, up(&x_data));
8502        let captured =
8503            PipelinedExecutor::capture_decode(Arc::clone(&graph), y, inputs, SymEnv::default())
8504                .expect("capture");
8505        assert_eq!(read(&captured.output), expect, "warm result after capture");
8506        let mut sq = Vec::new();
8507        for _ in 0..8 {
8508            let g: Vec<u8> = (0..N).flat_map(|_| 999.0f32.to_le_bytes()).collect();
8509            sq.push(CudaStorageBytes::from_cpu_bytes(&dev, &g).unwrap());
8510        }
8511        dev.synchronize().unwrap();
8512        let mut bad = 0usize;
8513        for _ in 0..50 {
8514            captured.run.replay(&dev).unwrap();
8515            dev.synchronize().unwrap();
8516            if read(&captured.output) != expect {
8517                bad += 1;
8518            }
8519        }
8520        assert_eq!(bad, 0, "affine capture replays bit-exact ({bad}/50 wrong)");
8521    }
8522
8523    /// `index_select` (embedding lookup) IS graph-capturable (regression for
8524    /// the dangling-input bug that once looked like "element 0 dropped on
8525    /// replay"). Captures `emb = index_select(wte, tok)` with `wte` NOT
8526    /// retained by the caller, FORCES the freed-`wte` slot to be reused by
8527    /// garbage buffers, then replays 50× — all must be `[1,2,3,4]`. Passes iff
8528    /// `capture_decode` retains its input buffers.
8529    #[test]
8530    #[ignore = "requires a live CUDA device"]
8531    #[cfg(feature = "cuda")]
8532    fn capture_decode_index_select_replays_bit_exact_cuda() {
8533        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8534        use fuel_ir::Shape;
8535        use fuel_memory::BackendStorage;
8536        let Ok(dev) = CudaDevice::new(0) else { return };
8537        const V: usize = 3;
8538        const H: usize = 4;
8539        let wte_data: Vec<f32> = (0..V)
8540            .flat_map(|v| (0..H).map(move |c| 1.0 + 10.0 * v as f32 + c as f32))
8541            .collect();
8542        let graph = Arc::new(RwLock::new(Graph::new()));
8543        let (tok, wte, emb) = {
8544            let mut g = graph.write().unwrap();
8545            let tok = g.push(Node {
8546                op: Op::Const,
8547                inputs: vec![],
8548                shape: Shape::from_dims(&[1]),
8549                dtype: DType::U32,
8550            });
8551            let wte = g.push(Node {
8552                op: Op::Const,
8553                inputs: vec![],
8554                shape: Shape::from_dims(&[V, H]),
8555                dtype: DType::F32,
8556            });
8557            let emb = g.push(Node {
8558                op: Op::IndexSelect { dim: 0 },
8559                inputs: vec![wte, tok],
8560                shape: Shape::from_dims(&[1, H]),
8561                dtype: DType::F32,
8562            });
8563            g.set_target_backend(emb, BackendId::Cuda);
8564            (tok, wte, emb)
8565        };
8566        let up_f32 = |v: &[f32]| {
8567            let b: Vec<u8> = v.iter().flat_map(|f| f.to_le_bytes()).collect();
8568            Arc::new(RwLock::new(Storage::new(
8569                BackendStorage::Cuda(CudaStorageBytes::from_cpu_bytes(&dev, &b).unwrap()),
8570                DType::F32,
8571            )))
8572        };
8573        let up_u32 = |v: &[u32]| {
8574            let b: Vec<u8> = v.iter().flat_map(|x| x.to_le_bytes()).collect();
8575            Arc::new(RwLock::new(Storage::new(
8576                BackendStorage::Cuda(CudaStorageBytes::from_cpu_bytes(&dev, &b).unwrap()),
8577                DType::U32,
8578            )))
8579        };
8580        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8581            let g = arc.read().unwrap();
8582            let BackendStorage::Cuda(c) = &g.inner else {
8583                panic!("not cuda")
8584            };
8585            c.to_cpu_bytes()
8586                .unwrap()
8587                .chunks_exact(4)
8588                .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
8589                .collect()
8590        };
8591        let tok_arc = up_u32(&[0]);
8592        let mut inputs = StorageCache::new();
8593        inputs.insert(tok, tok_arc.clone());
8594        inputs.insert(wte, up_f32(&wte_data));
8595        let captured =
8596            PipelinedExecutor::capture_decode(Arc::clone(&graph), emb, inputs, SymEnv::default())
8597                .expect("capture");
8598        assert_eq!(
8599            read(&captured.output),
8600            vec![1.0, 2.0, 3.0, 4.0],
8601            "warm result after capture"
8602        );
8603        // FORCE freed-memory reuse: same-size (V*H) garbage buffers reclaim
8604        // `wte`'s slot if it were dangling — replay would then read 999.0s.
8605        let mut squatters = Vec::new();
8606        for _ in 0..8 {
8607            let g: Vec<u8> = (0..V * H).flat_map(|_| 999.0f32.to_le_bytes()).collect();
8608            squatters.push(CudaStorageBytes::from_cpu_bytes(&dev, &g).unwrap());
8609        }
8610        dev.synchronize().unwrap();
8611        let mut bad = 0usize;
8612        for _ in 0..50 {
8613            captured.run.replay(&dev).unwrap();
8614            dev.synchronize().unwrap();
8615            if read(&captured.output) != vec![1.0, 2.0, 3.0, 4.0] {
8616                bad += 1;
8617            }
8618        }
8619        assert_eq!(
8620            bad, 0,
8621            "index_select capture replays bit-exact ({bad}/50 wrong)"
8622        );
8623    }
8624
8625    ///   n1 = rms_norm(x);  s = silu(n1);  p = softmax(s);
8626    ///   r  = p + x;  n2 = rms_norm(r);  y = n2 + x
8627    /// Exercises rms_norm (×2 — proves the per-device RMS workspace is reused
8628    /// across sequential norms inside ONE captured graph), silu + softmax
8629    /// (write-into), and residual adds through the persistent-output capture
8630    /// path. Verified across two input value-sets (robust, not luck).
8631    ///
8632    /// Deliberately EXCLUDES matmul (cuBLAS not graph-replay-safe) and
8633    /// index_select (its host-side shape/stride arrays dangle under capture —
8634    /// proven to mis-replay). Both are surfaced `capture_decode` gaps, not
8635    /// silent mis-replays. See `op_kind_is_capture_writeinto`.
8636    #[test]
8637    #[ignore = "requires a live CUDA device"]
8638    #[cfg(feature = "cuda")]
8639    fn capture_decode_norm_silu_softmax_replays_bit_exact_cuda() {
8640        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8641        use fuel_graph::registry::{FusedOpParams, FusedOps};
8642        use fuel_ir::Shape;
8643        use fuel_memory::BackendStorage;
8644
8645        let Ok(dev) = CudaDevice::new(0) else {
8646            return fuel_test_support::hardware::skip(
8647                fuel_test_support::hardware::Hardware::Cuda,
8648                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
8649            );
8650        };
8651        const H: usize = 6;
8652        let eps = 1e-5f64;
8653
8654        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId) {
8655            let graph = Arc::new(RwLock::new(Graph::new()));
8656            let (x, y) = {
8657                let mut g = graph.write().unwrap();
8658                let mk = |g: &mut Graph, op: Op, ins: Vec<NodeId>, dims: &[usize]| {
8659                    g.push(Node {
8660                        op,
8661                        inputs: ins,
8662                        shape: Shape::from_dims(dims),
8663                        dtype: DType::F32,
8664                    })
8665                };
8666                let rms = || {
8667                    Op::Fused(
8668                        FusedOps::RMS_NORM_LAST_DIM,
8669                        FusedOpParams::RmsNormLastDim { eps },
8670                    )
8671                };
8672                let sm = || Op::Fused(FusedOps::SOFTMAX_LAST_DIM, FusedOpParams::SoftmaxLastDim);
8673                let x = mk(&mut g, Op::Const, vec![], &[1, H]);
8674                let n1 = mk(&mut g, rms(), vec![x], &[1, H]);
8675                let s = mk(&mut g, Op::Silu, vec![n1], &[1, H]);
8676                let p = mk(&mut g, sm(), vec![s], &[1, H]);
8677                let r = mk(&mut g, Op::Add, vec![p, x], &[1, H]);
8678                let n2 = mk(&mut g, rms(), vec![r], &[1, H]);
8679                let y = mk(&mut g, Op::Add, vec![n2, x], &[1, H]);
8680                for id in [n1, s, p, r, n2, y] {
8681                    g.set_target_backend(id, BackendId::Cuda);
8682                }
8683                (x, y)
8684            };
8685            (graph, x, y)
8686        };
8687
8688        let up = |v: &[f32]| -> Arc<RwLock<Storage>> {
8689            let cb = CudaStorageBytes::from_cpu_bytes(&dev, bytemuck::cast_slice(v)).expect("h2d");
8690            Arc::new(RwLock::new(Storage::new(
8691                BackendStorage::Cuda(cb),
8692                DType::F32,
8693            )))
8694        };
8695        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8696            let g = arc.read().unwrap();
8697            let BackendStorage::Cuda(c) = &g.inner else {
8698                panic!("not cuda")
8699            };
8700            bytemuck::cast_slice(&c.to_cpu_bytes().expect("d2h")).to_vec()
8701        };
8702
8703        let x_data: Vec<f32> = (0..H).map(|c| 0.1 * (c as f32 + 1.0)).collect();
8704        let x_arc = up(&x_data);
8705        let (graph, x, y) = build();
8706        let mut inputs = StorageCache::new();
8707        inputs.insert(x, x_arc.clone());
8708
8709        let captured =
8710            PipelinedExecutor::capture_decode(Arc::clone(&graph), y, inputs, SymEnv::default())
8711                .expect("capture_decode norm/silu/softmax");
8712
8713        let realize_ref = |xv: &[f32]| -> Vec<f32> {
8714            let (g, xr, yr) = build();
8715            let mut ins = StorageCache::new();
8716            ins.insert(xr, up(xv));
8717            let (arc, _) = PipelinedExecutor::realize(g, yr, ins).expect("ref realize");
8718            read(&arc)
8719        };
8720        let expect0 = realize_ref(&x_data);
8721
8722        // (1) after capture the output holds the warm result.
8723        assert_eq!(read(&captured.output), expect0, "warm result after capture");
8724        // (2) replay reproduces bit-exactly (incl. RMS workspace reuse on replay).
8725        captured.run.replay(&dev).expect("replay");
8726        dev.synchronize().expect("sync");
8727        assert_eq!(read(&captured.output), expect0, "replay reproduces result");
8728
8729        // (3) overwrite x in place, replay -> matches uncaptured realize (a
8730        //     DIFFERENT value-set — so the chain is robust, not input-lucky).
8731        let x2: Vec<f32> = (0..H).map(|c| 0.3 * (c as f32 + 1.0)).collect();
8732        {
8733            let g = x_arc.read().unwrap();
8734            let BackendStorage::Cuda(c) = &g.inner else {
8735                panic!("x not cuda")
8736            };
8737            c.write_from_host(bytemuck::cast_slice(&x2))
8738                .expect("in-place H2D");
8739        }
8740        captured.run.replay(&dev).expect("replay 2");
8741        dev.synchronize().expect("sync 2");
8742        assert_eq!(
8743            read(&captured.output),
8744            realize_ref(&x2),
8745            "replay after x update matches realize"
8746        );
8747    }
8748
8749    /// CapturedRun executor build-out (Increment 4b-γ): make `ContiguizeOf`
8750    /// (a non-contiguous reshape after `Permute` — the real decode graph's
8751    /// attention-merge reshape shape) AND a 2-input `Op::Concat` (the shape
8752    /// RoPE's CUDA decomposition emits for its rotate-half) BOTH
8753    /// capture-safe in ONE graph, so the crux 4b-γ exists for — allocation
8754    /// of an INTERMEDIATE, non-final buffer inside a capture scope — is
8755    /// actually exercised, not just each gap in isolation.
8756    ///
8757    /// Graph: `x [2,3,4] --Permute[1,0,2]--> [3,2,4]` (non-contiguous)
8758    /// `--Reshape[3,8]--> r` (`ContiguizeOf`, MUST allocate: its input is
8759    /// non-contiguous) `--Concat(dim=1, with b [3,8])--> y [3,16]` (target).
8760    #[test]
8761    #[ignore = "requires a live CUDA device"]
8762    #[cfg(feature = "cuda")]
8763    fn capture_decode_contiguize_then_concat_replays_bit_exact_cuda() {
8764        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8765        use fuel_ir::Shape;
8766        use fuel_memory::BackendStorage;
8767
8768        let Ok(dev) = CudaDevice::new(0) else {
8769            return fuel_test_support::hardware::skip(
8770                fuel_test_support::hardware::Hardware::Cuda,
8771                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
8772            );
8773        };
8774
8775        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId, NodeId) {
8776            let graph = Arc::new(RwLock::new(Graph::new()));
8777            let (x, b, y) = {
8778                let mut g = graph.write().unwrap();
8779                let x = g.push(Node {
8780                    op: Op::Const,
8781                    inputs: vec![],
8782                    shape: Shape::from_dims(&[2, 3, 4]),
8783                    dtype: DType::F32,
8784                });
8785                let p = g.push(Node {
8786                    op: Op::Permute(vec![1, 0, 2]),
8787                    inputs: vec![x],
8788                    shape: Shape::from_dims(&[3, 2, 4]),
8789                    dtype: DType::F32,
8790                });
8791                let r = g.push(Node {
8792                    op: Op::Reshape(Shape::from_dims(&[3, 8])),
8793                    inputs: vec![p],
8794                    shape: Shape::from_dims(&[3, 8]),
8795                    dtype: DType::F32,
8796                });
8797                let b = g.push(Node {
8798                    op: Op::Const,
8799                    inputs: vec![],
8800                    shape: Shape::from_dims(&[3, 8]),
8801                    dtype: DType::F32,
8802                });
8803                let y = g.push(Node {
8804                    op: Op::Concat { dim: 1 },
8805                    inputs: vec![r, b],
8806                    shape: Shape::from_dims(&[3, 16]),
8807                    dtype: DType::F32,
8808                });
8809                g.set_target_backend(p, BackendId::Cuda);
8810                g.set_target_backend(r, BackendId::Cuda);
8811                g.set_target_backend(y, BackendId::Cuda);
8812                (x, b, y)
8813            };
8814            (graph, x, b, y)
8815        };
8816
8817        let up = |v: &[f32]| -> Arc<RwLock<Storage>> {
8818            let cb = CudaStorageBytes::from_cpu_bytes(&dev, bytemuck::cast_slice(v)).expect("h2d");
8819            Arc::new(RwLock::new(Storage::new(
8820                BackendStorage::Cuda(cb),
8821                DType::F32,
8822            )))
8823        };
8824        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8825            let g = arc.read().unwrap();
8826            let BackendStorage::Cuda(c) = &g.inner else {
8827                panic!("not cuda")
8828            };
8829            bytemuck::cast_slice(&c.to_cpu_bytes().expect("d2h")).to_vec()
8830        };
8831
8832        let x_data: Vec<f32> = (0..24).map(|i| i as f32).collect();
8833        let b_data: Vec<f32> = (0..24).map(|i| 100.0 + i as f32).collect();
8834        let x_arc = up(&x_data);
8835        let (graph, x, b, y) = build();
8836        let mut inputs = StorageCache::new();
8837        inputs.insert(x, x_arc.clone());
8838        // `b` deliberately NOT retained by a local variable — forces
8839        // reliance on `capture_decode`'s own `retained_inputs`, mirroring
8840        // the matmul/index_select regression precedent.
8841        inputs.insert(b, up(&b_data));
8842
8843        let captured =
8844            PipelinedExecutor::capture_decode(Arc::clone(&graph), y, inputs, SymEnv::default())
8845                .expect("capture_decode contiguize+concat");
8846
8847        let realize_ref = |xv: &[f32], bv: &[f32]| -> Vec<f32> {
8848            let (g, xr, br, yr) = build();
8849            let mut ins = StorageCache::new();
8850            ins.insert(xr, up(xv));
8851            ins.insert(br, up(bv));
8852            let (arc, _) = PipelinedExecutor::realize(g, yr, ins).expect("ref realize");
8853            read(&arc)
8854        };
8855        let expect0 = realize_ref(&x_data, &b_data);
8856
8857        // (1) warm-run result sits in the captured output buffer (capture
8858        //     RECORDS launches, it does not execute them at capture time).
8859        assert_eq!(read(&captured.output), expect0, "warm result after capture");
8860
8861        // (2) replay TWICE with unchanged inputs — proves the fixed-address
8862        //     reuse (both the ContiguizeOf intermediate and the Concat
8863        //     output) holds across multiple replay() calls, not just one.
8864        for i in 0..2 {
8865            captured
8866                .run
8867                .replay(&dev)
8868                .unwrap_or_else(|e| panic!("replay {i}: {e:?}"));
8869            dev.synchronize().expect("sync");
8870            assert_eq!(
8871                read(&captured.output),
8872                expect0,
8873                "replay {i} reproduces result"
8874            );
8875        }
8876
8877        // (3) overwrite x in place (a DIFFERENT value-set), replay again ->
8878        //     the new result flows from the FIXED input address, through
8879        //     the fixed ContiguizeOf intermediate, into the fixed Concat
8880        //     output — matches an independent uncaptured realize.
8881        let x2: Vec<f32> = (0..24).map(|i| 1000.0 + i as f32).collect();
8882        {
8883            let g = x_arc.read().unwrap();
8884            let BackendStorage::Cuda(c) = &g.inner else {
8885                panic!("x not cuda")
8886            };
8887            c.write_from_host(bytemuck::cast_slice(&x2))
8888                .expect("in-place H2D");
8889        }
8890        captured.run.replay(&dev).expect("replay 3");
8891        dev.synchronize().expect("sync 3");
8892        assert_eq!(
8893            read(&captured.output),
8894            realize_ref(&x2, &b_data),
8895            "replay after x update matches independent uncaptured realize"
8896        );
8897    }
8898
8899    /// CapturedRun executor build-out (Increment 4b-ζ): a same-device
8900    /// CUDA→CUDA `Op::Copy` — the shape `insert_safety_copies` emits for its
8901    /// aliasing-hazard snapshots in the real Llama decode graph — is
8902    /// capture-safe via `copy_from_cuda_wrapper`'s write-into
8903    /// `BackendStorage::Cuda` branch (`CudaStorageBytes::copy_from_device`).
8904    ///
8905    /// Graph: `x [2,4]`, `b [2,4]` --Copy{target: Cuda{0}}--> `c` (same-device
8906    /// snapshot of `x`) --Add(c, b)--> `y`. Capture, replay twice unchanged,
8907    /// then update `x` in place and replay again — every step must match an
8908    /// independent uncaptured `realize`.
8909    #[test]
8910    #[ignore = "requires a live CUDA device"]
8911    #[cfg(feature = "cuda")]
8912    fn capture_decode_same_device_copy_replays_bit_exact_cuda() {
8913        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8914        use fuel_ir::Shape;
8915        use fuel_memory::BackendStorage;
8916
8917        let Ok(dev) = CudaDevice::new(0) else {
8918            return fuel_test_support::hardware::skip(
8919                fuel_test_support::hardware::Hardware::Cuda,
8920                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
8921            );
8922        };
8923
8924        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId, NodeId) {
8925            let graph = Arc::new(RwLock::new(Graph::new()));
8926            let (x, b, y) = {
8927                let mut g = graph.write().unwrap();
8928                let x = g.push(Node {
8929                    op: Op::Const,
8930                    inputs: vec![],
8931                    shape: Shape::from_dims(&[2, 4]),
8932                    dtype: DType::F32,
8933                });
8934                let b = g.push(Node {
8935                    op: Op::Const,
8936                    inputs: vec![],
8937                    shape: Shape::from_dims(&[2, 4]),
8938                    dtype: DType::F32,
8939                });
8940                // Same-device CUDA->CUDA copy — the write-into-safe case.
8941                let c = g.push(Node {
8942                    op: Op::Copy {
8943                        target: DeviceLocation::Cuda { gpu_id: 0 },
8944                    },
8945                    inputs: vec![x],
8946                    shape: Shape::from_dims(&[2, 4]),
8947                    dtype: DType::F32,
8948                });
8949                let y = g.push(Node {
8950                    op: Op::Add,
8951                    inputs: vec![c, b],
8952                    shape: Shape::from_dims(&[2, 4]),
8953                    dtype: DType::F32,
8954                });
8955                // Copy's target_backend = SOURCE backend (x is Cuda-resident).
8956                g.set_target_backend(c, BackendId::Cuda);
8957                g.set_target_backend(y, BackendId::Cuda);
8958                (x, b, y)
8959            };
8960            (graph, x, b, y)
8961        };
8962
8963        let up = |v: &[f32]| -> Arc<RwLock<Storage>> {
8964            let cb = CudaStorageBytes::from_cpu_bytes(&dev, bytemuck::cast_slice(v)).expect("h2d");
8965            Arc::new(RwLock::new(Storage::new(
8966                BackendStorage::Cuda(cb),
8967                DType::F32,
8968            )))
8969        };
8970        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8971            let g = arc.read().unwrap();
8972            let BackendStorage::Cuda(c) = &g.inner else {
8973                panic!("not cuda")
8974            };
8975            bytemuck::cast_slice(&c.to_cpu_bytes().expect("d2h")).to_vec()
8976        };
8977
8978        let x_data: Vec<f32> = (0..8).map(|i| i as f32).collect();
8979        let b_data: Vec<f32> = (0..8).map(|i| 100.0 + i as f32).collect();
8980        let x_arc = up(&x_data);
8981        let (graph, x, b, y) = build();
8982        let mut inputs = StorageCache::new();
8983        inputs.insert(x, x_arc.clone());
8984        // `b` deliberately NOT retained by a local variable — forces
8985        // reliance on `capture_decode`'s own `retained_inputs`.
8986        inputs.insert(b, up(&b_data));
8987
8988        let captured =
8989            PipelinedExecutor::capture_decode(Arc::clone(&graph), y, inputs, SymEnv::default())
8990                .expect("capture_decode same-device copy");
8991
8992        let realize_ref = |xv: &[f32], bv: &[f32]| -> Vec<f32> {
8993            let (g, xr, br, yr) = build();
8994            let mut ins = StorageCache::new();
8995            ins.insert(xr, up(xv));
8996            ins.insert(br, up(bv));
8997            let (arc, _) = PipelinedExecutor::realize(g, yr, ins).expect("ref realize");
8998            read(&arc)
8999        };
9000        let expect0 = realize_ref(&x_data, &b_data);
9001
9002        // (1) warm-run result sits in the captured output buffer.
9003        assert_eq!(read(&captured.output), expect0, "warm result after capture");
9004
9005        // (2) replay TWICE with unchanged inputs — the Copy's write-into
9006        //     destination buffer must stay bit-exact across replays.
9007        for i in 0..2 {
9008            captured
9009                .run
9010                .replay(&dev)
9011                .unwrap_or_else(|e| panic!("replay {i}: {e:?}"));
9012            dev.synchronize().expect("sync");
9013            assert_eq!(
9014                read(&captured.output),
9015                expect0,
9016                "replay {i} reproduces result"
9017            );
9018        }
9019
9020        // (3) overwrite x in place (a DIFFERENT value-set), replay again ->
9021        //     the Copy re-runs on the fixed input address into its fixed
9022        //     destination buffer -> matches an independent uncaptured realize.
9023        let x2: Vec<f32> = (0..8).map(|i| 1000.0 + i as f32).collect();
9024        {
9025            let g = x_arc.read().unwrap();
9026            let BackendStorage::Cuda(c) = &g.inner else {
9027                panic!("x not cuda")
9028            };
9029            c.write_from_host(bytemuck::cast_slice(&x2))
9030                .expect("in-place H2D");
9031        }
9032        captured.run.replay(&dev).expect("replay 3");
9033        dev.synchronize().expect("sync 3");
9034        assert_eq!(
9035            read(&captured.output),
9036            realize_ref(&x2, &b_data),
9037            "replay after x update matches independent uncaptured realize"
9038        );
9039    }
9040
9041    /// CapturedRun executor build-out (Increment 4b-ζ): a genuinely
9042    /// cross-device `Op::Copy` (D2H — `target: DeviceLocation::Cpu` from a
9043    /// CUDA-resident source) must still be REJECTED by `capture_decode`'s
9044    /// validation loop — a host round-trip can never be part of a CUDA
9045    /// graph capture. Fast check: no replay, just confirm the typed `Err`.
9046    #[test]
9047    #[ignore = "requires a live CUDA device"]
9048    #[cfg(feature = "cuda")]
9049    fn capture_decode_rejects_cross_device_copy_cuda() {
9050        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
9051        use fuel_ir::Shape;
9052        use fuel_memory::BackendStorage;
9053
9054        let Ok(dev) = CudaDevice::new(0) else {
9055            return fuel_test_support::hardware::skip(
9056                fuel_test_support::hardware::Hardware::Cuda,
9057                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
9058            );
9059        };
9060
9061        let graph = Arc::new(RwLock::new(Graph::new()));
9062        let (x, y) = {
9063            let mut g = graph.write().unwrap();
9064            let x = g.push(Node {
9065                op: Op::Const,
9066                inputs: vec![],
9067                shape: Shape::from_dims(&[2, 4]),
9068                dtype: DType::F32,
9069            });
9070            // Genuinely cross-device: D2H.
9071            let y = g.push(Node {
9072                op: Op::Copy {
9073                    target: DeviceLocation::Cpu,
9074                },
9075                inputs: vec![x],
9076                shape: Shape::from_dims(&[2, 4]),
9077                dtype: DType::F32,
9078            });
9079            g.set_target_backend(y, BackendId::Cuda); // source backend = Cuda
9080            (x, y)
9081        };
9082
9083        let x_data: Vec<f32> = (0..8).map(|i| i as f32).collect();
9084        let cb =
9085            CudaStorageBytes::from_cpu_bytes(&dev, bytemuck::cast_slice(&x_data)).expect("h2d");
9086        let x_arc = Arc::new(RwLock::new(Storage::new(
9087            BackendStorage::Cuda(cb),
9088            DType::F32,
9089        )));
9090        let mut inputs = StorageCache::new();
9091        inputs.insert(x, x_arc);
9092
9093        let result = PipelinedExecutor::capture_decode(graph, y, inputs, SymEnv::default());
9094        let msg = match result {
9095            Ok(_) => panic!("D2H Op::Copy must be rejected by capture_decode"),
9096            Err(e) => e.to_string(),
9097        };
9098        assert!(
9099            msg.contains("cross-device"),
9100            "error should describe the cross-device rejection: {msg}"
9101        );
9102    }
9103
9104    /// CapturedDecodeSession (Increment 4a): drive the warm→capture→replay
9105    /// orchestration over MANY tokens on a synthetic decode-shaped session —
9106    /// the real per-token decode pattern. Capture once, then per token
9107    /// H2D-update the fixed input buffer IN PLACE + replay, asserting each
9108    /// token's output is bit-exact against an independent uncaptured realize.
9109    /// A kernel-agnostic proof of the state machine + fixed-buffer mechanics
9110    /// (matmul + index_select excluded pending baracuda capture-safe kernels).
9111    #[test]
9112    #[ignore = "requires a live CUDA device"]
9113    #[cfg(feature = "cuda")]
9114    fn captured_decode_session_replays_many_tokens_cuda() {
9115        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
9116        use fuel_graph::registry::{FusedOpParams, FusedOps};
9117        use fuel_ir::Shape;
9118        use fuel_memory::BackendStorage;
9119
9120        let Ok(dev) = CudaDevice::new(0) else {
9121            return fuel_test_support::hardware::skip(
9122                fuel_test_support::hardware::Hardware::Cuda,
9123                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
9124            );
9125        };
9126        const H: usize = 6;
9127        let eps = 1e-5f64;
9128
9129        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId) {
9130            let graph = Arc::new(RwLock::new(Graph::new()));
9131            let (x, y) = {
9132                let mut g = graph.write().unwrap();
9133                let mk = |g: &mut Graph, op: Op, ins: Vec<NodeId>, dims: &[usize]| {
9134                    g.push(Node {
9135                        op,
9136                        inputs: ins,
9137                        shape: Shape::from_dims(dims),
9138                        dtype: DType::F32,
9139                    })
9140                };
9141                let rms = || {
9142                    Op::Fused(
9143                        FusedOps::RMS_NORM_LAST_DIM,
9144                        FusedOpParams::RmsNormLastDim { eps },
9145                    )
9146                };
9147                let sm = || Op::Fused(FusedOps::SOFTMAX_LAST_DIM, FusedOpParams::SoftmaxLastDim);
9148                let x = mk(&mut g, Op::Const, vec![], &[1, H]);
9149                let n1 = mk(&mut g, rms(), vec![x], &[1, H]);
9150                let s = mk(&mut g, Op::Silu, vec![n1], &[1, H]);
9151                let p = mk(&mut g, sm(), vec![s], &[1, H]);
9152                let r = mk(&mut g, Op::Add, vec![p, x], &[1, H]);
9153                let n2 = mk(&mut g, rms(), vec![r], &[1, H]);
9154                let y = mk(&mut g, Op::Add, vec![n2, x], &[1, H]);
9155                for id in [n1, s, p, r, n2, y] {
9156                    g.set_target_backend(id, BackendId::Cuda);
9157                }
9158                (x, y)
9159            };
9160            (graph, x, y)
9161        };
9162        let up = |v: &[f32]| -> Arc<RwLock<Storage>> {
9163            let cb = CudaStorageBytes::from_cpu_bytes(&dev, bytemuck::cast_slice(v)).expect("h2d");
9164            Arc::new(RwLock::new(Storage::new(
9165                BackendStorage::Cuda(cb),
9166                DType::F32,
9167            )))
9168        };
9169        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9170            let g = arc.read().unwrap();
9171            let BackendStorage::Cuda(c) = &g.inner else {
9172                panic!("not cuda")
9173            };
9174            bytemuck::cast_slice(&c.to_cpu_bytes().expect("d2h")).to_vec()
9175        };
9176        let realize_ref = |xv: &[f32]| -> Vec<f32> {
9177            let (g, xr, yr) = build();
9178            let mut ins = StorageCache::new();
9179            ins.insert(xr, up(xv));
9180            let (arc, _) = PipelinedExecutor::realize(g, yr, ins).expect("ref realize");
9181            read(&arc)
9182        };
9183
9184        // 5 distinct "tokens" (distinct per-token input value-sets).
9185        let tokens: Vec<Vec<f32>> = (0..5)
9186            .map(|t| {
9187                (0..H)
9188                    .map(|c| 0.1 * (t as f32 + 1.0) * (c as f32 + 1.0))
9189                    .collect()
9190            })
9191            .collect();
9192
9193        // Capture ONCE against token 0's fixed input buffer.
9194        let x_arc = up(&tokens[0]);
9195        let (graph, x, y) = build();
9196        let mut inputs = StorageCache::new();
9197        inputs.insert(x, x_arc.clone());
9198        let session =
9199            CapturedDecodeSession::capture(Arc::clone(&graph), y, inputs, &[x], SymEnv::default())
9200                .expect("capture session");
9201
9202        // Warm result (token 0) already sits in the output buffer.
9203        assert_eq!(
9204            read(session.output()),
9205            realize_ref(&tokens[0]),
9206            "warm token 0"
9207        );
9208
9209        // The decode loop: replay every token (incl. re-replaying token 0) via
9210        // in-place H2D update of the fixed input + one graph launch.
9211        for (t, tok) in tokens.iter().enumerate() {
9212            let out = session
9213                .replay_token(&[(x, bytemuck::cast_slice(tok))])
9214                .expect("replay_token");
9215            assert_eq!(
9216                read(&out),
9217                realize_ref(tok),
9218                "replayed token {t} matches uncaptured realize"
9219            );
9220        }
9221        // Distinct tokens must give distinct outputs (live recompute, not stale).
9222        assert_ne!(
9223            realize_ref(&tokens[0]),
9224            realize_ref(&tokens[1]),
9225            "tokens must differ"
9226        );
9227    }
9228
9229    /// PR-C1 behavior contract: `realize_with_optimized_route` with an
9230    /// **empty** route (the no-pressure / no-telemetry case) is
9231    /// byte-identical to `realize_with_optimized` (arm-0). On a branchless
9232    /// graph the route has no branches to resolve, so both must produce
9233    /// the same bytes — realize is unchanged from Phase B.
9234    #[test]
9235    fn realize_with_optimized_route_empty_equals_arm0() {
9236        use crate::optimize::OptimizedGraph;
9237
9238        let build = || {
9239            let graph = Arc::new(RwLock::new(Graph::new()));
9240            let (lhs_id, rhs_id, add_id) = {
9241                let mut g = graph.write().unwrap();
9242                let lhs_id = g.push(Node {
9243                    op: Op::Const,
9244                    inputs: vec![],
9245                    shape: Shape::from_dims(&[3]),
9246                    dtype: DType::F32,
9247                });
9248                let rhs_id = g.push(Node {
9249                    op: Op::Const,
9250                    inputs: vec![],
9251                    shape: Shape::from_dims(&[3]),
9252                    dtype: DType::F32,
9253                });
9254                let add_id = g.push(Node {
9255                    op: Op::Add,
9256                    inputs: vec![lhs_id, rhs_id],
9257                    shape: Shape::from_dims(&[3]),
9258                    dtype: DType::F32,
9259                });
9260                g.set_target_backend(add_id, BackendId::Cpu);
9261                (lhs_id, rhs_id, add_id)
9262            };
9263            let mut inputs = StorageCache::new();
9264            inputs.insert(
9265                lhs_id,
9266                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9267                    1.0_f32, 2.0, 3.0,
9268                ]))),
9269            );
9270            inputs.insert(
9271                rhs_id,
9272                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9273                    10.0_f32, 20.0, 30.0,
9274                ]))),
9275            );
9276            (graph, add_id, inputs)
9277        };
9278
9279        let read_bytes = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9280            let guard = arc.read().unwrap();
9281            match &guard.inner {
9282                fuel_memory::BackendStorage::Cpu(c) => {
9283                    c.as_slice::<f32>().expect("f32 cast").to_vec()
9284                }
9285                _ => panic!("expected CPU output"),
9286            }
9287        };
9288
9289        // Stamp the fixture with the LIVE topology generation rather than a
9290        // hard-coded 0. The executor's chunk-boundary check compares the plan's
9291        // stamped generation against `topology_generation()`; a real
9292        // `OptimizedGraph` carries the generation snapshotted at optimize time
9293        // (`plan.rs` `compile_plan`, which reads it *after* the bindings table
9294        // is warm), so it already reflects every registered backend. Force
9295        // `global_bindings()` init here so any feature-gated auto-registration
9296        // has run and settled the counter before we read it — otherwise a stale
9297        // read would be bumped out from under us the first time realize warms
9298        // the bindings. Under default features this is 0; under
9299        // `--features vulkan`, `register_derived_gpu_caps` bumps it to 1.
9300        drop(global_bindings());
9301        let live_gen = crate::dispatch::topology_generation();
9302
9303        // Arm-0 path.
9304        let (g_a, add_a, in_a) = build();
9305        let opt_a = OptimizedGraph {
9306            roots: vec![add_a],
9307            generation: live_gen,
9308            placements: None,
9309            eviction: None,
9310        };
9311        let (arm0_arc, _) = PipelinedExecutor::realize_with_optimized(g_a, add_a, in_a, &opt_a)
9312            .expect("arm-0 realize");
9313        let arm0 = read_bytes(&arm0_arc);
9314
9315        // Empty-route path — must match arm-0 exactly.
9316        let (g_r, add_r, in_r) = build();
9317        let opt_r = OptimizedGraph {
9318            roots: vec![add_r],
9319            generation: live_gen,
9320            placements: None,
9321            eviction: None,
9322        };
9323        let empty_route = PickedRoute::new();
9324        let (route_arc, _) =
9325            PipelinedExecutor::realize_with_optimized_route(g_r, add_r, in_r, &opt_r, &empty_route)
9326                .expect("empty-route realize");
9327        let routed = read_bytes(&route_arc);
9328
9329        assert_eq!(arm0, vec![11.0, 22.0, 33.0]);
9330        assert_eq!(
9331            routed, arm0,
9332            "an empty route realizes byte-identically to arm-0 (Phase B contract)",
9333        );
9334    }
9335
9336    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
9337    /// §5): [`PipelinedExecutor::realize_with_optimized_picking_cached_env`]
9338    /// over a shared `order_cache` must (a) realize byte-identically to the
9339    /// uncached arm-0 path, on both the cold (empty cache) and warm
9340    /// (populated cache) call, and (b) actually populate the cache on the
9341    /// first call rather than silently never using it.
9342    #[test]
9343    fn realize_with_optimized_picking_cached_env_matches_arm0_cold_and_warm() {
9344        use crate::optimize::OptimizedGraph;
9345        use std::sync::OnceLock;
9346
9347        let build = || {
9348            let graph = Arc::new(RwLock::new(Graph::new()));
9349            let (lhs_id, rhs_id, add_id) = {
9350                let mut g = graph.write().unwrap();
9351                let lhs_id = g.push(Node {
9352                    op: Op::Const,
9353                    inputs: vec![],
9354                    shape: Shape::from_dims(&[3]),
9355                    dtype: DType::F32,
9356                });
9357                let rhs_id = g.push(Node {
9358                    op: Op::Const,
9359                    inputs: vec![],
9360                    shape: Shape::from_dims(&[3]),
9361                    dtype: DType::F32,
9362                });
9363                let add_id = g.push(Node {
9364                    op: Op::Add,
9365                    inputs: vec![lhs_id, rhs_id],
9366                    shape: Shape::from_dims(&[3]),
9367                    dtype: DType::F32,
9368                });
9369                g.set_target_backend(add_id, BackendId::Cpu);
9370                (lhs_id, rhs_id, add_id)
9371            };
9372            let mut inputs = StorageCache::new();
9373            inputs.insert(
9374                lhs_id,
9375                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9376                    1.0_f32, 2.0, 3.0,
9377                ]))),
9378            );
9379            inputs.insert(
9380                rhs_id,
9381                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9382                    10.0_f32, 20.0, 30.0,
9383                ]))),
9384            );
9385            (graph, add_id, inputs)
9386        };
9387        let read_bytes = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9388            let guard = arc.read().unwrap();
9389            match &guard.inner {
9390                fuel_memory::BackendStorage::Cpu(c) => {
9391                    c.as_slice::<f32>().expect("f32 cast").to_vec()
9392                }
9393                _ => panic!("expected CPU output"),
9394            }
9395        };
9396
9397        drop(global_bindings());
9398        let live_gen = crate::dispatch::topology_generation();
9399
9400        let (g, add, inputs) = build();
9401        let optimized = OptimizedGraph {
9402            roots: vec![add],
9403            generation: live_gen,
9404            placements: None,
9405            eviction: None,
9406        };
9407        let order_cache: OnceLock<Vec<NodeId>> = OnceLock::new();
9408        assert!(order_cache.get().is_none(), "sanity: cache starts empty");
9409
9410        // Cold call: cache miss, must compute AND populate.
9411        let (cold_arc, _) = PipelinedExecutor::realize_with_optimized_picking_cached_env(
9412            g.clone(),
9413            add,
9414            inputs,
9415            &optimized,
9416            &order_cache,
9417            None,
9418            None,
9419            SymEnv::default(),
9420        )
9421        .expect("cold cached realize");
9422        assert_eq!(read_bytes(&cold_arc), vec![11.0, 22.0, 33.0]);
9423        assert!(
9424            order_cache.get().is_some(),
9425            "the cold call must populate order_cache, not leave it empty"
9426        );
9427        let cached_order_after_cold = order_cache.get().unwrap().clone();
9428
9429        // Warm call: cache hit. Fresh inputs (same graph, new values) so the
9430        // realized OUTPUT differs from the cold call while the dispatch
9431        // ORDER (what's cached) must not change.
9432        let mut warm_inputs = StorageCache::new();
9433        warm_inputs.insert(
9434            g.read().unwrap().node(add).inputs[0],
9435            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9436                100.0_f32, 200.0, 300.0,
9437            ]))),
9438        );
9439        warm_inputs.insert(
9440            g.read().unwrap().node(add).inputs[1],
9441            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9442                1.0_f32, 2.0, 3.0,
9443            ]))),
9444        );
9445        let (warm_arc, _) = PipelinedExecutor::realize_with_optimized_picking_cached_env(
9446            g,
9447            add,
9448            warm_inputs,
9449            &optimized,
9450            &order_cache,
9451            None,
9452            None,
9453            SymEnv::default(),
9454        )
9455        .expect("warm cached realize");
9456        assert_eq!(
9457            read_bytes(&warm_arc),
9458            vec![101.0, 202.0, 303.0],
9459            "warm call must realize its OWN rebound inputs, not replay stale output",
9460        );
9461        assert_eq!(
9462            order_cache.get().unwrap(),
9463            &cached_order_after_cold,
9464            "the warm call must reuse the SAME cached order, not recompute a different one",
9465        );
9466    }
9467
9468    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
9469    /// §5), PM review question: does `OrderSource::Cached` weaken the
9470    /// existing `TopologyChanged` chunk-boundary check? No — proven at the
9471    /// unit level (not a live topology-bump integration test, deliberately:
9472    /// `bump_topology_generation()` mutates a process-wide atomic shared by
9473    /// every concurrently-running test in this binary, including the cold/
9474    /// warm cache test above, which reads it into a local at the start of
9475    /// ITS OWN body and would flake if another test's bump landed mid-call;
9476    /// introducing that cross-test hazard isn't worth it when the two arms'
9477    /// `generation_for` expressions are provably identical). `generation_for`
9478    /// is private to this module, so it's tested directly here: given the
9479    /// SAME `&OptimizedGraph`, `Cached` and `Optimized` must report the
9480    /// IDENTICAL generation — the chunk-boundary check that compares this
9481    /// value against the LIVE `topology_generation()` fires exactly the
9482    /// same way for both, so caching cannot silently skip or weaken it.
9483    #[test]
9484    fn cached_generation_for_matches_optimized_generation_for() {
9485        let optimized = OptimizedGraph {
9486            roots: vec![NodeId(0)],
9487            generation: 42,
9488            placements: None,
9489            eviction: None,
9490        };
9491        let order_cache: std::sync::OnceLock<Vec<NodeId>> = std::sync::OnceLock::new();
9492
9493        let optimized_gen = generation_for(&OrderSource::Optimized {
9494            optimized: &optimized,
9495            route: None,
9496        });
9497        let cached_gen = generation_for(&OrderSource::Cached {
9498            optimized: &optimized,
9499            order_cache: &order_cache,
9500        });
9501        assert_eq!(
9502            optimized_gen,
9503            Some(42),
9504            "sanity: Optimized reports the OptimizedGraph's own generation",
9505        );
9506        assert_eq!(
9507            cached_gen, optimized_gen,
9508            "Cached must report the SAME generation as Optimized for the same \
9509             OptimizedGraph -- the TopologyChanged check cannot tell the two apart, \
9510             by construction, so caching cannot silently weaken it",
9511        );
9512    }
9513
9514    /// **PR-C3 reorder-invariance gate (CPU, runnable — ORDERING level).**
9515    /// The auto-overlap reorder is a HINT: it changes only *which order*
9516    /// independent device runs dispatch in, never *which* nodes run nor the
9517    /// result. The byte-identical-OUTPUT proof is necessarily LIVE (the
9518    /// reorder fires only on a ≥2-device graph, which needs ≥2 real backends
9519    /// to realize — see `cuda_vulkan_multidevice_realize_live`'s
9520    /// `[22,86,192,340]` oracle, which now flows through this reorder, plus
9521    /// the dual-GPU `cuda_vulkan_overlap_bench_live` arbitrary-graph
9522    /// auto-overlap gate). THIS test proves the ordering-level invariant on a
9523    /// CPU-only path: the C3 reorder of a two-device graph is a valid
9524    /// topological **permutation** of the un-reordered topo order — same node
9525    /// multiset, every node still after its inputs — that genuinely DIFFERS
9526    /// from the un-reordered order (so the reorder fired). Because the
9527    /// executor caches each node's result and every op is deterministic,
9528    /// realizing any valid topological order yields identical bytes; this
9529    /// test guards the precondition (a valid permutation) that makes that so.
9530    #[test]
9531    fn c3_reorder_is_a_valid_topo_permutation() {
9532        // Two INDEPENDENT device sub-chains over distinct consts reconverging
9533        // at a final CUDA add, the Vulkan root bridged to CUDA by an explicit
9534        // Op::Copy (a residency seam = its own run). Reconverge inputs in the
9535        // "wrong" (cuda-first) order, the order the un-reordered topo DFS pops
9536        // CUDA-last — exactly the arbitrary-graph shape the auto-overlap pass
9537        // must fix. The chains are UNARY (Relu) so each stays a single
9538        // contiguous run (no const-re-read fan-in fragmenting them), exactly
9539        // like the live benchmark's `relu(mul·add)` chains; the CUDA chain is
9540        // HEAVIER (4 vs 2) so the critical-path reorder emits it first.
9541        // (Stamps only; not realized here — the ordering proof, CPU-runnable.)
9542        let n = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9543            g.push(Node {
9544                op,
9545                inputs,
9546                shape: Shape::from_dims(&[3]),
9547                dtype: DType::F32,
9548            })
9549        };
9550        let mut g = Graph::new();
9551        let ca = n(&mut g, Op::Const, vec![]);
9552        let cb = n(&mut g, Op::Const, vec![]);
9553        // CUDA chain — HEAVIER (4 unary stages, one contiguous run).
9554        let mut cprev = ca;
9555        for _ in 0..4 {
9556            cprev = n(&mut g, Op::Relu, vec![cprev]);
9557            g.set_target_backend(cprev, BackendId::Cuda);
9558        }
9559        let c2 = cprev; // CUDA chunk root
9560        // Vulkan chain — lighter (2 unary stages).
9561        let mut vprev = cb;
9562        for _ in 0..2 {
9563            vprev = n(&mut g, Op::Relu, vec![vprev]);
9564            g.set_target_backend(vprev, BackendId::Vulkan);
9565        }
9566        let v2 = vprev; // Vulkan chunk root
9567        // Vulkan -> CUDA copy (residency seam), then reconverge on CUDA with
9568        // inputs [cuda_root, copy] (cuda-first).
9569        let copy = g.push(Node {
9570            op: Op::Copy {
9571                target: DeviceLocation::Cuda { gpu_id: 0 },
9572            },
9573            inputs: vec![v2],
9574            shape: Shape::from_dims(&[3]),
9575            dtype: DType::F32,
9576        });
9577        g.set_target_backend(copy, BackendId::Cuda);
9578        let out = n(&mut g, Op::Add, vec![c2, copy]);
9579        g.set_target_backend(out, BackendId::Cuda);
9580
9581        let unreordered = execution_plan(&g, &[out]);
9582        let reordered = fuel_graph::lower_runs_arm0(&g, &[out]);
9583
9584        // (1) The reorder FIRED — the order changed (else the test is
9585        //     vacuous + auto-overlap did nothing on an arbitrary graph).
9586        assert_ne!(
9587            reordered, unreordered,
9588            "the C3 reorder must change the order on a two-device graph; \
9589             reordered={reordered:?} unreordered={unreordered:?}",
9590        );
9591
9592        // (2) Same node multiset — a permutation, no add/drop.
9593        let mut a = unreordered.clone();
9594        let mut b = reordered.clone();
9595        a.sort();
9596        b.sort();
9597        assert_eq!(a, b, "the reorder is a permutation of the same node set");
9598
9599        // (3) The reordered order is a VALID topological order: every node
9600        //     appears after all of its inputs that are in the order.
9601        let pos: std::collections::HashMap<NodeId, usize> = reordered
9602            .iter()
9603            .enumerate()
9604            .map(|(i, &node)| (node, i))
9605            .collect();
9606        for (i, &node) in reordered.iter().enumerate() {
9607            for &inp in &g.node(node).inputs {
9608                if let Some(&j) = pos.get(&inp) {
9609                    assert!(
9610                        j < i,
9611                        "input {inp:?} of {node:?} must precede it in the reordered \
9612                         order; reordered={reordered:?}",
9613                    );
9614                }
9615            }
9616        }
9617
9618        // (4) The overlap-relevant property: BOTH device producer chunks
9619        //     (the CUDA root c2, the Vulkan root v2) are emitted BEFORE the
9620        //     host-blocking cross-device copy — the A4b overlap topology the
9621        //     un-reordered cuda-last DFS violates — AND the HEAVIER CUDA chunk
9622        //     is emitted first (critical-path: the auto-submit device runs
9623        //     earliest, the live-overlap regression guard).
9624        let p = |node: NodeId| pos[&node];
9625        assert!(p(c2) < p(copy), "CUDA chunk before the cross-device copy");
9626        assert!(p(v2) < p(copy), "Vulkan chunk before the cross-device copy");
9627        assert!(
9628            p(c2) < p(v2),
9629            "the heavier CUDA chunk is emitted before the lighter Vulkan chunk \
9630             (critical-path heavy-first); reordered={reordered:?}",
9631        );
9632    }
9633
9634    /// **C3 follow-on — the OPERAND-ORDER-INVARIANCE gate (CPU, runnable —
9635    /// the reliable operand-independence proof).** The residual the live
9636    /// `cuda_vulkan_overlap_bench_live` benchmark targets is whether the
9637    /// reconverge OPERAND order (`xc.add(&xv)` vs `xv.add(&xc)`) changes the
9638    /// wall-clock overlap. Wall-clock is thermally noisy on a heterogeneous
9639    /// dev box; the DETERMINISTIC root guarantee is this: the C3-reordered
9640    /// dispatch order the executor consumes is **byte-identical for both
9641    /// operand orders**. If the lowered order is the same, the executor
9642    /// processes the SAME WorkItem stream with the SAME cross-device
9643    /// submit/wait timing, so overlap cannot depend on the operand order.
9644    ///
9645    /// This builds the SAME two-device reconverge as
9646    /// `c3_reorder_is_a_valid_topo_permutation` but TWICE — once cuda-first
9647    /// (`add(cuda_root, copy)`), once vulkan-first (`add(copy, cuda_root)`)
9648    /// — over structurally identical graphs (same node ids, only the
9649    /// reconverge's two inputs swapped) and asserts `lower_runs_arm0` emits
9650    /// the identical op/device run sequence. The live executor trace confirms
9651    /// the same: both operand orders produce the identical WorkItem stream
9652    /// (the eager-submit/drain/wait sequence at every cross-device copy is the
9653    /// same, and the CUDA chunk is enqueued first in both).
9654    #[test]
9655    fn c3_reorder_is_operand_order_invariant() {
9656        // Build the two-device reconverge with the reconverge inputs in the
9657        // given order; return (graph, out) over a FRESH graph so node ids line
9658        // up 1:1 between the two builds (only the add's input order differs).
9659        let build = |cuda_first: bool| -> (Graph, NodeId) {
9660            let n = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9661                g.push(Node {
9662                    op,
9663                    inputs,
9664                    shape: Shape::from_dims(&[3]),
9665                    dtype: DType::F32,
9666                })
9667            };
9668            let mut g = Graph::new();
9669            let ca = n(&mut g, Op::Const, vec![]);
9670            let cb = n(&mut g, Op::Const, vec![]);
9671            let mut cprev = ca;
9672            for _ in 0..4 {
9673                cprev = n(&mut g, Op::Relu, vec![cprev]);
9674                g.set_target_backend(cprev, BackendId::Cuda);
9675            }
9676            let c2 = cprev;
9677            let mut vprev = cb;
9678            for _ in 0..2 {
9679                vprev = n(&mut g, Op::Relu, vec![vprev]);
9680                g.set_target_backend(vprev, BackendId::Vulkan);
9681            }
9682            let v2 = vprev;
9683            let copy = g.push(Node {
9684                op: Op::Copy {
9685                    target: DeviceLocation::Cuda { gpu_id: 0 },
9686                },
9687                inputs: vec![v2],
9688                shape: Shape::from_dims(&[3]),
9689                dtype: DType::F32,
9690            });
9691            g.set_target_backend(copy, BackendId::Cuda);
9692            // The ONE knob: the reconverge's two inputs, swapped.
9693            let inputs = if cuda_first {
9694                vec![c2, copy]
9695            } else {
9696                vec![copy, c2]
9697            };
9698            let out = n(&mut g, Op::Add, inputs);
9699            g.set_target_backend(out, BackendId::Cuda);
9700            (g, out)
9701        };
9702
9703        let (g_cf, out_cf) = build(true);
9704        let (g_vf, out_vf) = build(false);
9705
9706        // Lower both via the production path (dispatch_order → lower_runs_arm0
9707        // → device_alternating_order, the C3 reorder).
9708        let order_cf = fuel_graph::lower_runs_arm0(&g_cf, &[out_cf]);
9709        let order_vf = fuel_graph::lower_runs_arm0(&g_vf, &[out_vf]);
9710
9711        // The decisive guarantee: the lowered dispatch order — as an
9712        // (op, device) sequence — is IDENTICAL for both operand orders. (Node
9713        // ids can differ if the build assigned them differently, but here the
9714        // builds are structurally identical so even the ids match; compare the
9715        // op/device sequence to be robust + descriptive on failure.)
9716        let tag = |g: &Graph, ids: &[NodeId]| -> Vec<(String, Option<BackendId>)> {
9717            ids.iter()
9718                .map(|&id| (format!("{:?}", g.node(id).op), g.target_backend(id)))
9719                .collect()
9720        };
9721        let seq_cf = tag(&g_cf, &order_cf);
9722        let seq_vf = tag(&g_vf, &order_vf);
9723        assert_eq!(
9724            seq_cf, seq_vf,
9725            "the C3-reordered dispatch order MUST be identical for both \
9726             reconverge operand orders (operand-order-invariance — the \
9727             executor then sees the same WorkItem stream regardless of \
9728             operand order, so overlap is operand-insensitive).\n\
9729             cuda-first = {seq_cf:?}\nvulkan-first = {seq_vf:?}",
9730        );
9731    }
9732
9733    /// A selector that always takes the LAST arm (arm 1) so a non-arm-0
9734    /// pick is observable (a `WinnerSelector` picks arm-0 ⇒ empty route).
9735    #[cfg(test)]
9736    #[derive(Debug)]
9737    struct PickLast;
9738    #[cfg(test)]
9739    impl RuntimeSelector for PickLast {
9740        fn select<'a>(
9741            &self,
9742            set: &'a crate::ranker::AlternativeSet,
9743        ) -> Option<&'a crate::ranker::Candidate> {
9744            set.alternatives().last()
9745        }
9746    }
9747
9748    /// Build the 2-arm diamond (mirrors `route_picker::tests::diamond`):
9749    /// arm-0 on CUDA, arm-1 on CPU; the arm exits carry their
9750    /// `target_backend` so the picker reads each arm's placement. Returns
9751    /// `(graph_arc, branch, post)`.
9752    #[cfg(test)]
9753    fn picking_diamond() -> (Arc<RwLock<Graph>>, NodeId, NodeId) {
9754        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9755            g.push(Node {
9756                op,
9757                inputs,
9758                shape: Shape::from_dims(&[2]),
9759                dtype: DType::F32,
9760            })
9761        };
9762        let mut g = Graph::new();
9763        let pre = node(&mut g, Op::Const, vec![]);
9764        let diverge = node(&mut g, Op::Relu, vec![pre]);
9765        let arm0 = node(&mut g, Op::Silu, vec![diverge]);
9766        let arm1 = node(&mut g, Op::GeluTanh, vec![diverge]);
9767        g.set_target_backend(arm0, BackendId::Cuda);
9768        g.set_target_backend(arm1, BackendId::Cpu);
9769        let reconverge = node(&mut g, Op::Relu, vec![arm0]);
9770        let mut b = g.open_branch(diverge);
9771        b.add_arm(arm0);
9772        b.add_arm(arm1);
9773        let branch = b
9774            .finalize_branches(&mut g, reconverge)
9775            .expect("well-formed 2-arm branch")
9776            .expect("2 arms survive");
9777        let post = node(&mut g, Op::Tanh, vec![reconverge]);
9778        (Arc::new(RwLock::new(g)), branch, post)
9779    }
9780
9781    /// Step E Phase C, PR C1: the streaming picking entry's gate.
9782    /// `streaming_pick_for` (the streaming successor of the old one-shot
9783    /// `pick_route_for`) must (1) return `Some(pick)` when a selector + a
9784    /// branch are present (⇒ the `OrderSource::Streaming` walk), (2) return
9785    /// `None` with no selector (the `runtime_selector_disabled` opt-out ⇒
9786    /// arm-0), and (3) short-circuit to `None` on a branchless graph (the
9787    /// fast-path ⇒ the untouched `dispatch_order` lowering).
9788    #[test]
9789    fn streaming_pick_for_gates() {
9790        let (graph, _branch, post) = picking_diamond();
9791        let _ = post;
9792
9793        // (1) selector + branch ⇒ Some(pick).
9794        let sel: Arc<dyn RuntimeSelector> = Arc::new(PickLast);
9795        assert!(
9796            PipelinedExecutor::streaming_pick_for(&graph, Some(sel.clone()), None)
9797                .expect("ok")
9798                .is_some(),
9799            "selector + branch ⇒ a streaming pick",
9800        );
9801
9802        // (2) no selector ⇒ None (arm-0 lowering).
9803        assert!(
9804            PipelinedExecutor::streaming_pick_for(&graph, None, None)
9805                .expect("ok")
9806                .is_none(),
9807            "no selector ⇒ no streaming pick (arm-0 lowering)",
9808        );
9809
9810        // (3) branchless graph + selector ⇒ None (the fast-path).
9811        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9812            g.push(Node {
9813                op,
9814                inputs,
9815                shape: Shape::from_dims(&[2]),
9816                dtype: DType::F32,
9817            })
9818        };
9819        let bl_graph = {
9820            let mut g = Graph::new();
9821            let c1 = node(&mut g, Op::Const, vec![]);
9822            let c2 = node(&mut g, Op::Const, vec![]);
9823            let add = node(&mut g, Op::Add, vec![c1, c2]);
9824            g.set_target_backend(add, BackendId::Cpu);
9825            Arc::new(RwLock::new(g))
9826        };
9827        assert!(
9828            PipelinedExecutor::streaming_pick_for(&bl_graph, Some(sel), None)
9829                .expect("ok")
9830                .is_none(),
9831            "branchless graph ⇒ no branches ⇒ no streaming pick (fast-path)",
9832        );
9833    }
9834
9835    /// **C1 byte-identity gate (executor layer).** The STREAMED dispatch
9836    /// order — produced by the compiler thread's lazy per-branch resolution
9837    /// (`walk_picked_route_streaming` over `resolve_branch`, the same path
9838    /// `order_for(OrderSource::Streaming)` collects) — equals the ONE-SHOT
9839    /// order (`lower_picked_route` over the route the eager `pick_route`
9840    /// resolves) on the branched diamond, for both arm-0 (WinnerSelector)
9841    /// and arm-1 (PickLast). This is the proof that C1 changes *when* a
9842    /// branch resolves, not *which* arm — the same selector, the same
9843    /// `resolve_branch`, the same emitted order.
9844    #[test]
9845    fn streamed_order_equals_one_shot() {
9846        let (graph, _branch, post) = picking_diamond();
9847        let g = graph.read().unwrap();
9848        let bindings = global_bindings();
9849
9850        for sel in [
9851            Arc::new(crate::ranker::WinnerSelector) as Arc<dyn RuntimeSelector>,
9852            Arc::new(PickLast) as Arc<dyn RuntimeSelector>,
9853        ] {
9854            // One-shot: resolve the whole route, then lower.
9855            let one_shot_route = pick_route(&g, &[post], &bindings, sel.as_ref(), None);
9856            let one_shot = fuel_graph::lower_picked_route(&g, &[post], &one_shot_route);
9857
9858            // Streamed: resolve each branch lazily at the frontier via the
9859            // SAME `resolve_branch` the compiler thread uses.
9860            let streamed = fuel_graph::lower_picked_route_streaming(&g, &[post], |branch| {
9861                resolve_branch(&g, branch, &bindings, sel.as_ref())
9862            });
9863
9864            assert_eq!(
9865                streamed, one_shot,
9866                "streamed order must equal one-shot for selector {sel:?}",
9867            );
9868        }
9869    }
9870
9871    /// Realizing a node whose target_backend isn't set surfaces a
9872    /// typed error (no panic).
9873    #[test]
9874    fn pipelined_errors_on_unset_target_backend() {
9875        let graph = Arc::new(RwLock::new(Graph::new()));
9876        let (lhs_id, rhs_id, add_id) = {
9877            let mut g = graph.write().unwrap();
9878            let lhs = g.push(Node {
9879                op: Op::Const,
9880                inputs: vec![],
9881                shape: Shape::from_dims(&[2]),
9882                dtype: DType::F32,
9883            });
9884            let rhs = g.push(Node {
9885                op: Op::Const,
9886                inputs: vec![],
9887                shape: Shape::from_dims(&[2]),
9888                dtype: DType::F32,
9889            });
9890            // Deliberately do NOT call set_target_backend on the Add.
9891            let add = g.push(Node {
9892                op: Op::Add,
9893                inputs: vec![lhs, rhs],
9894                shape: Shape::from_dims(&[2]),
9895                dtype: DType::F32,
9896            });
9897            (lhs, rhs, add)
9898        };
9899
9900        let mut inputs = StorageCache::new();
9901        inputs.insert(
9902            lhs_id,
9903            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]))),
9904        );
9905        inputs.insert(
9906            rhs_id,
9907            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[3.0_f32, 4.0]))),
9908        );
9909
9910        let result = PipelinedExecutor::realize(graph, add_id, inputs);
9911        assert!(result.is_err(), "missing target_backend must error");
9912        let msg = result.unwrap_err().to_string();
9913        assert!(
9914            msg.contains("target_backend"),
9915            "error names the unmet precondition: {msg}"
9916        );
9917    }
9918
9919    /// Realizing a Const-only graph adopts the pre-seeded input
9920    /// without calling any kernel.
9921    #[test]
9922    fn pipelined_realize_const_only() {
9923        let storage = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0, 7.0]);
9924
9925        let graph = Arc::new(RwLock::new(Graph::new()));
9926        let const_id = {
9927            let mut g = graph.write().unwrap();
9928            g.push(Node {
9929                op: Op::Const,
9930                inputs: vec![],
9931                shape: Shape::from_dims(&[3]),
9932                dtype: DType::F32,
9933            })
9934        };
9935
9936        let mut inputs = StorageCache::new();
9937        inputs.insert(const_id, Arc::new(RwLock::new(storage)));
9938
9939        let (result_arc, _) =
9940            PipelinedExecutor::realize(graph, const_id, inputs).expect("realize const");
9941        let guard = result_arc.read().unwrap();
9942        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
9943            let typed: &[f32] = c.as_slice().unwrap();
9944            assert_eq!(typed, &[5.0, 6.0, 7.0]);
9945        }
9946    }
9947
9948    /// Missing input-cache entry for a Const surfaces a typed error.
9949    #[test]
9950    fn pipelined_errors_on_missing_const_input() {
9951        let graph = Arc::new(RwLock::new(Graph::new()));
9952        let const_id = {
9953            let mut g = graph.write().unwrap();
9954            g.push(Node {
9955                op: Op::Const,
9956                inputs: vec![],
9957                shape: Shape::from_dims(&[2]),
9958                dtype: DType::F32,
9959            })
9960        };
9961        // Deliberately empty input cache.
9962        let inputs = StorageCache::new();
9963        let result = PipelinedExecutor::realize(graph, const_id, inputs);
9964        assert!(result.is_err());
9965    }
9966
9967    /// E2E: 2-node graph (Const + Relu) — exercises the unary
9968    /// dispatch wrapper + kernel through the pipelined executor.
9969    #[test]
9970    fn pipelined_realize_const_relu() {
9971        let storage = fuel_memory::from_slice_cpu(&[-1.0_f32, 0.0, 0.5, -3.5, 7.25]);
9972        let graph = Arc::new(RwLock::new(Graph::new()));
9973        let (in_id, relu_id) = {
9974            let mut g = graph.write().unwrap();
9975            let in_id = g.push(Node {
9976                op: Op::Const,
9977                inputs: vec![],
9978                shape: Shape::from_dims(&[5]),
9979                dtype: DType::F32,
9980            });
9981            let relu_id = g.push(Node {
9982                op: Op::Relu,
9983                inputs: vec![in_id],
9984                shape: Shape::from_dims(&[5]),
9985                dtype: DType::F32,
9986            });
9987            g.set_target_backend(relu_id, BackendId::Cpu);
9988            (in_id, relu_id)
9989        };
9990        let mut inputs = StorageCache::new();
9991        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
9992
9993        let (result_arc, _) = PipelinedExecutor::realize(graph, relu_id, inputs).expect("realize");
9994        let guard = result_arc.read().unwrap();
9995        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
9996            let typed: &[f32] = c.as_slice().expect("f32 cast");
9997            assert_eq!(typed, &[0.0, 0.0, 0.5, 0.0, 7.25]);
9998        }
9999    }
10000
10001    /// E2E: Const + Const + Sub + Mul + Div — exercises three more
10002    /// of the freshly-migrated binary kernels in one graph. Verifies
10003    /// that intermediates flow through the cache as expected.
10004    #[test]
10005    fn pipelined_realize_chained_binary_ops() {
10006        let a_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
10007        let b_storage = fuel_memory::from_slice_cpu(&[3.0_f32, 5.0]);
10008        let c_storage = fuel_memory::from_slice_cpu(&[2.0_f32, 4.0]);
10009
10010        let graph = Arc::new(RwLock::new(Graph::new()));
10011        let (a_id, b_id, c_id, sub_id, mul_id, div_id) = {
10012            let mut g = graph.write().unwrap();
10013            let a = g.push(Node {
10014                op: Op::Const,
10015                inputs: vec![],
10016                shape: Shape::from_dims(&[2]),
10017                dtype: DType::F32,
10018            });
10019            let b = g.push(Node {
10020                op: Op::Const,
10021                inputs: vec![],
10022                shape: Shape::from_dims(&[2]),
10023                dtype: DType::F32,
10024            });
10025            let c = g.push(Node {
10026                op: Op::Const,
10027                inputs: vec![],
10028                shape: Shape::from_dims(&[2]),
10029                dtype: DType::F32,
10030            });
10031            // (a - b)         = [7, 15]
10032            let sub = g.push(Node {
10033                op: Op::Sub,
10034                inputs: vec![a, b],
10035                shape: Shape::from_dims(&[2]),
10036                dtype: DType::F32,
10037            });
10038            // (a - b) * c     = [14, 60]
10039            let mul = g.push(Node {
10040                op: Op::Mul,
10041                inputs: vec![sub, c],
10042                shape: Shape::from_dims(&[2]),
10043                dtype: DType::F32,
10044            });
10045            // ((a-b)*c) / b   = [14/3, 12]
10046            let div = g.push(Node {
10047                op: Op::Div,
10048                inputs: vec![mul, b],
10049                shape: Shape::from_dims(&[2]),
10050                dtype: DType::F32,
10051            });
10052            g.set_target_backend(sub, BackendId::Cpu);
10053            g.set_target_backend(mul, BackendId::Cpu);
10054            g.set_target_backend(div, BackendId::Cpu);
10055            (a, b, c, sub, mul, div)
10056        };
10057
10058        let _ = (sub_id, mul_id);
10059        let mut inputs = StorageCache::new();
10060        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
10061        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
10062        inputs.insert(c_id, Arc::new(RwLock::new(c_storage)));
10063
10064        let (result_arc, _) = PipelinedExecutor::realize(graph, div_id, inputs).expect("realize");
10065        let guard = result_arc.read().unwrap();
10066        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
10067            let typed: &[f32] = c.as_slice().unwrap();
10068            assert!((typed[0] - (14.0_f32 / 3.0)).abs() < 1e-6);
10069            assert!((typed[1] - 12.0).abs() < 1e-6);
10070        }
10071    }
10072
10073    /// E2E: Const + Transpose — verifies metadata-only view ops
10074    /// share the input's Storage Arc and produce a strided Layout.
10075    /// Stage 3 of Layout-on-Node.
10076    #[test]
10077    fn pipelined_realize_transpose_is_metadata_only() {
10078        // shape [2, 3]; transpose → shape [3, 2], strided
10079        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
10080        let graph = Arc::new(RwLock::new(Graph::new()));
10081        let (in_id, t_id) = {
10082            let mut g = graph.write().unwrap();
10083            let in_id = g.push(Node {
10084                op: Op::Const,
10085                inputs: vec![],
10086                shape: Shape::from_dims(&[2, 3]),
10087                dtype: DType::F32,
10088            });
10089            let t_id = g.push(Node {
10090                op: Op::Transpose,
10091                inputs: vec![in_id],
10092                shape: Shape::from_dims(&[3, 2]),
10093                dtype: DType::F32,
10094            });
10095            // Note: NO set_target_backend — transpose is metadata-only
10096            // and doesn't run on a backend.
10097            (in_id, t_id)
10098        };
10099        let mut inputs = StorageCache::new();
10100        let in_arc = Arc::new(RwLock::new(storage));
10101        inputs.insert(in_id, Arc::clone(&in_arc));
10102
10103        let (result_arc, result_layout) =
10104            PipelinedExecutor::realize(graph, t_id, inputs).expect("realize");
10105
10106        // The output Storage Arc is the SAME Arc as the input —
10107        // metadata-only adoption shares bytes.
10108        assert!(
10109            Arc::ptr_eq(&result_arc, &in_arc),
10110            "transpose must share input bytes"
10111        );
10112
10113        // The output Layout is the transposed view.
10114        assert_eq!(result_layout.shape().dims(), &[3, 2]);
10115        assert_eq!(result_layout.stride(), &[1, 3]);
10116        assert!(!result_layout.is_contiguous());
10117    }
10118
10119    /// E2E: Const + Flip(dim=0) — verifies Op::Flip is metadata-only.
10120    /// The output Storage Arc must be the SAME Arc (no copy);
10121    /// the output Layout has a negated stride at dim 0 and a
10122    /// shifted start_offset.
10123    #[test]
10124    fn pipelined_realize_flip_is_metadata_only() {
10125        // shape [3, 4]; flip dim 0 → shape [3, 4], stride [-4, 1], offset 8.
10126        let data: Vec<f32> = (1..=12).map(|x| x as f32).collect();
10127        let storage = fuel_memory::from_slice_cpu(&data);
10128        let graph = Arc::new(RwLock::new(Graph::new()));
10129        let (in_id, f_id) = {
10130            let mut g = graph.write().unwrap();
10131            let in_id = g.push(Node {
10132                op: Op::Const,
10133                inputs: vec![],
10134                shape: Shape::from_dims(&[3, 4]),
10135                dtype: DType::F32,
10136            });
10137            let f_id = g.push(Node {
10138                op: Op::Flip { dim: 0 },
10139                inputs: vec![in_id],
10140                shape: Shape::from_dims(&[3, 4]),
10141                dtype: DType::F32,
10142            });
10143            (in_id, f_id)
10144        };
10145        let mut inputs = StorageCache::new();
10146        let in_arc = Arc::new(RwLock::new(storage));
10147        inputs.insert(in_id, Arc::clone(&in_arc));
10148
10149        let (result_arc, result_layout) =
10150            PipelinedExecutor::realize(graph, f_id, inputs).expect("realize");
10151
10152        assert!(
10153            Arc::ptr_eq(&result_arc, &in_arc),
10154            "flip must share input bytes"
10155        );
10156        assert_eq!(result_layout.shape().dims(), &[3, 4]);
10157        assert_eq!(result_layout.stride(), &[-4_isize, 1]);
10158        assert_eq!(result_layout.start_offset(), 8);
10159        assert!(!result_layout.is_contiguous());
10160    }
10161
10162    /// E2E: Const + Permute(rank-3 axes [2, 0, 1]) — verifies the
10163    /// general permute path through metadata-only adoption.
10164    #[test]
10165    fn pipelined_realize_permute_is_metadata_only() {
10166        // shape [2, 3, 4]; permute axes [2, 0, 1] → shape [4, 2, 3]
10167        let data: Vec<f32> = (1..=24).map(|x| x as f32).collect();
10168        let storage = fuel_memory::from_slice_cpu(&data);
10169        let graph = Arc::new(RwLock::new(Graph::new()));
10170        let (in_id, p_id) = {
10171            let mut g = graph.write().unwrap();
10172            let in_id = g.push(Node {
10173                op: Op::Const,
10174                inputs: vec![],
10175                shape: Shape::from_dims(&[2, 3, 4]),
10176                dtype: DType::F32,
10177            });
10178            let p_id = g.push(Node {
10179                op: Op::Permute(vec![2, 0, 1]),
10180                inputs: vec![in_id],
10181                shape: Shape::from_dims(&[4, 2, 3]),
10182                dtype: DType::F32,
10183            });
10184            (in_id, p_id)
10185        };
10186        let mut inputs = StorageCache::new();
10187        let in_arc = Arc::new(RwLock::new(storage));
10188        inputs.insert(in_id, Arc::clone(&in_arc));
10189
10190        let (result_arc, result_layout) =
10191            PipelinedExecutor::realize(graph, p_id, inputs).expect("realize");
10192
10193        assert!(Arc::ptr_eq(&result_arc, &in_arc));
10194        assert_eq!(result_layout.shape().dims(), &[4, 2, 3]);
10195        // Original strides for shape [2, 3, 4] are [12, 4, 1].
10196        // After permute axes [2, 0, 1]: [strides[2], strides[0], strides[1]] = [1, 12, 4].
10197        assert_eq!(result_layout.stride(), &[1, 12, 4]);
10198    }
10199
10200    /// E2E: Const + Cast(f32→f64) — verifies cast through the
10201    /// pipelined executor. Output Storage has the target dtype;
10202    /// bytes encode the widened values.
10203    #[test]
10204    fn pipelined_realize_cast_f32_to_f64() {
10205        let storage = fuel_memory::from_slice_cpu(&[1.5_f32, -2.25, 100.0]);
10206        let graph = Arc::new(RwLock::new(Graph::new()));
10207        let (in_id, c_id) = {
10208            let mut g = graph.write().unwrap();
10209            let in_id = g.push(Node {
10210                op: Op::Const,
10211                inputs: vec![],
10212                shape: Shape::from_dims(&[3]),
10213                dtype: DType::F32,
10214            });
10215            let c_id = g.push(Node {
10216                op: Op::Cast(DType::F64),
10217                inputs: vec![in_id],
10218                shape: Shape::from_dims(&[3]),
10219                dtype: DType::F64,
10220            });
10221            g.set_target_backend(c_id, BackendId::Cpu);
10222            (in_id, c_id)
10223        };
10224        let mut inputs = StorageCache::new();
10225        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10226
10227        let (result_arc, result_layout) =
10228            PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
10229        assert_eq!(result_layout.shape().dims(), &[3]);
10230
10231        let guard = result_arc.read().unwrap();
10232        assert_eq!(guard.dtype, DType::F64);
10233        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10234            panic!("expected Cpu storage");
10235        };
10236        assert_eq!(c.as_slice::<f64>().unwrap(), &[1.5_f64, -2.25, 100.0]);
10237    }
10238
10239    /// E2E: Const + Cast(f32→bf16) + Cast(bf16→f32) — round trip
10240    /// through bf16; verifies the Cast wrapper's source-dtype
10241    /// dispatch (different sources hit different match arms).
10242    /// Inputs chosen to round-trip exactly through bf16.
10243    #[test]
10244    fn pipelined_realize_cast_round_trip_via_bf16() {
10245        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, -3.0, 0.5]);
10246        let graph = Arc::new(RwLock::new(Graph::new()));
10247        let (in_id, c1_id, c2_id) = {
10248            let mut g = graph.write().unwrap();
10249            let in_id = g.push(Node {
10250                op: Op::Const,
10251                inputs: vec![],
10252                shape: Shape::from_dims(&[4]),
10253                dtype: DType::F32,
10254            });
10255            let c1_id = g.push(Node {
10256                op: Op::Cast(DType::BF16),
10257                inputs: vec![in_id],
10258                shape: Shape::from_dims(&[4]),
10259                dtype: DType::BF16,
10260            });
10261            let c2_id = g.push(Node {
10262                op: Op::Cast(DType::F32),
10263                inputs: vec![c1_id],
10264                shape: Shape::from_dims(&[4]),
10265                dtype: DType::F32,
10266            });
10267            g.set_target_backend(c1_id, BackendId::Cpu);
10268            g.set_target_backend(c2_id, BackendId::Cpu);
10269            (in_id, c1_id, c2_id)
10270        };
10271        let _ = c1_id;
10272        let mut inputs = StorageCache::new();
10273        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10274
10275        let (result_arc, _) = PipelinedExecutor::realize(graph, c2_id, inputs).expect("realize");
10276        let guard = result_arc.read().unwrap();
10277        assert_eq!(guard.dtype, DType::F32);
10278        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10279            panic!("expected Cpu storage");
10280        };
10281        assert_eq!(c.as_slice::<f32>().unwrap(), &[1.0_f32, 2.0, -3.0, 0.5]);
10282    }
10283
10284    /// E2E: Const + Slice — slice is metadata-only; the output Arc
10285    /// shares bytes with the input, and the Layout's start_offset
10286    /// + narrowed shape reflect the slice. Stage 3 of Layout-on-Node
10287    ///
10288    /// extended to cover Op::Slice via Layout::narrow.
10289    #[test]
10290    fn pipelined_realize_slice_is_metadata_only() {
10291        // shape [5]; slice dim 0 from index 1 with len 3 → shape [3]
10292        // Source: [10, 20, 30, 40, 50]; slice → [20, 30, 40]
10293        let storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0]);
10294        let graph = Arc::new(RwLock::new(Graph::new()));
10295        let (in_id, s_id) = {
10296            let mut g = graph.write().unwrap();
10297            let in_id = g.push(Node {
10298                op: Op::Const,
10299                inputs: vec![],
10300                shape: Shape::from_dims(&[5]),
10301                dtype: DType::F32,
10302            });
10303            let s_id = g.push(Node {
10304                op: Op::Slice {
10305                    dim: 0,
10306                    start: 1,
10307                    len: 3,
10308                },
10309                inputs: vec![in_id],
10310                shape: Shape::from_dims(&[3]),
10311                dtype: DType::F32,
10312            });
10313            (in_id, s_id)
10314        };
10315        let mut inputs = StorageCache::new();
10316        let in_arc = Arc::new(RwLock::new(storage));
10317        inputs.insert(in_id, Arc::clone(&in_arc));
10318
10319        let (result_arc, result_layout) =
10320            PipelinedExecutor::realize(graph, s_id, inputs).expect("realize");
10321
10322        // Bytes shared with the input.
10323        assert!(Arc::ptr_eq(&result_arc, &in_arc));
10324        assert_eq!(result_layout.shape().dims(), &[3]);
10325        // Slice into a contiguous source: the resulting layout has
10326        // start_offset = original_stride[0] * start = 1 * 1 = 1,
10327        // and stride [1] (still contiguous within the narrowed dim).
10328        assert_eq!(result_layout.start_offset(), 1);
10329        assert_eq!(result_layout.stride(), &[1]);
10330    }
10331
10332    /// E2E: Const + Slice + SumAll — slice is metadata-only, but
10333    /// sum needs contiguous bytes, so auto-Contiguize materializes
10334    /// the slice before reduce. Tests the stage 3+4 integration
10335    /// through Op::Slice. Sum of `[20, 30, 40]` is 90.
10336    #[test]
10337    fn pipelined_realize_slice_then_sum_all() {
10338        let storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0]);
10339        let graph = Arc::new(RwLock::new(Graph::new()));
10340        let (in_id, s_id, sum_id) = {
10341            let mut g = graph.write().unwrap();
10342            let in_id = g.push(Node {
10343                op: Op::Const,
10344                inputs: vec![],
10345                shape: Shape::from_dims(&[5]),
10346                dtype: DType::F32,
10347            });
10348            let s_id = g.push(Node {
10349                op: Op::Slice {
10350                    dim: 0,
10351                    start: 1,
10352                    len: 3,
10353                },
10354                inputs: vec![in_id],
10355                shape: Shape::from_dims(&[3]),
10356                dtype: DType::F32,
10357            });
10358            let sum_id = g.push(Node {
10359                op: Op::SumAll,
10360                inputs: vec![s_id],
10361                shape: Shape::from_dims(&[]),
10362                dtype: DType::F32,
10363            });
10364            g.set_target_backend(sum_id, BackendId::Cpu);
10365            (in_id, s_id, sum_id)
10366        };
10367        let _ = s_id;
10368        let mut inputs = StorageCache::new();
10369        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10370
10371        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
10372        let guard = result_arc.read().unwrap();
10373        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10374            panic!("expected Cpu storage");
10375        };
10376        assert_eq!(c.as_slice::<f32>().unwrap(), &[90.0]);
10377    }
10378
10379    /// E2E: Const + Flip + ReluElementwise — Flip is metadata-only,
10380    /// then a kernel that doesn't yet handle negative strides forces
10381    /// auto-Contiguize to materialize through StridedIndex (which
10382    /// handles signed strides natively). Verifies the post-flip
10383    /// data ordering ([4, 3, 2, 1]) is correctly seen by the kernel.
10384    #[test]
10385    fn pipelined_realize_flip_then_relu_materializes_in_reverse() {
10386        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
10387        let graph = Arc::new(RwLock::new(Graph::new()));
10388        let (in_id, _f_id, r_id) = {
10389            let mut g = graph.write().unwrap();
10390            let in_id = g.push(Node {
10391                op: Op::Const,
10392                inputs: vec![],
10393                shape: Shape::from_dims(&[4]),
10394                dtype: DType::F32,
10395            });
10396            let f_id = g.push(Node {
10397                op: Op::Flip { dim: 0 },
10398                inputs: vec![in_id],
10399                shape: Shape::from_dims(&[4]),
10400                dtype: DType::F32,
10401            });
10402            let r_id = g.push(Node {
10403                op: Op::Relu,
10404                inputs: vec![f_id],
10405                shape: Shape::from_dims(&[4]),
10406                dtype: DType::F32,
10407            });
10408            g.set_target_backend(r_id, BackendId::Cpu);
10409            (in_id, f_id, r_id)
10410        };
10411        let mut inputs = StorageCache::new();
10412        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10413
10414        let (result_arc, result_layout) =
10415            PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
10416        let guard = result_arc.read().unwrap();
10417        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10418            panic!("expected Cpu storage");
10419        };
10420        assert_eq!(c.as_slice::<f32>().unwrap(), &[4.0, 3.0, 2.0, 1.0]);
10421        assert_eq!(result_layout.shape().dims(), &[4]);
10422        assert!(result_layout.is_contiguous(), "relu output is contiguous");
10423    }
10424
10425    /// E2E: Const + BroadcastTo — verifies that broadcast layouts
10426    /// have stride 0 on the broadcast dim while sharing the input's
10427    /// bytes. Stage 3 of Layout-on-Node.
10428    #[test]
10429    fn pipelined_realize_broadcast_is_metadata_only() {
10430        // shape [3]; broadcast to [4, 3] — leading dim is 0-stride
10431        let storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
10432        let graph = Arc::new(RwLock::new(Graph::new()));
10433        let (in_id, b_id) = {
10434            let mut g = graph.write().unwrap();
10435            let in_id = g.push(Node {
10436                op: Op::Const,
10437                inputs: vec![],
10438                shape: Shape::from_dims(&[3]),
10439                dtype: DType::F32,
10440            });
10441            let b_id = g.push(Node {
10442                op: Op::BroadcastTo(Shape::from_dims(&[4, 3])),
10443                inputs: vec![in_id],
10444                shape: Shape::from_dims(&[4, 3]),
10445                dtype: DType::F32,
10446            });
10447            (in_id, b_id)
10448        };
10449        let mut inputs = StorageCache::new();
10450        let in_arc = Arc::new(RwLock::new(storage));
10451        inputs.insert(in_id, Arc::clone(&in_arc));
10452
10453        let (result_arc, result_layout) =
10454            PipelinedExecutor::realize(graph, b_id, inputs).expect("realize");
10455
10456        assert!(Arc::ptr_eq(&result_arc, &in_arc));
10457        assert_eq!(result_layout.shape().dims(), &[4, 3]);
10458        // Broadcasted leading dim has stride 0.
10459        assert_eq!(result_layout.stride(), &[0, 1]);
10460    }
10461
10462    /// E2E: Const + Const + MatMul — exercises rank-2 matmul
10463    /// through the pipelined executor. Inputs are contiguous (no
10464    /// auto-Contiguize needed); the kernel walks them via the
10465    /// (m, n, k) carried in OpParams::Matmul.
10466    #[test]
10467    fn pipelined_realize_matmul_2x3_times_3x2() {
10468        // [[1, 2, 3], [4, 5, 6]] @ [[7, 8], [9, 10], [11, 12]]
10469        //   = [[58, 64], [139, 154]]
10470        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
10471        let rhs_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0, 9.0, 10.0, 11.0, 12.0]);
10472
10473        let graph = Arc::new(RwLock::new(Graph::new()));
10474        let (lhs_id, rhs_id, mm_id) = {
10475            let mut g = graph.write().unwrap();
10476            let lhs = g.push(Node {
10477                op: Op::Const,
10478                inputs: vec![],
10479                shape: Shape::from_dims(&[2, 3]),
10480                dtype: DType::F32,
10481            });
10482            let rhs = g.push(Node {
10483                op: Op::Const,
10484                inputs: vec![],
10485                shape: Shape::from_dims(&[3, 2]),
10486                dtype: DType::F32,
10487            });
10488            let mm = g.push(Node {
10489                op: Op::MatMul,
10490                inputs: vec![lhs, rhs],
10491                shape: Shape::from_dims(&[2, 2]),
10492                dtype: DType::F32,
10493            });
10494            g.set_target_backend(mm, BackendId::Cpu);
10495            (lhs, rhs, mm)
10496        };
10497        let mut inputs = StorageCache::new();
10498        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
10499        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
10500
10501        let (result_arc, result_layout) =
10502            PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
10503        assert_eq!(result_layout.shape().dims(), &[2, 2]);
10504        assert!(result_layout.is_contiguous());
10505
10506        let guard = result_arc.read().unwrap();
10507        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10508            panic!("expected Cpu storage");
10509        };
10510        assert_eq!(c.as_slice::<f32>().unwrap(), &[58.0, 64.0, 139.0, 154.0]);
10511    }
10512
10513    /// E2E: batched matmul through the pipelined executor. Two
10514    /// batches of [2, 2] @ [2, 2]; the kernel iterates over
10515    /// `batch_count` and produces concatenated outputs.
10516    #[test]
10517    fn pipelined_realize_matmul_batched_2x_2x2_times_2x2() {
10518        let lhs_storage = fuel_memory::from_slice_cpu(&[
10519            1.0_f32, 2.0, 3.0, 4.0, // batch 0
10520            1.0, 0.0, 0.0, 1.0, // batch 1 (identity)
10521        ]);
10522        let rhs_storage = fuel_memory::from_slice_cpu(&[
10523            5.0_f32, 6.0, 7.0, 8.0, // batch 0
10524            10.0, 20.0, 30.0, 40.0, // batch 1
10525        ]);
10526
10527        let graph = Arc::new(RwLock::new(Graph::new()));
10528        let (lhs_id, rhs_id, mm_id) = {
10529            let mut g = graph.write().unwrap();
10530            let lhs = g.push(Node {
10531                op: Op::Const,
10532                inputs: vec![],
10533                shape: Shape::from_dims(&[2, 2, 2]),
10534                dtype: DType::F32,
10535            });
10536            let rhs = g.push(Node {
10537                op: Op::Const,
10538                inputs: vec![],
10539                shape: Shape::from_dims(&[2, 2, 2]),
10540                dtype: DType::F32,
10541            });
10542            let mm = g.push(Node {
10543                op: Op::MatMul,
10544                inputs: vec![lhs, rhs],
10545                shape: Shape::from_dims(&[2, 2, 2]),
10546                dtype: DType::F32,
10547            });
10548            g.set_target_backend(mm, BackendId::Cpu);
10549            (lhs, rhs, mm)
10550        };
10551        let mut inputs = StorageCache::new();
10552        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
10553        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
10554
10555        let (result_arc, result_layout) =
10556            PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
10557        assert_eq!(result_layout.shape().dims(), &[2, 2, 2]);
10558        assert!(result_layout.is_contiguous());
10559
10560        let guard = result_arc.read().unwrap();
10561        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10562            panic!("expected Cpu storage");
10563        };
10564        // batch 0: [[1,2],[3,4]] @ [[5,6],[7,8]] = [[19,22],[43,50]]
10565        // batch 1: identity @ [[10,20],[30,40]]   = [[10,20],[30,40]]
10566        assert_eq!(
10567            c.as_slice::<f32>().unwrap(),
10568            &[19.0, 22.0, 43.0, 50.0, 10.0, 20.0, 30.0, 40.0]
10569        );
10570    }
10571
10572    /// E2E: F64 elementwise add through the pipelined executor.
10573    /// Verifies that capability-driven dispatch correctly routes
10574    /// (AddElementwise, F64) to the f64 wrapper/kernel.
10575    #[test]
10576    fn pipelined_realize_add_f64() {
10577        let lhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0]);
10578        let rhs = fuel_memory::from_slice_cpu(&[10.0_f64, 20.0, 30.0]);
10579        let graph = Arc::new(RwLock::new(Graph::new()));
10580        let (l_id, r_id, op_id) = {
10581            let mut g = graph.write().unwrap();
10582            let l = g.push(Node {
10583                op: Op::Const,
10584                inputs: vec![],
10585                shape: Shape::from_dims(&[3]),
10586                dtype: DType::F64,
10587            });
10588            let r = g.push(Node {
10589                op: Op::Const,
10590                inputs: vec![],
10591                shape: Shape::from_dims(&[3]),
10592                dtype: DType::F64,
10593            });
10594            let op = g.push(Node {
10595                op: Op::Add,
10596                inputs: vec![l, r],
10597                shape: Shape::from_dims(&[3]),
10598                dtype: DType::F64,
10599            });
10600            g.set_target_backend(op, BackendId::Cpu);
10601            (l, r, op)
10602        };
10603        let mut inputs = StorageCache::new();
10604        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10605        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10606        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
10607        let guard = result_arc.read().unwrap();
10608        assert_eq!(guard.dtype, DType::F64);
10609        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10610            panic!("expected Cpu storage");
10611        };
10612        assert_eq!(c.as_slice::<f64>().unwrap(), &[11.0_f64, 22.0, 33.0]);
10613    }
10614
10615    /// E2E: Op::Equal F32 → Bool mask through the pipelined executor (GAP-168c).
10616    /// Verifies (a) the binding-table key `(EqualElementwise, [F32, F32, U8],
10617    /// Cpu)` resolves, (b) the executor allocates a U8-sized output
10618    /// buffer (1 byte per element, not 4), (c) the kernel writes the
10619    /// expected mask bits including IEEE-754 NaN handling
10620    /// (`NaN == NaN` is false).
10621    #[test]
10622    fn pipelined_realize_eq_f32_to_bool_mask() {
10623        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, f32::NAN, 0.0]);
10624        let rhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -0.0]);
10625        let graph = Arc::new(RwLock::new(Graph::new()));
10626        let (l_id, r_id, eq_id) = {
10627            let mut g = graph.write().unwrap();
10628            let l = g.push(Node {
10629                op: Op::Const,
10630                inputs: vec![],
10631                shape: Shape::from_dims(&[5]),
10632                dtype: DType::F32,
10633            });
10634            let r = g.push(Node {
10635                op: Op::Const,
10636                inputs: vec![],
10637                shape: Shape::from_dims(&[5]),
10638                dtype: DType::F32,
10639            });
10640            let eq = g.push(Node {
10641                op: Op::Equal,
10642                inputs: vec![l, r],
10643                shape: Shape::from_dims(&[5]),
10644                dtype: DType::Bool,
10645            });
10646            g.set_target_backend(eq, BackendId::Cpu);
10647            (l, r, eq)
10648        };
10649        let mut inputs = StorageCache::new();
10650        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10651        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10652        let (result_arc, _) = PipelinedExecutor::realize(graph, eq_id, inputs).expect("realize");
10653        let guard = result_arc.read().unwrap();
10654        assert_eq!(guard.dtype, DType::Bool);
10655        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10656            panic!("expected Cpu storage");
10657        };
10658        let mask: &[u8] = c.as_slice().expect("u8 view");
10659        // Index 0: 1.0 == 1.0 → 1.
10660        // Index 1: 2.0 != 5.0 → 0.
10661        // Index 2: 3.0 == 3.0 → 1.
10662        // Index 3: NaN == NaN → 0 (IEEE-754).
10663        // Index 4: 0.0 == -0.0 → 1 (IEEE-754 zero equality).
10664        assert_eq!(mask, &[1, 0, 1, 0, 1]);
10665    }
10666
10667    /// E2E: Op::Ne F32 → Bool mask. Mirrors the Eq F32 test with
10668    /// inverted predicate; NaN-vs-NaN slot now yields `1` (since
10669    /// `NaN != NaN` per IEEE-754).
10670    #[test]
10671    fn pipelined_realize_ne_f32_to_bool_mask() {
10672        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, f32::NAN, 0.0]);
10673        let rhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -0.0]);
10674        let graph = Arc::new(RwLock::new(Graph::new()));
10675        let (l_id, r_id, ne_id) = {
10676            let mut g = graph.write().unwrap();
10677            let l = g.push(Node {
10678                op: Op::Const,
10679                inputs: vec![],
10680                shape: Shape::from_dims(&[5]),
10681                dtype: DType::F32,
10682            });
10683            let r = g.push(Node {
10684                op: Op::Const,
10685                inputs: vec![],
10686                shape: Shape::from_dims(&[5]),
10687                dtype: DType::F32,
10688            });
10689            let ne = g.push(Node {
10690                op: Op::Ne,
10691                inputs: vec![l, r],
10692                shape: Shape::from_dims(&[5]),
10693                dtype: DType::Bool,
10694            });
10695            g.set_target_backend(ne, BackendId::Cpu);
10696            (l, r, ne)
10697        };
10698        let mut inputs = StorageCache::new();
10699        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10700        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10701        let (result_arc, _) = PipelinedExecutor::realize(graph, ne_id, inputs).expect("realize");
10702        let guard = result_arc.read().unwrap();
10703        assert_eq!(guard.dtype, DType::Bool);
10704        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10705            panic!("expected Cpu storage");
10706        };
10707        let mask: &[u8] = c.as_slice().expect("u8 view");
10708        // Inverse of the Eq test:
10709        // 1.0 != 1.0 → 0;  2.0 != 5.0 → 1;  3.0 != 3.0 → 0;
10710        // NaN != NaN → 1 (IEEE-754);  0.0 != -0.0 → 0 (IEEE-754).
10711        assert_eq!(mask, &[0, 1, 0, 1, 0]);
10712    }
10713
10714    /// E2E: Op::Lt F32 → Bool mask. Confirms strict-less-than semantics
10715    /// + IEEE-754 NaN handling (any comparison with NaN is unordered →
10716    ///
10717    /// `0`).
10718    #[test]
10719    fn pipelined_realize_lt_f32_to_bool_mask() {
10720        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -1.0]);
10721        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 3.0, 0.0, 0.0]);
10722        let graph = Arc::new(RwLock::new(Graph::new()));
10723        let (l_id, r_id, lt_id) = {
10724            let mut g = graph.write().unwrap();
10725            let l = g.push(Node {
10726                op: Op::Const,
10727                inputs: vec![],
10728                shape: Shape::from_dims(&[5]),
10729                dtype: DType::F32,
10730            });
10731            let r = g.push(Node {
10732                op: Op::Const,
10733                inputs: vec![],
10734                shape: Shape::from_dims(&[5]),
10735                dtype: DType::F32,
10736            });
10737            let lt = g.push(Node {
10738                op: Op::Lt,
10739                inputs: vec![l, r],
10740                shape: Shape::from_dims(&[5]),
10741                dtype: DType::Bool,
10742            });
10743            g.set_target_backend(lt, BackendId::Cpu);
10744            (l, r, lt)
10745        };
10746        let mut inputs = StorageCache::new();
10747        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10748        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10749        let (result_arc, _) = PipelinedExecutor::realize(graph, lt_id, inputs).expect("realize");
10750        let guard = result_arc.read().unwrap();
10751        assert_eq!(guard.dtype, DType::Bool);
10752        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10753            panic!("expected Cpu storage");
10754        };
10755        let mask: &[u8] = c.as_slice().expect("u8 view");
10756        // 1.0 < 2.0 → 1;  5.0 < 5.0 → 0 (strict);  3.0 < 3.0 → 0;
10757        // NaN < 0.0 → 0 (unordered);  -1.0 < 0.0 → 1.
10758        assert_eq!(mask, &[1, 0, 0, 0, 1]);
10759    }
10760
10761    /// E2E: Op::Le F32 → Bool mask. Distinct from Lt at the equal slot
10762    /// (`5.0 <= 5.0` = 1, vs Lt's `5.0 < 5.0` = 0). NaN unordered → 0.
10763    #[test]
10764    fn pipelined_realize_le_f32_to_bool_mask() {
10765        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -1.0]);
10766        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 2.0, 0.0, 0.0]);
10767        let graph = Arc::new(RwLock::new(Graph::new()));
10768        let (l_id, r_id, le_id) = {
10769            let mut g = graph.write().unwrap();
10770            let l = g.push(Node {
10771                op: Op::Const,
10772                inputs: vec![],
10773                shape: Shape::from_dims(&[5]),
10774                dtype: DType::F32,
10775            });
10776            let r = g.push(Node {
10777                op: Op::Const,
10778                inputs: vec![],
10779                shape: Shape::from_dims(&[5]),
10780                dtype: DType::F32,
10781            });
10782            let le = g.push(Node {
10783                op: Op::Le,
10784                inputs: vec![l, r],
10785                shape: Shape::from_dims(&[5]),
10786                dtype: DType::Bool,
10787            });
10788            g.set_target_backend(le, BackendId::Cpu);
10789            (l, r, le)
10790        };
10791        let mut inputs = StorageCache::new();
10792        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10793        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10794        let (result_arc, _) = PipelinedExecutor::realize(graph, le_id, inputs).expect("realize");
10795        let guard = result_arc.read().unwrap();
10796        assert_eq!(guard.dtype, DType::Bool);
10797        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10798            panic!("expected Cpu storage");
10799        };
10800        let mask: &[u8] = c.as_slice().expect("u8 view");
10801        // 1.0 <= 2.0 → 1;  5.0 <= 5.0 → 1 (key Lt difference);
10802        // 3.0 <= 2.0 → 0;  NaN <= 0.0 → 0 (unordered);  -1.0 <= 0.0 → 1.
10803        assert_eq!(mask, &[1, 1, 0, 0, 1]);
10804    }
10805
10806    /// E2E: Op::Gt F32 → Bool mask. Strict-greater: equality slot is
10807    /// `0`. NaN unordered → `0`.
10808    #[test]
10809    fn pipelined_realize_gt_f32_to_bool_mask() {
10810        let lhs = fuel_memory::from_slice_cpu(&[3.0_f32, 5.0, 2.0, f32::NAN, 1.0]);
10811        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 3.0, 0.0, 0.0]);
10812        let graph = Arc::new(RwLock::new(Graph::new()));
10813        let (l_id, r_id, gt_id) = {
10814            let mut g = graph.write().unwrap();
10815            let l = g.push(Node {
10816                op: Op::Const,
10817                inputs: vec![],
10818                shape: Shape::from_dims(&[5]),
10819                dtype: DType::F32,
10820            });
10821            let r = g.push(Node {
10822                op: Op::Const,
10823                inputs: vec![],
10824                shape: Shape::from_dims(&[5]),
10825                dtype: DType::F32,
10826            });
10827            let gt = g.push(Node {
10828                op: Op::Gt,
10829                inputs: vec![l, r],
10830                shape: Shape::from_dims(&[5]),
10831                dtype: DType::Bool,
10832            });
10833            g.set_target_backend(gt, BackendId::Cpu);
10834            (l, r, gt)
10835        };
10836        let mut inputs = StorageCache::new();
10837        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10838        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10839        let (result_arc, _) = PipelinedExecutor::realize(graph, gt_id, inputs).expect("realize");
10840        let guard = result_arc.read().unwrap();
10841        assert_eq!(guard.dtype, DType::Bool);
10842        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10843            panic!("expected Cpu storage");
10844        };
10845        let mask: &[u8] = c.as_slice().expect("u8 view");
10846        // 3.0 > 2.0 → 1;  5.0 > 5.0 → 0 (strict);  2.0 > 3.0 → 0;
10847        // NaN > 0.0 → 0 (unordered);  1.0 > 0.0 → 1.
10848        assert_eq!(mask, &[1, 0, 0, 0, 1]);
10849    }
10850
10851    /// E2E: Op::Ge F32 → Bool mask. Greater-or-equal: equality slot
10852    /// is `1` (distinguishes from Gt). NaN unordered → `0`. Closes
10853    /// the comparison family with full `[Eq, Ne, Lt, Le, Gt, Ge]`
10854    /// coverage.
10855    #[test]
10856    fn pipelined_realize_ge_f32_to_bool_mask() {
10857        let lhs = fuel_memory::from_slice_cpu(&[3.0_f32, 5.0, 2.0, f32::NAN, 0.0]);
10858        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 3.0, 0.0, 0.0]);
10859        let graph = Arc::new(RwLock::new(Graph::new()));
10860        let (l_id, r_id, ge_id) = {
10861            let mut g = graph.write().unwrap();
10862            let l = g.push(Node {
10863                op: Op::Const,
10864                inputs: vec![],
10865                shape: Shape::from_dims(&[5]),
10866                dtype: DType::F32,
10867            });
10868            let r = g.push(Node {
10869                op: Op::Const,
10870                inputs: vec![],
10871                shape: Shape::from_dims(&[5]),
10872                dtype: DType::F32,
10873            });
10874            let ge = g.push(Node {
10875                op: Op::Ge,
10876                inputs: vec![l, r],
10877                shape: Shape::from_dims(&[5]),
10878                dtype: DType::Bool,
10879            });
10880            g.set_target_backend(ge, BackendId::Cpu);
10881            (l, r, ge)
10882        };
10883        let mut inputs = StorageCache::new();
10884        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10885        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10886        let (result_arc, _) = PipelinedExecutor::realize(graph, ge_id, inputs).expect("realize");
10887        let guard = result_arc.read().unwrap();
10888        assert_eq!(guard.dtype, DType::Bool);
10889        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10890            panic!("expected Cpu storage");
10891        };
10892        let mask: &[u8] = c.as_slice().expect("u8 view");
10893        // 3.0 >= 2.0 → 1;  5.0 >= 5.0 → 1 (key Gt difference);
10894        // 2.0 >= 3.0 → 0;  NaN >= 0.0 → 0 (unordered);  0.0 >= 0.0 → 1.
10895        assert_eq!(mask, &[1, 1, 0, 0, 1]);
10896    }
10897
10898    /// E2E: Op::Equal F64 → Bool mask. Confirms the F64 wrapper is
10899    /// independently registered and routed (binding-table key
10900    /// `(EqualElementwise, [F64, F64, U8], Cpu)`).
10901    #[test]
10902    fn pipelined_realize_eq_f64_to_bool_mask() {
10903        let lhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0]);
10904        let rhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 4.0]);
10905        let graph = Arc::new(RwLock::new(Graph::new()));
10906        let (l_id, r_id, eq_id) = {
10907            let mut g = graph.write().unwrap();
10908            let l = g.push(Node {
10909                op: Op::Const,
10910                inputs: vec![],
10911                shape: Shape::from_dims(&[3]),
10912                dtype: DType::F64,
10913            });
10914            let r = g.push(Node {
10915                op: Op::Const,
10916                inputs: vec![],
10917                shape: Shape::from_dims(&[3]),
10918                dtype: DType::F64,
10919            });
10920            let eq = g.push(Node {
10921                op: Op::Equal,
10922                inputs: vec![l, r],
10923                shape: Shape::from_dims(&[3]),
10924                dtype: DType::Bool,
10925            });
10926            g.set_target_backend(eq, BackendId::Cpu);
10927            (l, r, eq)
10928        };
10929        let mut inputs = StorageCache::new();
10930        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10931        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10932        let (result_arc, _) = PipelinedExecutor::realize(graph, eq_id, inputs).expect("realize");
10933        let guard = result_arc.read().unwrap();
10934        assert_eq!(guard.dtype, DType::Bool);
10935        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10936            panic!("expected Cpu storage");
10937        };
10938        let mask: &[u8] = c.as_slice().expect("u8 view");
10939        assert_eq!(mask, &[1, 1, 0]);
10940    }
10941
10942    /// E2E: Op::Where ternary select — `out[i] = if cond[i] != 0 { a[i] } else { b[i] }`.
10943    /// Validates (a) the binding-table key `(Where, [Bool, F32, F32, F32], Cpu)`
10944    /// resolves to the where_f32 wrapper, (b) the Bool cond input drives
10945    /// the per-slot pick, (c) outputs preserve the input dtype.
10946    ///
10947    /// GAP-168(c): the cond STORAGE is tagged Bool, not merely the graph node.
10948    /// Bool and U8 are byte-identical, so leaving the storage U8 under a Bool
10949    /// node is exactly the mismatch this cut exists to make visible.
10950    #[test]
10951    fn pipelined_realize_where_f32_picks_per_slot_from_bool_mask() {
10952        // cond = [1, 0, 1, 0, 1]; a = [1, 2, 3, 4, 5]; b = [10, 20, 30, 40, 50]
10953        // expected = [1, 20, 3, 40, 5]
10954        let mut cond_storage = fuel_memory::from_slice_cpu(&[1u8, 0, 1, 0, 1]);
10955        cond_storage.dtype = DType::Bool; // GAP-168(c): a Bool mask, not U8 bytes
10956        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0]);
10957        let b_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0]);
10958        let graph = Arc::new(RwLock::new(Graph::new()));
10959        let (cond_id, a_id, b_id, where_id) = {
10960            let mut g = graph.write().unwrap();
10961            let cond = g.push(Node {
10962                op: Op::Const,
10963                inputs: vec![],
10964                shape: Shape::from_dims(&[5]),
10965                dtype: DType::Bool,
10966            });
10967            let a = g.push(Node {
10968                op: Op::Const,
10969                inputs: vec![],
10970                shape: Shape::from_dims(&[5]),
10971                dtype: DType::F32,
10972            });
10973            let b = g.push(Node {
10974                op: Op::Const,
10975                inputs: vec![],
10976                shape: Shape::from_dims(&[5]),
10977                dtype: DType::F32,
10978            });
10979            let w = g.push(Node {
10980                op: Op::Where,
10981                inputs: vec![cond, a, b],
10982                shape: Shape::from_dims(&[5]),
10983                dtype: DType::F32,
10984            });
10985            g.set_target_backend(w, BackendId::Cpu);
10986            (cond, a, b, w)
10987        };
10988        let mut inputs = StorageCache::new();
10989        inputs.insert(cond_id, Arc::new(RwLock::new(cond_storage)));
10990        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
10991        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
10992        let (result_arc, _) = PipelinedExecutor::realize(graph, where_id, inputs).expect("realize");
10993        let guard = result_arc.read().unwrap();
10994        assert_eq!(guard.dtype, DType::F32);
10995        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10996            panic!("expected Cpu storage");
10997        };
10998        let out: &[f32] = c.as_slice().expect("f32 view");
10999        assert_eq!(out, &[1.0, 20.0, 3.0, 40.0, 5.0]);
11000    }
11001
11002    /// E2E: full chain `eq → where`. Compares two f32 vectors, then
11003    /// uses the resulting Bool mask to pick from a third tensor (or a
11004    /// fallback). Validates the comparison-family + Where ops compose
11005    /// end-to-end.
11006    #[test]
11007    fn pipelined_realize_eq_then_where_full_chain() {
11008        // a = [1, 2, 3]; b = [1, 5, 3] → eq = [1, 0, 1]
11009        // pick = [10, 20, 30]; fallback = [99, 99, 99]
11010        // result = [10, 99, 30]
11011        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
11012        let b_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0]);
11013        let pick_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
11014        let fb_storage = fuel_memory::from_slice_cpu(&[99.0_f32, 99.0, 99.0]);
11015        let graph = Arc::new(RwLock::new(Graph::new()));
11016        let (a_id, b_id, pick_id, fb_id, where_id) = {
11017            let mut g = graph.write().unwrap();
11018            let a = g.push(Node {
11019                op: Op::Const,
11020                inputs: vec![],
11021                shape: Shape::from_dims(&[3]),
11022                dtype: DType::F32,
11023            });
11024            let b = g.push(Node {
11025                op: Op::Const,
11026                inputs: vec![],
11027                shape: Shape::from_dims(&[3]),
11028                dtype: DType::F32,
11029            });
11030            let pick = g.push(Node {
11031                op: Op::Const,
11032                inputs: vec![],
11033                shape: Shape::from_dims(&[3]),
11034                dtype: DType::F32,
11035            });
11036            let fb = g.push(Node {
11037                op: Op::Const,
11038                inputs: vec![],
11039                shape: Shape::from_dims(&[3]),
11040                dtype: DType::F32,
11041            });
11042            let eq = g.push(Node {
11043                op: Op::Equal,
11044                inputs: vec![a, b],
11045                shape: Shape::from_dims(&[3]),
11046                dtype: DType::Bool,
11047            });
11048            let w = g.push(Node {
11049                op: Op::Where,
11050                inputs: vec![eq, pick, fb],
11051                shape: Shape::from_dims(&[3]),
11052                dtype: DType::F32,
11053            });
11054            g.set_target_backend(eq, BackendId::Cpu);
11055            g.set_target_backend(w, BackendId::Cpu);
11056            (a, b, pick, fb, w)
11057        };
11058        let mut inputs = StorageCache::new();
11059        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
11060        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
11061        inputs.insert(pick_id, Arc::new(RwLock::new(pick_storage)));
11062        inputs.insert(fb_id, Arc::new(RwLock::new(fb_storage)));
11063        let (result_arc, _) = PipelinedExecutor::realize(graph, where_id, inputs).expect("realize");
11064        let guard = result_arc.read().unwrap();
11065        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11066            panic!("expected Cpu storage");
11067        };
11068        let out: &[f32] = c.as_slice().expect("f32 view");
11069        assert_eq!(out, &[10.0, 99.0, 30.0]);
11070    }
11071
11072    /// E2E: Q4_0 QMatMul through the pipelined executor — proves
11073    /// quantized weights can flow into the unified path. Activations
11074    /// are F32, weights are U32-typed (raw block bytes).
11075    /// Construct a Q4_0 weight tensor where every weight = 1.0
11076    /// (d=1.0, every nibble=9 → 1*(9-8)=1), so A @ W^T computes
11077    /// the per-row sum of activations.
11078    #[test]
11079    fn pipelined_realize_qmatmul_q4_0_unit_weight_sums_activations() {
11080        use fuel_graph::QuantType;
11081        use half::f16;
11082        let block_size = std::mem::size_of::<fuel_quantized::BlockQ4_0>();
11083        let mut w_bytes = vec![0u8; 2 * block_size];
11084        for block_idx in 0..2 {
11085            let off = block_idx * block_size;
11086            let d_bytes = f16::from_f32(1.0).to_le_bytes();
11087            w_bytes[off..off + 2].copy_from_slice(&d_bytes);
11088            for i in 0..16 {
11089                w_bytes[off + 2 + i] = 0x99;
11090            }
11091        }
11092        // Weight tensor is U32-typed (rank-1, length = bytes/4)
11093        let w_storage = fuel_memory::Storage::new(
11094            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
11095                &w_bytes,
11096            )),
11097            DType::U32,
11098        );
11099
11100        let act_vec: Vec<f32> = (1..=32).map(|x| x as f32).collect();
11101        let act_storage = fuel_memory::from_slice_cpu(&act_vec);
11102
11103        let graph = Arc::new(RwLock::new(Graph::new()));
11104        let (act_id, w_id, mm_id) = {
11105            let mut g = graph.write().unwrap();
11106            let act = g.push(Node {
11107                op: Op::Const,
11108                inputs: vec![],
11109                shape: Shape::from_dims(&[1, 32]),
11110                dtype: DType::F32,
11111            });
11112            let w = g.push(Node {
11113                op: Op::Const,
11114                inputs: vec![],
11115                shape: Shape::from_dims(&[w_bytes.len() / 4]),
11116                dtype: DType::U32,
11117            });
11118            let mm = g.push(Node {
11119                op: Op::Fused(
11120                    fuel_graph::registry::FusedOps::QMATMUL,
11121                    fuel_graph::registry::FusedOpParams::QMatMul {
11122                        quant_type: QuantType::Q4_0,
11123                        k: 32,
11124                        n: 2,
11125                    },
11126                ),
11127                inputs: vec![act, w],
11128                shape: Shape::from_dims(&[1, 2]),
11129                dtype: DType::F32,
11130            });
11131            g.set_target_backend(mm, BackendId::Cpu);
11132            (act, w, mm)
11133        };
11134        let mut inputs = StorageCache::new();
11135        inputs.insert(act_id, Arc::new(RwLock::new(act_storage)));
11136        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
11137        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11138        let guard = result_arc.read().unwrap();
11139        assert_eq!(guard.dtype, DType::F32);
11140        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11141            panic!("expected Cpu storage");
11142        };
11143        let r: &[f32] = c.as_slice().unwrap();
11144        // Both rows = sum(1..=32) = 528, within Q8_1 round-trip
11145        // tolerance.
11146        assert!((r[0] - 528.0).abs() < 0.5, "got {}, want 528", r[0]);
11147        assert!((r[1] - 528.0).abs() < 0.5, "got {}, want 528", r[1]);
11148    }
11149
11150    /// E2E: QMatMul with Q5_0 weights — verifies the new quant
11151    /// dispatch arm picks `qmatmul_q5_0_f32`. We build weights by
11152    /// quantizing all-ones via `BlockQ5_0::from_float`, then
11153    /// compare pipelined output against the direct fuel_quantized
11154    /// matmul on the same blocks.
11155    #[test]
11156    fn pipelined_realize_qmatmul_q5_0_against_reference() {
11157        use fuel_graph::QuantType;
11158        use fuel_quantized::{BlockQ5_0, GgmlType};
11159        let n = 2;
11160        let k = 64; // 2 blocks per row (Q5_0 vec_dot pairs blocks)
11161        // Quantize an all-ones [n, k] weight matrix.
11162        let w_f32 = vec![1.0_f32; n * k];
11163        let blocks_per_row = k / BlockQ5_0::BLCK_SIZE;
11164        let mut w_blocks = vec![BlockQ5_0::zeros(); n * blocks_per_row];
11165        BlockQ5_0::from_float(&w_f32, &mut w_blocks);
11166        // Reinterpret block slice as bytes (BlockQ5_0 is #[repr(C)]).
11167        let bytes_per_block = std::mem::size_of::<BlockQ5_0>();
11168        let w_bytes: Vec<u8> = unsafe {
11169            std::slice::from_raw_parts(
11170                w_blocks.as_ptr() as *const u8,
11171                w_blocks.len() * bytes_per_block,
11172            )
11173        }
11174        .to_vec();
11175        let w_storage = fuel_memory::Storage::new(
11176            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
11177                &w_bytes,
11178            )),
11179            DType::U32,
11180        );
11181        let act_vec: Vec<f32> = (1..=k).map(|x| x as f32).collect();
11182        let act_storage = fuel_memory::from_slice_cpu(&act_vec);
11183        // Reference: direct matmul through fuel_quantized.
11184        let mut ref_out = vec![0.0_f32; n];
11185        fuel_quantized::matmul::<BlockQ5_0>((1, k, n), &act_vec, &w_blocks, &mut ref_out)
11186            .expect("ref matmul");
11187
11188        let graph = Arc::new(RwLock::new(Graph::new()));
11189        let (act_id, w_id, mm_id) = {
11190            let mut g = graph.write().unwrap();
11191            let act = g.push(Node {
11192                op: Op::Const,
11193                inputs: vec![],
11194                shape: Shape::from_dims(&[1, k]),
11195                dtype: DType::F32,
11196            });
11197            let w = g.push(Node {
11198                op: Op::Const,
11199                inputs: vec![],
11200                shape: Shape::from_dims(&[w_bytes.len() / 4]),
11201                dtype: DType::U32,
11202            });
11203            let mm = g.push(Node {
11204                op: Op::Fused(
11205                    fuel_graph::registry::FusedOps::QMATMUL,
11206                    fuel_graph::registry::FusedOpParams::QMatMul {
11207                        quant_type: QuantType::Q5_0,
11208                        k,
11209                        n,
11210                    },
11211                ),
11212                inputs: vec![act, w],
11213                shape: Shape::from_dims(&[1, n]),
11214                dtype: DType::F32,
11215            });
11216            g.set_target_backend(mm, BackendId::Cpu);
11217            (act, w, mm)
11218        };
11219        let mut inputs = StorageCache::new();
11220        inputs.insert(act_id, Arc::new(RwLock::new(act_storage)));
11221        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
11222        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11223        let guard = result_arc.read().unwrap();
11224        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11225            panic!("expected Cpu storage");
11226        };
11227        let r: &[f32] = c.as_slice().unwrap();
11228        // Bit-exact against same kernel via the trait, since both
11229        // paths run fuel_quantized::matmul<BlockQ5_0>.
11230        assert_eq!(
11231            r,
11232            ref_out.as_slice(),
11233            "pipelined Q5_0 differs from reference: got {r:?}, want {ref_out:?}"
11234        );
11235    }
11236
11237    /// E2E: QMatMul with Q6K (256-element super-block k-quant).
11238    /// Same idea as the Q5_0 test — bit-exact against the
11239    /// reference fuel_quantized::matmul<BlockQ6K>. Confirms the
11240    /// dispatch arm wires `qmatmul_q6k_f32` correctly.
11241    #[test]
11242    fn pipelined_realize_qmatmul_q6k_against_reference() {
11243        use fuel_graph::QuantType;
11244        use fuel_quantized::{BlockQ6K, GgmlType};
11245        let n = 2;
11246        let k = 256; // 1 super-block per row
11247        let w_f32 = vec![1.0_f32; n * k];
11248        let blocks_per_row = k / BlockQ6K::BLCK_SIZE;
11249        let mut w_blocks = vec![BlockQ6K::zeros(); n * blocks_per_row];
11250        BlockQ6K::from_float(&w_f32, &mut w_blocks);
11251        let bytes_per_block = std::mem::size_of::<BlockQ6K>();
11252        let w_bytes: Vec<u8> = unsafe {
11253            std::slice::from_raw_parts(
11254                w_blocks.as_ptr() as *const u8,
11255                w_blocks.len() * bytes_per_block,
11256            )
11257        }
11258        .to_vec();
11259        let w_storage = fuel_memory::Storage::new(
11260            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
11261                &w_bytes,
11262            )),
11263            DType::U32,
11264        );
11265        let act_vec: Vec<f32> = (1..=k).map(|x| x as f32 / 100.0).collect();
11266        let act_storage = fuel_memory::from_slice_cpu(&act_vec);
11267        let mut ref_out = vec![0.0_f32; n];
11268        fuel_quantized::matmul::<BlockQ6K>((1, k, n), &act_vec, &w_blocks, &mut ref_out)
11269            .expect("ref matmul");
11270
11271        let graph = Arc::new(RwLock::new(Graph::new()));
11272        let (act_id, w_id, mm_id) = {
11273            let mut g = graph.write().unwrap();
11274            let act = g.push(Node {
11275                op: Op::Const,
11276                inputs: vec![],
11277                shape: Shape::from_dims(&[1, k]),
11278                dtype: DType::F32,
11279            });
11280            let w = g.push(Node {
11281                op: Op::Const,
11282                inputs: vec![],
11283                shape: Shape::from_dims(&[w_bytes.len() / 4]),
11284                dtype: DType::U32,
11285            });
11286            let mm = g.push(Node {
11287                op: Op::Fused(
11288                    fuel_graph::registry::FusedOps::QMATMUL,
11289                    fuel_graph::registry::FusedOpParams::QMatMul {
11290                        quant_type: QuantType::Q6K,
11291                        k,
11292                        n,
11293                    },
11294                ),
11295                inputs: vec![act, w],
11296                shape: Shape::from_dims(&[1, n]),
11297                dtype: DType::F32,
11298            });
11299            g.set_target_backend(mm, BackendId::Cpu);
11300            (act, w, mm)
11301        };
11302        let mut inputs = StorageCache::new();
11303        inputs.insert(act_id, Arc::new(RwLock::new(act_storage)));
11304        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
11305        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11306        let guard = result_arc.read().unwrap();
11307        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11308            panic!("expected Cpu storage");
11309        };
11310        let r: &[f32] = c.as_slice().unwrap();
11311        assert_eq!(
11312            r,
11313            ref_out.as_slice(),
11314            "pipelined Q6K differs from reference: got {r:?}, want {ref_out:?}"
11315        );
11316    }
11317
11318    /// E2E: BF16 RmsNormLastDim through the pipelined executor.
11319    /// Verifies that capability-driven dispatch routes the
11320    /// half-float norm op to the bf16-specific kernel (which
11321    /// accumulates in f32 internally).
11322    #[test]
11323    fn pipelined_realize_rms_norm_bf16() {
11324        let v: Vec<half::bf16> = [3.0_f32, 4.0]
11325            .iter()
11326            .map(|&x| half::bf16::from_f32(x))
11327            .collect();
11328        let storage = fuel_memory::from_slice_cpu(&v);
11329        let graph = Arc::new(RwLock::new(Graph::new()));
11330        let (in_id, op_id) = {
11331            let mut g = graph.write().unwrap();
11332            let in_id = g.push(Node {
11333                op: Op::Const,
11334                inputs: vec![],
11335                shape: Shape::from_dims(&[1, 2]),
11336                dtype: DType::BF16,
11337            });
11338            let op_id = g.push(Node {
11339                op: Op::Fused(
11340                    fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM,
11341                    fuel_graph::registry::FusedOpParams::RmsNormLastDim { eps: 0.0 },
11342                ),
11343                inputs: vec![in_id],
11344                shape: Shape::from_dims(&[1, 2]),
11345                dtype: DType::BF16,
11346            });
11347            g.set_target_backend(op_id, BackendId::Cpu);
11348            (in_id, op_id)
11349        };
11350        let mut inputs = StorageCache::new();
11351        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11352        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
11353        let guard = result_arc.read().unwrap();
11354        assert_eq!(guard.dtype, DType::BF16);
11355        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11356            panic!("expected Cpu storage");
11357        };
11358        let r: &[half::bf16] = c.as_slice().unwrap();
11359        let rms = (12.5_f32).sqrt();
11360        // bf16's ~3-digit mantissa absorbs the divisor; allow ~5%.
11361        assert!((r[0].to_f32() - 3.0 / rms).abs() < 0.05);
11362        assert!((r[1].to_f32() - 4.0 / rms).abs() < 0.05);
11363    }
11364
11365    /// E2E: BF16 matmul through the pipelined executor — proves
11366    /// the LLM forward-pass blocker (every transformer layer
11367    /// is dominated by matmul). Identity matmul on bf16 round-
11368    /// trips small integers exactly.
11369    #[test]
11370    fn pipelined_realize_matmul_bf16_identity() {
11371        let lhs_v: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0]
11372            .iter()
11373            .map(|&x| half::bf16::from_f32(x))
11374            .collect();
11375        let rhs_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0]
11376            .iter()
11377            .map(|&x| half::bf16::from_f32(x))
11378            .collect();
11379        let lhs = fuel_memory::from_slice_cpu(&lhs_v);
11380        let rhs = fuel_memory::from_slice_cpu(&rhs_v);
11381        let graph = Arc::new(RwLock::new(Graph::new()));
11382        let (l_id, r_id, mm_id) = {
11383            let mut g = graph.write().unwrap();
11384            let l = g.push(Node {
11385                op: Op::Const,
11386                inputs: vec![],
11387                shape: Shape::from_dims(&[2, 2]),
11388                dtype: DType::BF16,
11389            });
11390            let r = g.push(Node {
11391                op: Op::Const,
11392                inputs: vec![],
11393                shape: Shape::from_dims(&[2, 2]),
11394                dtype: DType::BF16,
11395            });
11396            let mm = g.push(Node {
11397                op: Op::MatMul,
11398                inputs: vec![l, r],
11399                shape: Shape::from_dims(&[2, 2]),
11400                dtype: DType::BF16,
11401            });
11402            g.set_target_backend(mm, BackendId::Cpu);
11403            (l, r, mm)
11404        };
11405        let mut inputs = StorageCache::new();
11406        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11407        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11408        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11409        let guard = result_arc.read().unwrap();
11410        assert_eq!(guard.dtype, DType::BF16);
11411        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11412            panic!("expected Cpu storage");
11413        };
11414        let r: &[half::bf16] = c.as_slice().unwrap();
11415        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
11416        assert_eq!(result_f32, vec![1.0, 2.0, 3.0, 4.0]);
11417    }
11418
11419    /// E2E (ROADMAP row 34): a mixed `[F32, W, F32]` matmul (f32 activation, half weight) runs on
11420    /// the CPU through the NATIVE kernel, with the weight left half-width: the output is f32 and
11421    /// equals the f64 matmul over the widened weights to f32 accumulation error. The weight is
11422    /// rounded to its stored half type first.
11423    fn mixed_cpu_matmul_matches_f64(weight_dtype: DType) {
11424        let (m, n, k) = (3_usize, 5_usize, 7_usize);
11425        let a: Vec<f32> = (0..m * k)
11426            .map(|i| ((i * 37 % 19) as f32 - 9.0) / 8.0)
11427            .collect();
11428        let w_f32: Vec<f32> = (0..k * n)
11429            .map(|i| ((i * 53 % 23) as f32 - 11.0) / 10.0)
11430            .collect();
11431        let (w_storage, widened): (_, Vec<f32>) = if weight_dtype == DType::BF16 {
11432            let h: Vec<half::bf16> = w_f32.iter().map(|&x| half::bf16::from_f32(x)).collect();
11433            let wide = h.iter().map(|x| x.to_f32()).collect();
11434            (fuel_memory::from_slice_cpu(&h), wide)
11435        } else {
11436            let h: Vec<half::f16> = w_f32.iter().map(|&x| half::f16::from_f32(x)).collect();
11437            let wide = h.iter().map(|x| x.to_f32()).collect();
11438            (fuel_memory::from_slice_cpu(&h), wide)
11439        };
11440        let graph = Arc::new(RwLock::new(Graph::new()));
11441        let (l_id, r_id, mm_id) = {
11442            let mut g = graph.write().unwrap();
11443            let l = g.push(Node {
11444                op: Op::Const,
11445                inputs: vec![],
11446                shape: Shape::from_dims(&[m, k]),
11447                dtype: DType::F32,
11448            });
11449            let r = g.push(Node {
11450                op: Op::Const,
11451                inputs: vec![],
11452                shape: Shape::from_dims(&[k, n]),
11453                dtype: weight_dtype,
11454            });
11455            let mm = g.push(Node {
11456                op: Op::MatMul,
11457                inputs: vec![l, r],
11458                shape: Shape::from_dims(&[m, n]),
11459                dtype: DType::F32,
11460            });
11461            g.set_target_backend(mm, BackendId::Cpu);
11462            (l, r, mm)
11463        };
11464        let mut inputs = StorageCache::new();
11465        inputs.insert(l_id, Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&a))));
11466        inputs.insert(r_id, Arc::new(RwLock::new(w_storage)));
11467        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11468        let guard = result_arc.read().unwrap();
11469        assert_eq!(guard.dtype, DType::F32);
11470        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11471            panic!("expected Cpu storage");
11472        };
11473        let got: &[f32] = c.as_slice().unwrap();
11474        for i in 0..m {
11475            for j in 0..n {
11476                let want: f64 = (0..k)
11477                    .map(|kk| a[i * k + kk] as f64 * widened[kk * n + j] as f64)
11478                    .sum();
11479                let err = (got[i * n + j] as f64 - want).abs();
11480                assert!(
11481                    err < 1e-5,
11482                    "{weight_dtype:?} [{i},{j}]: got {}, want {want}",
11483                    got[i * n + j]
11484                );
11485            }
11486        }
11487    }
11488
11489    #[test]
11490    fn pipelined_realize_mixed_f32_bf16_matmul_is_native_on_cpu() {
11491        mixed_cpu_matmul_matches_f64(DType::BF16);
11492    }
11493
11494    #[test]
11495    fn pipelined_realize_mixed_f32_f16_matmul_is_native_on_cpu() {
11496        mixed_cpu_matmul_matches_f64(DType::F16);
11497    }
11498
11499    /// E2E: F16 sum-reduce — verifies bf16/f16 reduction dispatch
11500    /// works through the executor.
11501    #[test]
11502    fn pipelined_realize_sum_dim_f16() {
11503        let v: Vec<half::f16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]
11504            .iter()
11505            .map(|&x| half::f16::from_f32(x))
11506            .collect();
11507        let storage = fuel_memory::from_slice_cpu(&v);
11508        let graph = Arc::new(RwLock::new(Graph::new()));
11509        let (in_id, sum_id) = {
11510            let mut g = graph.write().unwrap();
11511            let in_id = g.push(Node {
11512                op: Op::Const,
11513                inputs: vec![],
11514                shape: Shape::from_dims(&[2, 3]),
11515                dtype: DType::F16,
11516            });
11517            let sum_id = g.push(Node {
11518                op: Op::SumDim(1),
11519                inputs: vec![in_id],
11520                shape: Shape::from_dims(&[2]),
11521                dtype: DType::F16,
11522            });
11523            g.set_target_backend(sum_id, BackendId::Cpu);
11524            (in_id, sum_id)
11525        };
11526        let mut inputs = StorageCache::new();
11527        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11528        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
11529        let guard = result_arc.read().unwrap();
11530        assert_eq!(guard.dtype, DType::F16);
11531        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11532            panic!("expected Cpu storage");
11533        };
11534        let r: &[half::f16] = c.as_slice().unwrap();
11535        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
11536        assert_eq!(result_f32, vec![6.0, 15.0]);
11537    }
11538
11539    /// E2E: BF16 elementwise add through the pipelined executor.
11540    #[test]
11541    fn pipelined_realize_add_bf16() {
11542        let lhs_vec: Vec<half::bf16> = [1.0_f32, 2.0, 3.0]
11543            .iter()
11544            .map(|&x| half::bf16::from_f32(x))
11545            .collect();
11546        let rhs_vec: Vec<half::bf16> = [10.0_f32, 20.0, 30.0]
11547            .iter()
11548            .map(|&x| half::bf16::from_f32(x))
11549            .collect();
11550        let lhs = fuel_memory::from_slice_cpu(&lhs_vec);
11551        let rhs = fuel_memory::from_slice_cpu(&rhs_vec);
11552        let graph = Arc::new(RwLock::new(Graph::new()));
11553        let (l_id, r_id, op_id) = {
11554            let mut g = graph.write().unwrap();
11555            let l = g.push(Node {
11556                op: Op::Const,
11557                inputs: vec![],
11558                shape: Shape::from_dims(&[3]),
11559                dtype: DType::BF16,
11560            });
11561            let r = g.push(Node {
11562                op: Op::Const,
11563                inputs: vec![],
11564                shape: Shape::from_dims(&[3]),
11565                dtype: DType::BF16,
11566            });
11567            let op = g.push(Node {
11568                op: Op::Add,
11569                inputs: vec![l, r],
11570                shape: Shape::from_dims(&[3]),
11571                dtype: DType::BF16,
11572            });
11573            g.set_target_backend(op, BackendId::Cpu);
11574            (l, r, op)
11575        };
11576        let mut inputs = StorageCache::new();
11577        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11578        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11579        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
11580        let guard = result_arc.read().unwrap();
11581        assert_eq!(guard.dtype, DType::BF16);
11582        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11583            panic!("expected Cpu storage");
11584        };
11585        let r: &[half::bf16] = c.as_slice().unwrap();
11586        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
11587        assert_eq!(result_f32, vec![11.0, 22.0, 33.0]);
11588    }
11589
11590    /// E2E: F16 unary chain — Const + Sqr + Sqrt — verifies F16
11591    /// dispatch works and the via-f32 round-trip kernels behave
11592    /// correctly through the executor.
11593    #[test]
11594    fn pipelined_realize_sqr_then_sqrt_f16() {
11595        let v: Vec<half::f16> = [1.0_f32, 4.0, 9.0]
11596            .iter()
11597            .map(|&x| half::f16::from_f32(x))
11598            .collect();
11599        let storage = fuel_memory::from_slice_cpu(&v);
11600        let graph = Arc::new(RwLock::new(Graph::new()));
11601        let (in_id, sqrt_id) = {
11602            let mut g = graph.write().unwrap();
11603            let in_id = g.push(Node {
11604                op: Op::Const,
11605                inputs: vec![],
11606                shape: Shape::from_dims(&[3]),
11607                dtype: DType::F16,
11608            });
11609            let sqr_id = g.push(Node {
11610                op: Op::Sqr,
11611                inputs: vec![in_id],
11612                shape: Shape::from_dims(&[3]),
11613                dtype: DType::F16,
11614            });
11615            let sqrt_id = g.push(Node {
11616                op: Op::Sqrt,
11617                inputs: vec![sqr_id],
11618                shape: Shape::from_dims(&[3]),
11619                dtype: DType::F16,
11620            });
11621            g.set_target_backend(sqr_id, BackendId::Cpu);
11622            g.set_target_backend(sqrt_id, BackendId::Cpu);
11623            (in_id, sqrt_id)
11624        };
11625        let mut inputs = StorageCache::new();
11626        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11627        let (result_arc, _) = PipelinedExecutor::realize(graph, sqrt_id, inputs).expect("realize");
11628        let guard = result_arc.read().unwrap();
11629        assert_eq!(guard.dtype, DType::F16);
11630        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11631            panic!("expected Cpu storage");
11632        };
11633        let r: &[half::f16] = c.as_slice().unwrap();
11634        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
11635        // f16 has ~3 decimal digits; sqrt(sqr(x)) = |x| within rounding.
11636        for (got, want) in result_f32.iter().zip(&[1.0_f32, 4.0, 9.0]) {
11637            assert!((got - want).abs() < 0.05, "got {got}, want {want}");
11638        }
11639    }
11640
11641    /// E2E: F64 sum-reduce along one dim through the pipelined
11642    /// executor.
11643    #[test]
11644    fn pipelined_realize_sum_dim_f64() {
11645        let storage = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
11646        let graph = Arc::new(RwLock::new(Graph::new()));
11647        let (in_id, sum_id) = {
11648            let mut g = graph.write().unwrap();
11649            let in_id = g.push(Node {
11650                op: Op::Const,
11651                inputs: vec![],
11652                shape: Shape::from_dims(&[2, 3]),
11653                dtype: DType::F64,
11654            });
11655            let sum_id = g.push(Node {
11656                op: Op::SumDim(1),
11657                inputs: vec![in_id],
11658                shape: Shape::from_dims(&[2]),
11659                dtype: DType::F64,
11660            });
11661            g.set_target_backend(sum_id, BackendId::Cpu);
11662            (in_id, sum_id)
11663        };
11664        let mut inputs = StorageCache::new();
11665        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11666        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
11667        let guard = result_arc.read().unwrap();
11668        assert_eq!(guard.dtype, DType::F64);
11669        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11670            panic!("expected Cpu storage");
11671        };
11672        assert_eq!(c.as_slice::<f64>().unwrap(), &[6.0_f64, 15.0]);
11673    }
11674
11675    /// E2E: F64 matmul through the pipelined executor.
11676    #[test]
11677    fn pipelined_realize_matmul_2x3_times_3x2_f64() {
11678        let lhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
11679        let rhs = fuel_memory::from_slice_cpu(&[7.0_f64, 8.0, 9.0, 10.0, 11.0, 12.0]);
11680        let graph = Arc::new(RwLock::new(Graph::new()));
11681        let (l_id, r_id, mm_id) = {
11682            let mut g = graph.write().unwrap();
11683            let l = g.push(Node {
11684                op: Op::Const,
11685                inputs: vec![],
11686                shape: Shape::from_dims(&[2, 3]),
11687                dtype: DType::F64,
11688            });
11689            let r = g.push(Node {
11690                op: Op::Const,
11691                inputs: vec![],
11692                shape: Shape::from_dims(&[3, 2]),
11693                dtype: DType::F64,
11694            });
11695            let mm = g.push(Node {
11696                op: Op::MatMul,
11697                inputs: vec![l, r],
11698                shape: Shape::from_dims(&[2, 2]),
11699                dtype: DType::F64,
11700            });
11701            g.set_target_backend(mm, BackendId::Cpu);
11702            (l, r, mm)
11703        };
11704        let mut inputs = StorageCache::new();
11705        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11706        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11707        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11708        let guard = result_arc.read().unwrap();
11709        assert_eq!(guard.dtype, DType::F64);
11710        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11711            panic!("expected Cpu storage");
11712        };
11713        assert_eq!(
11714            c.as_slice::<f64>().unwrap(),
11715            &[58.0_f64, 64.0, 139.0, 154.0]
11716        );
11717    }
11718
11719    /// E2E: F64 unary chain — Const + Sqr + Sqrt — verifies that
11720    /// the kernel-binding lookup picks the f64 entries when the
11721    /// graph nodes carry DType::F64.
11722    #[test]
11723    fn pipelined_realize_sqr_then_sqrt_f64() {
11724        let storage = fuel_memory::from_slice_cpu(&[1.0_f64, 4.0, 9.0]);
11725        let graph = Arc::new(RwLock::new(Graph::new()));
11726        let (in_id, sqrt_id) = {
11727            let mut g = graph.write().unwrap();
11728            let in_id = g.push(Node {
11729                op: Op::Const,
11730                inputs: vec![],
11731                shape: Shape::from_dims(&[3]),
11732                dtype: DType::F64,
11733            });
11734            let sqr_id = g.push(Node {
11735                op: Op::Sqr,
11736                inputs: vec![in_id],
11737                shape: Shape::from_dims(&[3]),
11738                dtype: DType::F64,
11739            });
11740            let sqrt_id = g.push(Node {
11741                op: Op::Sqrt,
11742                inputs: vec![sqr_id],
11743                shape: Shape::from_dims(&[3]),
11744                dtype: DType::F64,
11745            });
11746            g.set_target_backend(sqr_id, BackendId::Cpu);
11747            g.set_target_backend(sqrt_id, BackendId::Cpu);
11748            (in_id, sqrt_id)
11749        };
11750        let mut inputs = StorageCache::new();
11751        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11752        let (result_arc, _) = PipelinedExecutor::realize(graph, sqrt_id, inputs).expect("realize");
11753        let guard = result_arc.read().unwrap();
11754        assert_eq!(guard.dtype, DType::F64);
11755        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11756            panic!("expected Cpu storage");
11757        };
11758        assert_eq!(c.as_slice::<f64>().unwrap(), &[1.0_f64, 4.0, 9.0]);
11759    }
11760
11761    /// E2E: ArgMaxDim — produces U32 output indices.
11762    #[test]
11763    fn pipelined_realize_argmax_dim() {
11764        // input [2, 3] = [[1, 5, 2], [9, 0, 4]]
11765        // argmax dim=1 → [1, 0]
11766        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 2.0, 9.0, 0.0, 4.0]);
11767        let graph = Arc::new(RwLock::new(Graph::new()));
11768        let (in_id, op_id) = {
11769            let mut g = graph.write().unwrap();
11770            let in_id = g.push(Node {
11771                op: Op::Const,
11772                inputs: vec![],
11773                shape: Shape::from_dims(&[2, 3]),
11774                dtype: DType::F32,
11775            });
11776            let op_id = g.push(Node {
11777                op: Op::ArgMaxDim(1),
11778                inputs: vec![in_id],
11779                shape: Shape::from_dims(&[2]),
11780                dtype: DType::U32,
11781            });
11782            g.set_target_backend(op_id, BackendId::Cpu);
11783            (in_id, op_id)
11784        };
11785        let mut inputs = StorageCache::new();
11786        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11787        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
11788        let guard = result_arc.read().unwrap();
11789        assert_eq!(guard.dtype, DType::U32);
11790        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11791            panic!("expected Cpu storage");
11792        };
11793        assert_eq!(c.as_slice::<u32>().unwrap(), &[1u32, 0]);
11794    }
11795
11796    /// E2E: IndexAdd along outer dim — accumulate updates into a
11797    /// rank-1 base tensor at indexed positions.
11798    #[test]
11799    fn pipelined_realize_index_add_simple() {
11800        let base = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
11801        let indices = fuel_memory::from_slice_cpu(&[0u32, 0]);
11802        let src = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
11803        let graph = Arc::new(RwLock::new(Graph::new()));
11804        let (b_id, i_id, s_id, op_id) = {
11805            let mut g = graph.write().unwrap();
11806            let b = g.push(Node {
11807                op: Op::Const,
11808                inputs: vec![],
11809                shape: Shape::from_dims(&[3]),
11810                dtype: DType::F32,
11811            });
11812            let i = g.push(Node {
11813                op: Op::Const,
11814                inputs: vec![],
11815                shape: Shape::from_dims(&[2]),
11816                dtype: DType::U32,
11817            });
11818            let s = g.push(Node {
11819                op: Op::Const,
11820                inputs: vec![],
11821                shape: Shape::from_dims(&[2]),
11822                dtype: DType::F32,
11823            });
11824            let op = g.push(Node {
11825                op: Op::IndexAdd { dim: 0 },
11826                inputs: vec![b, i, s],
11827                shape: Shape::from_dims(&[3]),
11828                dtype: DType::F32,
11829            });
11830            g.set_target_backend(op, BackendId::Cpu);
11831            (b, i, s, op)
11832        };
11833        let mut inputs = StorageCache::new();
11834        inputs.insert(b_id, Arc::new(RwLock::new(base)));
11835        inputs.insert(i_id, Arc::new(RwLock::new(indices)));
11836        inputs.insert(s_id, Arc::new(RwLock::new(src)));
11837        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
11838        let guard = result_arc.read().unwrap();
11839        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11840            panic!("expected Cpu storage");
11841        };
11842        // 10 + 1 + 2 = 13; 20 untouched; 30 untouched.
11843        assert_eq!(c.as_slice::<f32>().unwrap(), &[13.0, 20.0, 30.0]);
11844    }
11845
11846    /// E2E: ScatterAdd along outer dim — same-rank indices, base
11847    /// starts as zeros, src adds values at scatter positions.
11848    #[test]
11849    fn pipelined_realize_scatter_add_outer_dim() {
11850        // base [3, 2] = zeros; indices [2, 2] = [[0, 1], [2, 0]];
11851        // src [2, 2] = [[1, 2], [3, 4]]; dim=0
11852        // → out = [[1, 4], [0, 2], [3, 0]]
11853        let base = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
11854        let indices = fuel_memory::from_slice_cpu(&[0u32, 1, 2, 0]);
11855        let src = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
11856        let graph = Arc::new(RwLock::new(Graph::new()));
11857        let (b_id, i_id, s_id, op_id) = {
11858            let mut g = graph.write().unwrap();
11859            let b = g.push(Node {
11860                op: Op::Const,
11861                inputs: vec![],
11862                shape: Shape::from_dims(&[3, 2]),
11863                dtype: DType::F32,
11864            });
11865            let i = g.push(Node {
11866                op: Op::Const,
11867                inputs: vec![],
11868                shape: Shape::from_dims(&[2, 2]),
11869                dtype: DType::U32,
11870            });
11871            let s = g.push(Node {
11872                op: Op::Const,
11873                inputs: vec![],
11874                shape: Shape::from_dims(&[2, 2]),
11875                dtype: DType::F32,
11876            });
11877            let op = g.push(Node {
11878                op: Op::ScatterAdd { dim: 0 },
11879                inputs: vec![b, i, s],
11880                shape: Shape::from_dims(&[3, 2]),
11881                dtype: DType::F32,
11882            });
11883            g.set_target_backend(op, BackendId::Cpu);
11884            (b, i, s, op)
11885        };
11886        let mut inputs = StorageCache::new();
11887        inputs.insert(b_id, Arc::new(RwLock::new(base)));
11888        inputs.insert(i_id, Arc::new(RwLock::new(indices)));
11889        inputs.insert(s_id, Arc::new(RwLock::new(src)));
11890        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
11891        let guard = result_arc.read().unwrap();
11892        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11893            panic!("expected Cpu storage");
11894        };
11895        assert_eq!(
11896            c.as_slice::<f32>().unwrap(),
11897            &[1.0, 4.0, 0.0, 2.0, 3.0, 0.0]
11898        );
11899    }
11900
11901    /// E2E: Rope through the pipelined executor. cos=0, sin=1
11902    /// rotates the head_dim halves with sign per the rotate_half
11903    /// convention.
11904    #[test]
11905    fn pipelined_realize_rope_pi_over_two() {
11906        // x [1, 1, 4] = [1, 2, 3, 4]. cos=[0,0,0,0], sin=[1,1,1,1].
11907        // Expected: [-3, -4, 1, 2].
11908        let x = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
11909        let cos = fuel_memory::from_slice_cpu(&[0.0_f32, 0.0, 0.0, 0.0]);
11910        let sin = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
11911        let graph = Arc::new(RwLock::new(Graph::new()));
11912        let (x_id, cos_id, sin_id, r_id) = {
11913            let mut g = graph.write().unwrap();
11914            let x = g.push(Node {
11915                op: Op::Const,
11916                inputs: vec![],
11917                shape: Shape::from_dims(&[1, 1, 4]),
11918                dtype: DType::F32,
11919            });
11920            let c = g.push(Node {
11921                op: Op::Const,
11922                inputs: vec![],
11923                shape: Shape::from_dims(&[1, 4]),
11924                dtype: DType::F32,
11925            });
11926            let s = g.push(Node {
11927                op: Op::Const,
11928                inputs: vec![],
11929                shape: Shape::from_dims(&[1, 4]),
11930                dtype: DType::F32,
11931            });
11932            let r = g.push(Node {
11933                op: Op::Fused(
11934                    fuel_graph::registry::FusedOps::ROPE,
11935                    fuel_graph::registry::FusedOpParams::Rope,
11936                ),
11937                inputs: vec![x, c, s],
11938                shape: Shape::from_dims(&[1, 1, 4]),
11939                dtype: DType::F32,
11940            });
11941            g.set_target_backend(r, BackendId::Cpu);
11942            (x, c, s, r)
11943        };
11944        let mut inputs = StorageCache::new();
11945        inputs.insert(x_id, Arc::new(RwLock::new(x)));
11946        inputs.insert(cos_id, Arc::new(RwLock::new(cos)));
11947        inputs.insert(sin_id, Arc::new(RwLock::new(sin)));
11948        let (result_arc, _) = PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
11949        let guard = result_arc.read().unwrap();
11950        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11951            panic!("expected Cpu storage");
11952        };
11953        assert_eq!(c.as_slice::<f32>().unwrap(), &[-3.0, -4.0, 1.0, 2.0]);
11954    }
11955
11956    /// E2E: Gather along inner dim. Source [2, 4]; indices [2, 3];
11957    /// output [2, 3] = picks from each row by per-row indices.
11958    #[test]
11959    fn pipelined_realize_gather_inner_dim() {
11960        let source =
11961            fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0]);
11962        let indices = fuel_memory::from_slice_cpu(&[0u32, 2, 1, 3, 0, 0]);
11963        let graph = Arc::new(RwLock::new(Graph::new()));
11964        let (src_id, idx_id, g_id) = {
11965            let mut g = graph.write().unwrap();
11966            let s = g.push(Node {
11967                op: Op::Const,
11968                inputs: vec![],
11969                shape: Shape::from_dims(&[2, 4]),
11970                dtype: DType::F32,
11971            });
11972            let i = g.push(Node {
11973                op: Op::Const,
11974                inputs: vec![],
11975                shape: Shape::from_dims(&[2, 3]),
11976                dtype: DType::U32,
11977            });
11978            let g_id = g.push(Node {
11979                op: Op::Gather { dim: 1 },
11980                inputs: vec![s, i],
11981                shape: Shape::from_dims(&[2, 3]),
11982                dtype: DType::F32,
11983            });
11984            g.set_target_backend(g_id, BackendId::Cpu);
11985            (s, i, g_id)
11986        };
11987        let mut inputs = StorageCache::new();
11988        inputs.insert(src_id, Arc::new(RwLock::new(source)));
11989        inputs.insert(idx_id, Arc::new(RwLock::new(indices)));
11990        let (result_arc, _) = PipelinedExecutor::realize(graph, g_id, inputs).expect("realize");
11991        let guard = result_arc.read().unwrap();
11992        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11993            panic!("expected Cpu storage");
11994        };
11995        assert_eq!(
11996            c.as_slice::<f32>().unwrap(),
11997            &[10.0, 30.0, 20.0, 80.0, 50.0, 50.0]
11998        );
11999    }
12000
12001    /// E2E: IndexSelect — embedding-table lookup. Source is a
12002    /// `[vocab=4, d_model=3]` table; indices are token IDs;
12003    /// output is `[seq=3, d_model=3]` with the picked rows.
12004    #[test]
12005    fn pipelined_realize_index_select_embedding_lookup() {
12006        let table = fuel_memory::from_slice_cpu(&[
12007            10.0_f32, 11.0, 12.0, // row 0
12008            20.0, 21.0, 22.0, // row 1
12009            30.0, 31.0, 32.0, // row 2
12010            40.0, 41.0, 42.0, // row 3
12011        ]);
12012        let indices = fuel_memory::from_slice_cpu(&[2u32, 0, 2]);
12013        let graph = Arc::new(RwLock::new(Graph::new()));
12014        let (table_id, idx_id, sel_id) = {
12015            let mut g = graph.write().unwrap();
12016            let t = g.push(Node {
12017                op: Op::Const,
12018                inputs: vec![],
12019                shape: Shape::from_dims(&[4, 3]),
12020                dtype: DType::F32,
12021            });
12022            let i = g.push(Node {
12023                op: Op::Const,
12024                inputs: vec![],
12025                shape: Shape::from_dims(&[3]),
12026                dtype: DType::U32,
12027            });
12028            let s = g.push(Node {
12029                op: Op::IndexSelect { dim: 0 },
12030                inputs: vec![t, i],
12031                shape: Shape::from_dims(&[3, 3]),
12032                dtype: DType::F32,
12033            });
12034            g.set_target_backend(s, BackendId::Cpu);
12035            (t, i, s)
12036        };
12037        let mut inputs = StorageCache::new();
12038        inputs.insert(table_id, Arc::new(RwLock::new(table)));
12039        inputs.insert(idx_id, Arc::new(RwLock::new(indices)));
12040        let (result_arc, result_layout) =
12041            PipelinedExecutor::realize(graph, sel_id, inputs).expect("realize");
12042        assert_eq!(result_layout.shape().dims(), &[3, 3]);
12043        let guard = result_arc.read().unwrap();
12044        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12045            panic!("expected Cpu storage");
12046        };
12047        assert_eq!(
12048            c.as_slice::<f32>().unwrap(),
12049            &[30.0, 31.0, 32.0, 10.0, 11.0, 12.0, 30.0, 31.0, 32.0]
12050        );
12051    }
12052
12053    /// E2E: RmsNormLastDim on a 2-row input. Each row's output
12054    /// has unit RMS up to the eps-induced bias.
12055    #[test]
12056    fn pipelined_realize_rms_norm_last_dim() {
12057        let storage = fuel_memory::from_slice_cpu(&[
12058            3.0_f32, 4.0, // row 0: rms = sqrt(12.5)
12059            6.0, 8.0, // row 1: rms = sqrt(50.0) = 5*sqrt(2)
12060        ]);
12061        let graph = Arc::new(RwLock::new(Graph::new()));
12062        let (in_id, op_id) = {
12063            let mut g = graph.write().unwrap();
12064            let in_id = g.push(Node {
12065                op: Op::Const,
12066                inputs: vec![],
12067                shape: Shape::from_dims(&[2, 2]),
12068                dtype: DType::F32,
12069            });
12070            let op_id = g.push(Node {
12071                op: Op::Fused(
12072                    fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM,
12073                    fuel_graph::registry::FusedOpParams::RmsNormLastDim { eps: 0.0 },
12074                ),
12075                inputs: vec![in_id],
12076                shape: Shape::from_dims(&[2, 2]),
12077                dtype: DType::F32,
12078            });
12079            g.set_target_backend(op_id, BackendId::Cpu);
12080            (in_id, op_id)
12081        };
12082        let mut inputs = StorageCache::new();
12083        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12084        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12085        let guard = result_arc.read().unwrap();
12086        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12087            panic!("expected Cpu storage");
12088        };
12089        let result: &[f32] = c.as_slice().unwrap();
12090        // Row 0: rms = sqrt(12.5). Output = [3, 4] / sqrt(12.5).
12091        let rms0 = (12.5_f32).sqrt();
12092        assert!((result[0] - 3.0 / rms0).abs() < 1e-6);
12093        assert!((result[1] - 4.0 / rms0).abs() < 1e-6);
12094        // Row 1: rms = sqrt(50). Output = [6, 8] / sqrt(50).
12095        let rms1 = (50.0_f32).sqrt();
12096        assert!((result[2] - 6.0 / rms1).abs() < 1e-6);
12097        assert!((result[3] - 8.0 / rms1).abs() < 1e-6);
12098    }
12099
12100    /// E2E: LayerNormLastDim — each row's output has zero mean and
12101    /// unit variance.
12102    #[test]
12103    fn pipelined_realize_layer_norm_last_dim() {
12104        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 10.0, 20.0, 30.0]);
12105        let graph = Arc::new(RwLock::new(Graph::new()));
12106        let (in_id, op_id) = {
12107            let mut g = graph.write().unwrap();
12108            let in_id = g.push(Node {
12109                op: Op::Const,
12110                inputs: vec![],
12111                shape: Shape::from_dims(&[2, 3]),
12112                dtype: DType::F32,
12113            });
12114            let op_id = g.push(Node {
12115                op: Op::Fused(
12116                    fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM,
12117                    fuel_graph::registry::FusedOpParams::LayerNormLastDim { eps: 0.0 },
12118                ),
12119                inputs: vec![in_id],
12120                shape: Shape::from_dims(&[2, 3]),
12121                dtype: DType::F32,
12122            });
12123            g.set_target_backend(op_id, BackendId::Cpu);
12124            (in_id, op_id)
12125        };
12126        let mut inputs = StorageCache::new();
12127        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12128        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12129        let guard = result_arc.read().unwrap();
12130        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12131            panic!("expected Cpu storage");
12132        };
12133        let result: &[f32] = c.as_slice().unwrap();
12134        // Each row should have mean ~0 and var ~1.
12135        for row in 0..2 {
12136            let off = row * 3;
12137            let sum: f32 = result[off..off + 3].iter().sum();
12138            let mean = sum / 3.0;
12139            assert!(mean.abs() < 1e-6, "row {row} mean should be 0, got {mean}");
12140            let var: f32 = result[off..off + 3]
12141                .iter()
12142                .map(|v| (v - mean).powi(2))
12143                .sum::<f32>()
12144                / 3.0;
12145            assert!(
12146                (var - 1.0).abs() < 1e-6,
12147                "row {row} var should be 1, got {var}"
12148            );
12149        }
12150    }
12151
12152    /// E2E: SoftmaxLastDim on a 2-row input. Each row should sum
12153    /// to 1; uniform row gives uniform output.
12154    #[test]
12155    fn pipelined_realize_softmax_last_dim() {
12156        // Row 0: [1, 1, 1, 1] → uniform 0.25 each
12157        // Row 1: [0, 0, 0, 100] → effectively a one-hot at position 3
12158        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 100.0]);
12159        let graph = Arc::new(RwLock::new(Graph::new()));
12160        let (in_id, op_id) = {
12161            let mut g = graph.write().unwrap();
12162            let in_id = g.push(Node {
12163                op: Op::Const,
12164                inputs: vec![],
12165                shape: Shape::from_dims(&[2, 4]),
12166                dtype: DType::F32,
12167            });
12168            let op_id = g.push(Node {
12169                op: Op::Fused(
12170                    fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM,
12171                    fuel_graph::registry::FusedOpParams::SoftmaxLastDim,
12172                ),
12173                inputs: vec![in_id],
12174                shape: Shape::from_dims(&[2, 4]),
12175                dtype: DType::F32,
12176            });
12177            g.set_target_backend(op_id, BackendId::Cpu);
12178            (in_id, op_id)
12179        };
12180        let mut inputs = StorageCache::new();
12181        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12182        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12183        let guard = result_arc.read().unwrap();
12184        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12185            panic!("expected Cpu storage");
12186        };
12187        let result: &[f32] = c.as_slice().unwrap();
12188
12189        // Row 0: uniform 0.25
12190        for v in &result[..4] {
12191            assert!((v - 0.25).abs() < 1e-7);
12192        }
12193        // Row 1: positions 0..3 ≈ 0, position 4 (= last column) ≈ 1
12194        // (e^100 dominates).
12195        for v in &result[4..7] {
12196            assert!(
12197                *v < 1e-30,
12198                "row-1 leading positions should be near 0, got {v}"
12199            );
12200        }
12201        assert!(
12202            result[7] > 0.999,
12203            "row-1 last position should dominate, got {}",
12204            result[7]
12205        );
12206        // Each row sums to 1.
12207        let row0_sum: f32 = result[..4].iter().sum();
12208        let row1_sum: f32 = result[4..].iter().sum();
12209        assert!((row0_sum - 1.0).abs() < 1e-6);
12210        assert!((row1_sum - 1.0).abs() < 1e-6);
12211    }
12212
12213    /// E2E: Concat along inner dim — two [2, 3] tensors → [2, 6].
12214    #[test]
12215    fn pipelined_realize_concat_inner_dim() {
12216        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
12217        let b = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0, 9.0, 10.0, 11.0, 12.0]);
12218        let graph = Arc::new(RwLock::new(Graph::new()));
12219        let (a_id, b_id, c_id) = {
12220            let mut g = graph.write().unwrap();
12221            let a = g.push(Node {
12222                op: Op::Const,
12223                inputs: vec![],
12224                shape: Shape::from_dims(&[2, 3]),
12225                dtype: DType::F32,
12226            });
12227            let b = g.push(Node {
12228                op: Op::Const,
12229                inputs: vec![],
12230                shape: Shape::from_dims(&[2, 3]),
12231                dtype: DType::F32,
12232            });
12233            let c = g.push(Node {
12234                op: Op::Concat { dim: 1 },
12235                inputs: vec![a, b],
12236                shape: Shape::from_dims(&[2, 6]),
12237                dtype: DType::F32,
12238            });
12239            g.set_target_backend(c, BackendId::Cpu);
12240            (a, b, c)
12241        };
12242        let mut inputs = StorageCache::new();
12243        inputs.insert(a_id, Arc::new(RwLock::new(a)));
12244        inputs.insert(b_id, Arc::new(RwLock::new(b)));
12245        let (result_arc, result_layout) =
12246            PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12247        assert_eq!(result_layout.shape().dims(), &[2, 6]);
12248        let guard = result_arc.read().unwrap();
12249        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12250            panic!("expected Cpu storage");
12251        };
12252        assert_eq!(
12253            c.as_slice::<f32>().unwrap(),
12254            &[
12255                1.0, 2.0, 3.0, 7.0, 8.0, 9.0, 4.0, 5.0, 6.0, 10.0, 11.0, 12.0
12256            ]
12257        );
12258    }
12259
12260    /// E2E: Concat with three inputs along outer dim — verifies
12261    /// variable-arity input handling through the executor.
12262    #[test]
12263    fn pipelined_realize_concat_three_inputs_outer() {
12264        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
12265        let b = fuel_memory::from_slice_cpu(&[3.0_f32, 4.0]);
12266        let c = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0]);
12267        let graph = Arc::new(RwLock::new(Graph::new()));
12268        let (a_id, b_id, c_id, cat_id) = {
12269            let mut g = graph.write().unwrap();
12270            let a = g.push(Node {
12271                op: Op::Const,
12272                inputs: vec![],
12273                shape: Shape::from_dims(&[2]),
12274                dtype: DType::F32,
12275            });
12276            let b = g.push(Node {
12277                op: Op::Const,
12278                inputs: vec![],
12279                shape: Shape::from_dims(&[2]),
12280                dtype: DType::F32,
12281            });
12282            let c = g.push(Node {
12283                op: Op::Const,
12284                inputs: vec![],
12285                shape: Shape::from_dims(&[2]),
12286                dtype: DType::F32,
12287            });
12288            let cat = g.push(Node {
12289                op: Op::Concat { dim: 0 },
12290                inputs: vec![a, b, c],
12291                shape: Shape::from_dims(&[6]),
12292                dtype: DType::F32,
12293            });
12294            g.set_target_backend(cat, BackendId::Cpu);
12295            (a, b, c, cat)
12296        };
12297        let mut inputs = StorageCache::new();
12298        inputs.insert(a_id, Arc::new(RwLock::new(a)));
12299        inputs.insert(b_id, Arc::new(RwLock::new(b)));
12300        inputs.insert(c_id, Arc::new(RwLock::new(c)));
12301        let (result_arc, _) = PipelinedExecutor::realize(graph, cat_id, inputs).expect("realize");
12302        let guard = result_arc.read().unwrap();
12303        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12304            panic!("expected Cpu storage");
12305        };
12306        assert_eq!(
12307            c.as_slice::<f32>().unwrap(),
12308            &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
12309        );
12310    }
12311
12312    /// E2E: AddScalar — graph emits Op::AddScalar; the executor
12313    /// maps it to OpKind::Affine with mul=1, add=c.
12314    #[test]
12315    fn pipelined_realize_add_scalar() {
12316        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
12317        let graph = Arc::new(RwLock::new(Graph::new()));
12318        let (in_id, op_id) = {
12319            let mut g = graph.write().unwrap();
12320            let in_id = g.push(Node {
12321                op: Op::Const,
12322                inputs: vec![],
12323                shape: Shape::from_dims(&[3]),
12324                dtype: DType::F32,
12325            });
12326            let op_id = g.push(Node {
12327                op: Op::AddScalar(10.0),
12328                inputs: vec![in_id],
12329                shape: Shape::from_dims(&[3]),
12330                dtype: DType::F32,
12331            });
12332            g.set_target_backend(op_id, BackendId::Cpu);
12333            (in_id, op_id)
12334        };
12335        let mut inputs = StorageCache::new();
12336        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12337        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12338        let guard = result_arc.read().unwrap();
12339        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12340            panic!("expected Cpu storage");
12341        };
12342        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 12.0, 13.0]);
12343    }
12344
12345    /// E2E: Clamp — clamp values to [-2, 2].
12346    #[test]
12347    fn pipelined_realize_clamp() {
12348        let storage = fuel_memory::from_slice_cpu(&[-5.0_f32, 0.5, 100.0]);
12349        let graph = Arc::new(RwLock::new(Graph::new()));
12350        let (in_id, op_id) = {
12351            let mut g = graph.write().unwrap();
12352            let in_id = g.push(Node {
12353                op: Op::Const,
12354                inputs: vec![],
12355                shape: Shape::from_dims(&[3]),
12356                dtype: DType::F32,
12357            });
12358            let op_id = g.push(Node {
12359                op: Op::Clamp {
12360                    min: -2.0,
12361                    max: 2.0,
12362                },
12363                inputs: vec![in_id],
12364                shape: Shape::from_dims(&[3]),
12365                dtype: DType::F32,
12366            });
12367            g.set_target_backend(op_id, BackendId::Cpu);
12368            (in_id, op_id)
12369        };
12370        let mut inputs = StorageCache::new();
12371        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12372        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12373        let guard = result_arc.read().unwrap();
12374        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12375            panic!("expected Cpu storage");
12376        };
12377        assert_eq!(c.as_slice::<f32>().unwrap(), &[-2.0, 0.5, 2.0]);
12378    }
12379
12380    /// E2E: Maximum — elementwise tensor max.
12381    #[test]
12382    fn pipelined_realize_maximum_elementwise() {
12383        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, -3.0]);
12384        let rhs_storage = fuel_memory::from_slice_cpu(&[2.0_f32, 1.0, -1.0]);
12385        let graph = Arc::new(RwLock::new(Graph::new()));
12386        let (lhs_id, rhs_id, op_id) = {
12387            let mut g = graph.write().unwrap();
12388            let lhs = g.push(Node {
12389                op: Op::Const,
12390                inputs: vec![],
12391                shape: Shape::from_dims(&[3]),
12392                dtype: DType::F32,
12393            });
12394            let rhs = g.push(Node {
12395                op: Op::Const,
12396                inputs: vec![],
12397                shape: Shape::from_dims(&[3]),
12398                dtype: DType::F32,
12399            });
12400            let op = g.push(Node {
12401                op: Op::Maximum,
12402                inputs: vec![lhs, rhs],
12403                shape: Shape::from_dims(&[3]),
12404                dtype: DType::F32,
12405            });
12406            g.set_target_backend(op, BackendId::Cpu);
12407            (lhs, rhs, op)
12408        };
12409        let mut inputs = StorageCache::new();
12410        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
12411        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
12412        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12413        let guard = result_arc.read().unwrap();
12414        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12415            panic!("expected Cpu storage");
12416        };
12417        assert_eq!(c.as_slice::<f32>().unwrap(), &[2.0, 5.0, -1.0]);
12418    }
12419
12420    /// E2E: Const + Const + Conv2D — the 2×2 sum-kernel test from
12421    /// byte_kernels driven through the pipelined executor.
12422    #[test]
12423    fn pipelined_realize_conv2d_2x2_sum_kernel() {
12424        // x [1, 1, 3, 3]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
12425        // weight [1, 1, 2, 2]: all-ones
12426        // → out [1, 1, 2, 2]: [[12, 16], [24, 28]]
12427        let x_storage =
12428            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
12429        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
12430
12431        let graph = Arc::new(RwLock::new(Graph::new()));
12432        let (x_id, w_id, c_id) = {
12433            let mut g = graph.write().unwrap();
12434            let x = g.push(Node {
12435                op: Op::Const,
12436                inputs: vec![],
12437                shape: Shape::from_dims(&[1, 1, 3, 3]),
12438                dtype: DType::F32,
12439            });
12440            let w = g.push(Node {
12441                op: Op::Const,
12442                inputs: vec![],
12443                shape: Shape::from_dims(&[1, 1, 2, 2]),
12444                dtype: DType::F32,
12445            });
12446            let c = g.push(Node {
12447                op: Op::Fused(
12448                    fuel_graph::registry::FusedOps::CONV2D,
12449                    fuel_graph::registry::FusedOpParams::Conv2D {
12450                        stride: (1, 1),
12451                        padding: (0, 0),
12452                        groups: 1,
12453                    },
12454                ),
12455                inputs: vec![x, w],
12456                shape: Shape::from_dims(&[1, 1, 2, 2]),
12457                dtype: DType::F32,
12458            });
12459            g.set_target_backend(c, BackendId::Cpu);
12460            (x, w, c)
12461        };
12462        let mut inputs = StorageCache::new();
12463        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12464        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12465
12466        let (result_arc, result_layout) =
12467            PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12468        assert_eq!(result_layout.shape().dims(), &[1, 1, 2, 2]);
12469
12470        let guard = result_arc.read().unwrap();
12471        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12472            panic!("expected Cpu storage");
12473        };
12474        assert_eq!(c.as_slice::<f32>().unwrap(), &[12.0, 16.0, 24.0, 28.0]);
12475    }
12476
12477    /// E2E: Conv2D with bias (3 inputs).
12478    #[test]
12479    fn pipelined_realize_conv2d_with_bias() {
12480        let x_storage =
12481            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
12482        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
12483        let bias_storage = fuel_memory::from_slice_cpu(&[100.0_f32]);
12484
12485        let graph = Arc::new(RwLock::new(Graph::new()));
12486        let (x_id, w_id, b_id, c_id) = {
12487            let mut g = graph.write().unwrap();
12488            let x = g.push(Node {
12489                op: Op::Const,
12490                inputs: vec![],
12491                shape: Shape::from_dims(&[1, 1, 3, 3]),
12492                dtype: DType::F32,
12493            });
12494            let w = g.push(Node {
12495                op: Op::Const,
12496                inputs: vec![],
12497                shape: Shape::from_dims(&[1, 1, 2, 2]),
12498                dtype: DType::F32,
12499            });
12500            let b = g.push(Node {
12501                op: Op::Const,
12502                inputs: vec![],
12503                shape: Shape::from_dims(&[1]),
12504                dtype: DType::F32,
12505            });
12506            let c = g.push(Node {
12507                op: Op::Fused(
12508                    fuel_graph::registry::FusedOps::CONV2D,
12509                    fuel_graph::registry::FusedOpParams::Conv2D {
12510                        stride: (1, 1),
12511                        padding: (0, 0),
12512                        groups: 1,
12513                    },
12514                ),
12515                inputs: vec![x, w, b],
12516                shape: Shape::from_dims(&[1, 1, 2, 2]),
12517                dtype: DType::F32,
12518            });
12519            g.set_target_backend(c, BackendId::Cpu);
12520            (x, w, b, c)
12521        };
12522        let mut inputs = StorageCache::new();
12523        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12524        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12525        inputs.insert(b_id, Arc::new(RwLock::new(bias_storage)));
12526
12527        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12528        let guard = result_arc.read().unwrap();
12529        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12530            panic!("expected Cpu storage");
12531        };
12532        assert_eq!(c.as_slice::<f32>().unwrap(), &[112.0, 116.0, 124.0, 128.0]);
12533    }
12534
12535    /// E2E: Conv2D in F64 — same 2x2 sum-kernel test as F32, on doubles.
12536    #[test]
12537    fn pipelined_realize_conv2d_f64() {
12538        let x_storage =
12539            fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
12540        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f64, 1.0, 1.0, 1.0]);
12541
12542        let graph = Arc::new(RwLock::new(Graph::new()));
12543        let (x_id, w_id, c_id) = {
12544            let mut g = graph.write().unwrap();
12545            let x = g.push(Node {
12546                op: Op::Const,
12547                inputs: vec![],
12548                shape: Shape::from_dims(&[1, 1, 3, 3]),
12549                dtype: DType::F64,
12550            });
12551            let w = g.push(Node {
12552                op: Op::Const,
12553                inputs: vec![],
12554                shape: Shape::from_dims(&[1, 1, 2, 2]),
12555                dtype: DType::F64,
12556            });
12557            let c = g.push(Node {
12558                op: Op::Fused(
12559                    fuel_graph::registry::FusedOps::CONV2D,
12560                    fuel_graph::registry::FusedOpParams::Conv2D {
12561                        stride: (1, 1),
12562                        padding: (0, 0),
12563                        groups: 1,
12564                    },
12565                ),
12566                inputs: vec![x, w],
12567                shape: Shape::from_dims(&[1, 1, 2, 2]),
12568                dtype: DType::F64,
12569            });
12570            g.set_target_backend(c, BackendId::Cpu);
12571            (x, w, c)
12572        };
12573        let mut inputs = StorageCache::new();
12574        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12575        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12576        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12577        let guard = result_arc.read().unwrap();
12578        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12579            panic!("expected Cpu storage");
12580        };
12581        assert_eq!(c.as_slice::<f64>().unwrap(), &[12.0, 16.0, 24.0, 28.0]);
12582    }
12583
12584    /// E2E: Conv2D in BF16 — f32-accumulator path. Tolerant compare.
12585    #[test]
12586    fn pipelined_realize_conv2d_bf16() {
12587        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]
12588            .iter()
12589            .map(|v| half::bf16::from_f32(*v))
12590            .collect();
12591        let w_data: Vec<half::bf16> = [1.0_f32, 1.0, 1.0, 1.0]
12592            .iter()
12593            .map(|v| half::bf16::from_f32(*v))
12594            .collect();
12595        let x_storage = fuel_memory::from_slice_cpu(&x_data);
12596        let w_storage = fuel_memory::from_slice_cpu(&w_data);
12597
12598        let graph = Arc::new(RwLock::new(Graph::new()));
12599        let (x_id, w_id, c_id) = {
12600            let mut g = graph.write().unwrap();
12601            let x = g.push(Node {
12602                op: Op::Const,
12603                inputs: vec![],
12604                shape: Shape::from_dims(&[1, 1, 3, 3]),
12605                dtype: DType::BF16,
12606            });
12607            let w = g.push(Node {
12608                op: Op::Const,
12609                inputs: vec![],
12610                shape: Shape::from_dims(&[1, 1, 2, 2]),
12611                dtype: DType::BF16,
12612            });
12613            let c = g.push(Node {
12614                op: Op::Fused(
12615                    fuel_graph::registry::FusedOps::CONV2D,
12616                    fuel_graph::registry::FusedOpParams::Conv2D {
12617                        stride: (1, 1),
12618                        padding: (0, 0),
12619                        groups: 1,
12620                    },
12621                ),
12622                inputs: vec![x, w],
12623                shape: Shape::from_dims(&[1, 1, 2, 2]),
12624                dtype: DType::BF16,
12625            });
12626            g.set_target_backend(c, BackendId::Cpu);
12627            (x, w, c)
12628        };
12629        let mut inputs = StorageCache::new();
12630        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12631        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12632        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12633        let guard = result_arc.read().unwrap();
12634        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12635            panic!("expected Cpu storage");
12636        };
12637        let got: Vec<f32> = c
12638            .as_slice::<half::bf16>()
12639            .unwrap()
12640            .iter()
12641            .map(|v| v.to_f32())
12642            .collect();
12643        let want = [12.0_f32, 16.0, 24.0, 28.0];
12644        for (g, w) in got.iter().zip(want.iter()) {
12645            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
12646        }
12647    }
12648
12649    /// E2E: Conv2D in F16 — f32-accumulator path. Tolerant compare.
12650    #[test]
12651    fn pipelined_realize_conv2d_f16() {
12652        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]
12653            .iter()
12654            .map(|v| half::f16::from_f32(*v))
12655            .collect();
12656        let w_data: Vec<half::f16> = [1.0_f32, 1.0, 1.0, 1.0]
12657            .iter()
12658            .map(|v| half::f16::from_f32(*v))
12659            .collect();
12660        let x_storage = fuel_memory::from_slice_cpu(&x_data);
12661        let w_storage = fuel_memory::from_slice_cpu(&w_data);
12662
12663        let graph = Arc::new(RwLock::new(Graph::new()));
12664        let (x_id, w_id, c_id) = {
12665            let mut g = graph.write().unwrap();
12666            let x = g.push(Node {
12667                op: Op::Const,
12668                inputs: vec![],
12669                shape: Shape::from_dims(&[1, 1, 3, 3]),
12670                dtype: DType::F16,
12671            });
12672            let w = g.push(Node {
12673                op: Op::Const,
12674                inputs: vec![],
12675                shape: Shape::from_dims(&[1, 1, 2, 2]),
12676                dtype: DType::F16,
12677            });
12678            let c = g.push(Node {
12679                op: Op::Fused(
12680                    fuel_graph::registry::FusedOps::CONV2D,
12681                    fuel_graph::registry::FusedOpParams::Conv2D {
12682                        stride: (1, 1),
12683                        padding: (0, 0),
12684                        groups: 1,
12685                    },
12686                ),
12687                inputs: vec![x, w],
12688                shape: Shape::from_dims(&[1, 1, 2, 2]),
12689                dtype: DType::F16,
12690            });
12691            g.set_target_backend(c, BackendId::Cpu);
12692            (x, w, c)
12693        };
12694        let mut inputs = StorageCache::new();
12695        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12696        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12697        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12698        let guard = result_arc.read().unwrap();
12699        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12700            panic!("expected Cpu storage");
12701        };
12702        let got: Vec<f32> = c
12703            .as_slice::<half::f16>()
12704            .unwrap()
12705            .iter()
12706            .map(|v| v.to_f32())
12707            .collect();
12708        let want = [12.0_f32, 16.0, 24.0, 28.0];
12709        for (g, w) in got.iter().zip(want.iter()) {
12710            assert!((g - w).abs() < 0.05, "got {got:?} want {want:?}");
12711        }
12712    }
12713
12714    /// E2E: Op::PagedAttn — F32, single-head, B=1, Sq=1.
12715    /// Same setup as the FlashAttn smoke test, but the K/V live in a
12716    /// paged cache that we look up via block_table.
12717    /// Layout:
12718    ///   block_size=2, num_blocks=1, max_blocks_per_seq=1.
12719    ///   k_cache shape [1, 2, 1, 2] = num_blocks × block_size × Hkv × D.
12720    ///   k_cache[block 0, slot 0, h 0] = [1, 0]
12721    ///   k_cache[block 0, slot 1, h 0] = [0, 1]
12722    ///   v_cache values: [10, 0] / [0, 10]
12723    ///   block_table[b=0, logical_block 0] = 0 (physical)
12724    ///   context_lens[0] = 2
12725    ///   q[0, 0, 0] = [2, 0]
12726    /// Causal is implicit (q_pos = ctx_len - Sq + sq = 2 - 1 + 0 = 1, both keys admissible).
12727    /// Same softmax math as FlashAttn → ~[8.808, 1.192].
12728    #[test]
12729    fn pipelined_realize_paged_attn_f32() {
12730        let q = fuel_memory::from_slice_cpu(&[2.0_f32, 0.0]);
12731        let k_cache = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
12732        let v_cache = fuel_memory::from_slice_cpu(&[10.0_f32, 0.0, 0.0, 10.0]);
12733        let block_table_u32 = fuel_memory::Storage::new(
12734            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
12735                0_u32,
12736            ])),
12737            DType::U32,
12738        );
12739        let context_lens_u32 = fuel_memory::Storage::new(
12740            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
12741                2_u32,
12742            ])),
12743            DType::U32,
12744        );
12745        let graph = Arc::new(RwLock::new(Graph::new()));
12746        let (q_id, kc_id, vc_id, bt_id, cl_id, op_id) = {
12747            let mut g = graph.write().unwrap();
12748            let q = g.push(Node {
12749                op: Op::Const,
12750                inputs: vec![],
12751                shape: Shape::from_dims(&[1, 1, 1, 2]),
12752                dtype: DType::F32,
12753            });
12754            let kc = g.push(Node {
12755                op: Op::Const,
12756                inputs: vec![],
12757                shape: Shape::from_dims(&[1, 2, 1, 2]),
12758                dtype: DType::F32,
12759            });
12760            let vc = g.push(Node {
12761                op: Op::Const,
12762                inputs: vec![],
12763                shape: Shape::from_dims(&[1, 2, 1, 2]),
12764                dtype: DType::F32,
12765            });
12766            let bt = g.push(Node {
12767                op: Op::Const,
12768                inputs: vec![],
12769                shape: Shape::from_dims(&[1, 1]),
12770                dtype: DType::U32,
12771            });
12772            let cl = g.push(Node {
12773                op: Op::Const,
12774                inputs: vec![],
12775                shape: Shape::from_dims(&[1]),
12776                dtype: DType::U32,
12777            });
12778            let op = g.push(Node {
12779                op: Op::Fused(
12780                    fuel_graph::registry::FusedOps::PAGED_ATTN,
12781                    fuel_graph::registry::FusedOpParams::PagedAttn {
12782                        softmax_scale: 1.0,
12783                        block_size: 2,
12784                        softcap: None,
12785                    },
12786                ),
12787                inputs: vec![q, kc, vc, bt, cl],
12788                shape: Shape::from_dims(&[1, 1, 1, 2]),
12789                dtype: DType::F32,
12790            });
12791            g.set_target_backend(op, BackendId::Cpu);
12792            (q, kc, vc, bt, cl, op)
12793        };
12794        let mut inputs = StorageCache::new();
12795        inputs.insert(q_id, Arc::new(RwLock::new(q)));
12796        inputs.insert(kc_id, Arc::new(RwLock::new(k_cache)));
12797        inputs.insert(vc_id, Arc::new(RwLock::new(v_cache)));
12798        inputs.insert(bt_id, Arc::new(RwLock::new(block_table_u32)));
12799        inputs.insert(cl_id, Arc::new(RwLock::new(context_lens_u32)));
12800        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12801        let guard = result_arc.read().unwrap();
12802        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12803            panic!("expected Cpu storage");
12804        };
12805        let r = c.as_slice::<f32>().unwrap();
12806        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
12807        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
12808        assert!(
12809            (r[0] - 10.0 * expected_p0).abs() < 1e-5,
12810            "row[0]: got {} expected {}",
12811            r[0],
12812            10.0 * expected_p0
12813        );
12814        assert!(
12815            (r[1] - 10.0 * expected_p1).abs() < 1e-5,
12816            "row[1]: got {} expected {}",
12817            r[1],
12818            10.0 * expected_p1
12819        );
12820    }
12821
12822    /// E2E: PagedAttn BF16 — same single-row test, tolerant.
12823    #[test]
12824    fn pipelined_realize_paged_attn_bf16() {
12825        let q_v: Vec<half::bf16> = [2.0_f32, 0.0]
12826            .iter()
12827            .map(|x| half::bf16::from_f32(*x))
12828            .collect();
12829        let kc_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0]
12830            .iter()
12831            .map(|x| half::bf16::from_f32(*x))
12832            .collect();
12833        let vc_v: Vec<half::bf16> = [10.0_f32, 0.0, 0.0, 10.0]
12834            .iter()
12835            .map(|x| half::bf16::from_f32(*x))
12836            .collect();
12837        let q = fuel_memory::from_slice_cpu(&q_v);
12838        let k_cache = fuel_memory::from_slice_cpu(&kc_v);
12839        let v_cache = fuel_memory::from_slice_cpu(&vc_v);
12840        let bt = fuel_memory::Storage::new(
12841            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
12842                0_u32,
12843            ])),
12844            DType::U32,
12845        );
12846        let cl = fuel_memory::Storage::new(
12847            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
12848                2_u32,
12849            ])),
12850            DType::U32,
12851        );
12852        let graph = Arc::new(RwLock::new(Graph::new()));
12853        let (q_id, kc_id, vc_id, bt_id, cl_id, op_id) = {
12854            let mut g = graph.write().unwrap();
12855            let q = g.push(Node {
12856                op: Op::Const,
12857                inputs: vec![],
12858                shape: Shape::from_dims(&[1, 1, 1, 2]),
12859                dtype: DType::BF16,
12860            });
12861            let kc = g.push(Node {
12862                op: Op::Const,
12863                inputs: vec![],
12864                shape: Shape::from_dims(&[1, 2, 1, 2]),
12865                dtype: DType::BF16,
12866            });
12867            let vc = g.push(Node {
12868                op: Op::Const,
12869                inputs: vec![],
12870                shape: Shape::from_dims(&[1, 2, 1, 2]),
12871                dtype: DType::BF16,
12872            });
12873            let bt = g.push(Node {
12874                op: Op::Const,
12875                inputs: vec![],
12876                shape: Shape::from_dims(&[1, 1]),
12877                dtype: DType::U32,
12878            });
12879            let cl = g.push(Node {
12880                op: Op::Const,
12881                inputs: vec![],
12882                shape: Shape::from_dims(&[1]),
12883                dtype: DType::U32,
12884            });
12885            let op = g.push(Node {
12886                op: Op::Fused(
12887                    fuel_graph::registry::FusedOps::PAGED_ATTN,
12888                    fuel_graph::registry::FusedOpParams::PagedAttn {
12889                        softmax_scale: 1.0,
12890                        block_size: 2,
12891                        softcap: None,
12892                    },
12893                ),
12894                inputs: vec![q, kc, vc, bt, cl],
12895                shape: Shape::from_dims(&[1, 1, 1, 2]),
12896                dtype: DType::BF16,
12897            });
12898            g.set_target_backend(op, BackendId::Cpu);
12899            (q, kc, vc, bt, cl, op)
12900        };
12901        let mut inputs = StorageCache::new();
12902        inputs.insert(q_id, Arc::new(RwLock::new(q)));
12903        inputs.insert(kc_id, Arc::new(RwLock::new(k_cache)));
12904        inputs.insert(vc_id, Arc::new(RwLock::new(v_cache)));
12905        inputs.insert(bt_id, Arc::new(RwLock::new(bt)));
12906        inputs.insert(cl_id, Arc::new(RwLock::new(cl)));
12907        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12908        let guard = result_arc.read().unwrap();
12909        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12910            panic!("expected Cpu storage");
12911        };
12912        let got: Vec<f32> = c
12913            .as_slice::<half::bf16>()
12914            .unwrap()
12915            .iter()
12916            .map(|v| v.to_f32())
12917            .collect();
12918        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
12919        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
12920        let want = [10.0 * expected_p0, 10.0 * expected_p1];
12921        for (g, w) in got.iter().zip(want.iter()) {
12922            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
12923        }
12924    }
12925
12926    /// E2E: Op::FlashAttn — F32 single-head, single-batch, no mask.
12927    /// q = [[2.0, 0.0]], k = [[1.0, 0.0], [0.0, 1.0]], v = [[10, 0], [0, 10]]
12928    /// scale = 1.0
12929    /// scores = q · kᵀ = [2.0, 0.0]
12930    /// softmax = [e^2/(e^2+1), 1/(e^2+1)] ≈ [0.8808, 0.1192]
12931    /// out = softmax @ v = [10*0.8808, 10*0.1192] ≈ [8.808, 1.192]
12932    #[test]
12933    fn pipelined_realize_flash_attn_f32() {
12934        // [B=1, H=1, S=1or2, D=2]
12935        let q = fuel_memory::from_slice_cpu(&[2.0_f32, 0.0]);
12936        let k = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
12937        let v = fuel_memory::from_slice_cpu(&[10.0_f32, 0.0, 0.0, 10.0]);
12938        let graph = Arc::new(RwLock::new(Graph::new()));
12939        let (q_id, k_id, v_id, op_id) = {
12940            let mut g = graph.write().unwrap();
12941            let q = g.push(Node {
12942                op: Op::Const,
12943                inputs: vec![],
12944                shape: Shape::from_dims(&[1, 1, 1, 2]),
12945                dtype: DType::F32,
12946            });
12947            let k = g.push(Node {
12948                op: Op::Const,
12949                inputs: vec![],
12950                shape: Shape::from_dims(&[1, 1, 2, 2]),
12951                dtype: DType::F32,
12952            });
12953            let v = g.push(Node {
12954                op: Op::Const,
12955                inputs: vec![],
12956                shape: Shape::from_dims(&[1, 1, 2, 2]),
12957                dtype: DType::F32,
12958            });
12959            let op = g.push(Node {
12960                op: Op::Fused(
12961                    fuel_graph::registry::FusedOps::FLASH_ATTN,
12962                    fuel_graph::registry::FusedOpParams::FlashAttn {
12963                        softmax_scale: 1.0,
12964                        causal: false,
12965                        window_size_left: None,
12966                        window_size_right: None,
12967                        softcap: None,
12968                        k_len: None,
12969                    },
12970                ),
12971                inputs: vec![q, k, v],
12972                shape: Shape::from_dims(&[1, 1, 1, 2]),
12973                dtype: DType::F32,
12974            });
12975            g.set_target_backend(op, BackendId::Cpu);
12976            (q, k, v, op)
12977        };
12978        let mut inputs = StorageCache::new();
12979        inputs.insert(q_id, Arc::new(RwLock::new(q)));
12980        inputs.insert(k_id, Arc::new(RwLock::new(k)));
12981        inputs.insert(v_id, Arc::new(RwLock::new(v)));
12982        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12983        let guard = result_arc.read().unwrap();
12984        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12985            panic!("expected Cpu storage");
12986        };
12987        let r = c.as_slice::<f32>().unwrap();
12988        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
12989        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
12990        assert!(
12991            (r[0] - 10.0 * expected_p0).abs() < 1e-5,
12992            "row[0]: got {} expected {}",
12993            r[0],
12994            10.0 * expected_p0
12995        );
12996        assert!(
12997            (r[1] - 10.0 * expected_p1).abs() < 1e-5,
12998            "row[1]: got {} expected {}",
12999            r[1],
13000            10.0 * expected_p1
13001        );
13002    }
13003
13004    /// E2E: FlashAttn with causal mask — second query position
13005    /// attends to both keys (positions 0 and 1), first only attends
13006    /// to key 0 (everything beyond is masked).
13007    #[test]
13008    fn pipelined_realize_flash_attn_causal_f32() {
13009        // q [1,1,2,2]: query 0 = [1, 0], query 1 = [0, 1]
13010        // k [1,1,2,2]: keys = [[1, 0], [0, 1]]
13011        // v [1,1,2,2]: values = [[5, 6], [7, 8]]
13012        // softmax_scale=1, causal:
13013        //   query 0: only key 0 admissible → out = v[0] = [5, 6]
13014        //   query 1: both admissible. scores = q1·k = [0, 1]
13015        //            softmax = [1/(e+1), e/(e+1)]
13016        //            out = scores · v = [(5)/(e+1) + 7e/(e+1), 6/(e+1) + 8e/(e+1)]
13017        let q = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13018        let k = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13019        let v = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0, 7.0, 8.0]);
13020        let graph = Arc::new(RwLock::new(Graph::new()));
13021        let (q_id, k_id, v_id, op_id) = {
13022            let mut g = graph.write().unwrap();
13023            let q = g.push(Node {
13024                op: Op::Const,
13025                inputs: vec![],
13026                shape: Shape::from_dims(&[1, 1, 2, 2]),
13027                dtype: DType::F32,
13028            });
13029            let k = g.push(Node {
13030                op: Op::Const,
13031                inputs: vec![],
13032                shape: Shape::from_dims(&[1, 1, 2, 2]),
13033                dtype: DType::F32,
13034            });
13035            let v = g.push(Node {
13036                op: Op::Const,
13037                inputs: vec![],
13038                shape: Shape::from_dims(&[1, 1, 2, 2]),
13039                dtype: DType::F32,
13040            });
13041            let op = g.push(Node {
13042                op: Op::Fused(
13043                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13044                    fuel_graph::registry::FusedOpParams::FlashAttn {
13045                        softmax_scale: 1.0,
13046                        causal: true,
13047                        window_size_left: None,
13048                        window_size_right: None,
13049                        softcap: None,
13050                        k_len: None,
13051                    },
13052                ),
13053                inputs: vec![q, k, v],
13054                shape: Shape::from_dims(&[1, 1, 2, 2]),
13055                dtype: DType::F32,
13056            });
13057            g.set_target_backend(op, BackendId::Cpu);
13058            (q, k, v, op)
13059        };
13060        let mut inputs = StorageCache::new();
13061        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13062        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13063        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13064        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13065        let guard = result_arc.read().unwrap();
13066        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13067            panic!("expected Cpu storage");
13068        };
13069        let r = c.as_slice::<f32>().unwrap();
13070        // Query 0 sees only key 0 → output = v[0]
13071        assert!((r[0] - 5.0).abs() < 1e-5, "got {}", r[0]);
13072        assert!((r[1] - 6.0).abs() < 1e-5, "got {}", r[1]);
13073        // Query 1 sees both. softmax([0, 1]) = [1/(e+1), e/(e+1)]
13074        let denom = (1.0_f32).exp() + 1.0;
13075        let expected_a = 5.0 / denom + 7.0 * (1.0_f32).exp() / denom;
13076        let expected_b = 6.0 / denom + 8.0 * (1.0_f32).exp() / denom;
13077        assert!(
13078            (r[2] - expected_a).abs() < 1e-5,
13079            "row1[0]: got {} expected {}",
13080            r[2],
13081            expected_a
13082        );
13083        assert!(
13084            (r[3] - expected_b).abs() < 1e-5,
13085            "row1[1]: got {} expected {}",
13086            r[3],
13087            expected_b
13088        );
13089    }
13090
13091    /// E2E: FlashAttn over a fixed-**capacity** K/V with a runtime
13092    /// `k_len` resolved through a `SymEnv` (Phase D symbolic extents).
13093    /// Only the first `k_len` rows are attended; trailing "poison" rows
13094    /// in the capacity buffer are ignored, and the causal mask is
13095    /// bottom-right-aligned at offset `k_len - Sq`. This is flash decode
13096    /// over a persistent KV-cache: K/V are `[.., max_seq, ..]` capacity
13097    /// and the live prefix grows per token.
13098    #[test]
13099    fn pipelined_realize_flash_attn_dynamic_k_len() {
13100        use fuel_ir::{DynScalar, SymId};
13101        // q [1,1,2,2]; K/V capacity [1,1,4,2]; bind k_len = 3 so row 3
13102        // (the "poison" row) is never attended.
13103        let q = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13104        let k = fuel_memory::from_slice_cpu(&[
13105            1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0, 100.0,
13106            100.0, // poison row 3 — must be ignored (k_len=3)
13107        ]);
13108        let v = fuel_memory::from_slice_cpu(&[
13109            5.0_f32, 6.0, 7.0, 8.0, 9.0, 10.0, 999.0,
13110            999.0, // poison row 3 — must be ignored
13111        ]);
13112        let sym = SymId(0);
13113        let graph = Arc::new(RwLock::new(Graph::new()));
13114        let (q_id, k_id, v_id, op_id) = {
13115            let mut g = graph.write().unwrap();
13116            let q = g.push(Node {
13117                op: Op::Const,
13118                inputs: vec![],
13119                shape: Shape::from_dims(&[1, 1, 2, 2]),
13120                dtype: DType::F32,
13121            });
13122            let k = g.push(Node {
13123                op: Op::Const,
13124                inputs: vec![],
13125                shape: Shape::from_dims(&[1, 1, 4, 2]),
13126                dtype: DType::F32,
13127            });
13128            let v = g.push(Node {
13129                op: Op::Const,
13130                inputs: vec![],
13131                shape: Shape::from_dims(&[1, 1, 4, 2]),
13132                dtype: DType::F32,
13133            });
13134            let op = g.push(Node {
13135                op: Op::Fused(
13136                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13137                    fuel_graph::registry::FusedOpParams::FlashAttn {
13138                        softmax_scale: 1.0,
13139                        causal: true,
13140                        window_size_left: None,
13141                        window_size_right: None,
13142                        softcap: None,
13143                        k_len: Some(DynScalar::Sym(sym)),
13144                    },
13145                ),
13146                inputs: vec![q, k, v],
13147                shape: Shape::from_dims(&[1, 1, 2, 2]),
13148                dtype: DType::F32,
13149            });
13150            g.set_target_backend(op, BackendId::Cpu);
13151            (q, k, v, op)
13152        };
13153        let mut inputs = StorageCache::new();
13154        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13155        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13156        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13157        let mut env = SymEnv::new();
13158        env.bind(sym, 3).unwrap();
13159        let (result_arc, _) = PipelinedExecutor::realize_with_env(graph, op_id, inputs, env)
13160            .expect("realize_with_env");
13161        let guard = result_arc.read().unwrap();
13162        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13163            panic!("expected Cpu storage");
13164        };
13165        let r = c.as_slice::<f32>().unwrap();
13166        let e = 1.0_f32.exp();
13167        // causal_offset = k_len - Sq = 3 - 2 = 1.
13168        // Query 0 (abs pos 1): keys {0,1}. scores [1,0] → softmax [e,1]/(e+1).
13169        let d0 = e + 1.0;
13170        let e0x = (5.0 * e + 7.0) / d0;
13171        let e0y = (6.0 * e + 8.0) / d0;
13172        // Query 1 (abs pos 2): keys {0,1,2}. scores [0,1,1] → [1,e,e]/(1+2e).
13173        let d1 = 1.0 + 2.0 * e;
13174        let e1x = (5.0 + 7.0 * e + 9.0 * e) / d1;
13175        let e1y = (6.0 + 8.0 * e + 10.0 * e) / d1;
13176        for (got, want) in r.iter().zip([e0x, e0y, e1x, e1y].iter()) {
13177            assert!(
13178                (got - want).abs() < 1e-4,
13179                "flash dyn k_len: got {got}, want {want} (full output {r:?}); \
13180                 a poison-contaminated value means the capacity rows past k_len leaked in",
13181            );
13182        }
13183    }
13184
13185    /// A flash `k_len` symbol unbound in the `SymEnv` surfaces a typed
13186    /// error at realize (never a panic).
13187    #[test]
13188    fn pipelined_realize_flash_attn_dynamic_k_len_unbound_errors() {
13189        use fuel_ir::{DynScalar, SymId};
13190        let q = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13191        let k = fuel_memory::from_slice_cpu(&[0.0_f32; 16]);
13192        let v = fuel_memory::from_slice_cpu(&[0.0_f32; 16]);
13193        let graph = Arc::new(RwLock::new(Graph::new()));
13194        let (q_id, k_id, v_id, op_id) = {
13195            let mut g = graph.write().unwrap();
13196            let q = g.push(Node {
13197                op: Op::Const,
13198                inputs: vec![],
13199                shape: Shape::from_dims(&[1, 1, 2, 2]),
13200                dtype: DType::F32,
13201            });
13202            let k = g.push(Node {
13203                op: Op::Const,
13204                inputs: vec![],
13205                shape: Shape::from_dims(&[1, 1, 4, 2]),
13206                dtype: DType::F32,
13207            });
13208            let v = g.push(Node {
13209                op: Op::Const,
13210                inputs: vec![],
13211                shape: Shape::from_dims(&[1, 1, 4, 2]),
13212                dtype: DType::F32,
13213            });
13214            let op = g.push(Node {
13215                op: Op::Fused(
13216                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13217                    fuel_graph::registry::FusedOpParams::FlashAttn {
13218                        softmax_scale: 1.0,
13219                        causal: true,
13220                        window_size_left: None,
13221                        window_size_right: None,
13222                        softcap: None,
13223                        k_len: Some(DynScalar::Sym(SymId(0))),
13224                    },
13225                ),
13226                inputs: vec![q, k, v],
13227                shape: Shape::from_dims(&[1, 1, 2, 2]),
13228                dtype: DType::F32,
13229            });
13230            g.set_target_backend(op, BackendId::Cpu);
13231            (q, k, v, op)
13232        };
13233        let mut inputs = StorageCache::new();
13234        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13235        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13236        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13237        // Empty env — the k_len symbol is unbound.
13238        let result = PipelinedExecutor::realize_with_env(graph, op_id, inputs, SymEnv::new());
13239        assert!(
13240            result.is_err(),
13241            "unbound flash k_len symbol must surface a typed error"
13242        );
13243    }
13244
13245    /// E2E: FlashAttn BF16 — same single-row test as f32, tolerant.
13246    #[test]
13247    fn pipelined_realize_flash_attn_bf16() {
13248        let q_v: Vec<half::bf16> = [2.0_f32, 0.0]
13249            .iter()
13250            .map(|x| half::bf16::from_f32(*x))
13251            .collect();
13252        let k_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0]
13253            .iter()
13254            .map(|x| half::bf16::from_f32(*x))
13255            .collect();
13256        let v_v: Vec<half::bf16> = [10.0_f32, 0.0, 0.0, 10.0]
13257            .iter()
13258            .map(|x| half::bf16::from_f32(*x))
13259            .collect();
13260        let q = fuel_memory::from_slice_cpu(&q_v);
13261        let k = fuel_memory::from_slice_cpu(&k_v);
13262        let v = fuel_memory::from_slice_cpu(&v_v);
13263        let graph = Arc::new(RwLock::new(Graph::new()));
13264        let (q_id, k_id, v_id, op_id) = {
13265            let mut g = graph.write().unwrap();
13266            let q = g.push(Node {
13267                op: Op::Const,
13268                inputs: vec![],
13269                shape: Shape::from_dims(&[1, 1, 1, 2]),
13270                dtype: DType::BF16,
13271            });
13272            let k = g.push(Node {
13273                op: Op::Const,
13274                inputs: vec![],
13275                shape: Shape::from_dims(&[1, 1, 2, 2]),
13276                dtype: DType::BF16,
13277            });
13278            let v = g.push(Node {
13279                op: Op::Const,
13280                inputs: vec![],
13281                shape: Shape::from_dims(&[1, 1, 2, 2]),
13282                dtype: DType::BF16,
13283            });
13284            let op = g.push(Node {
13285                op: Op::Fused(
13286                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13287                    fuel_graph::registry::FusedOpParams::FlashAttn {
13288                        softmax_scale: 1.0,
13289                        causal: false,
13290                        window_size_left: None,
13291                        window_size_right: None,
13292                        softcap: None,
13293                        k_len: None,
13294                    },
13295                ),
13296                inputs: vec![q, k, v],
13297                shape: Shape::from_dims(&[1, 1, 1, 2]),
13298                dtype: DType::BF16,
13299            });
13300            g.set_target_backend(op, BackendId::Cpu);
13301            (q, k, v, op)
13302        };
13303        let mut inputs = StorageCache::new();
13304        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13305        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13306        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13307        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13308        let guard = result_arc.read().unwrap();
13309        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13310            panic!("expected Cpu storage");
13311        };
13312        let got: Vec<f32> = c
13313            .as_slice::<half::bf16>()
13314            .unwrap()
13315            .iter()
13316            .map(|v| v.to_f32())
13317            .collect();
13318        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
13319        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
13320        let want = [10.0 * expected_p0, 10.0 * expected_p1];
13321        for (g, w) in got.iter().zip(want.iter()) {
13322            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
13323        }
13324    }
13325
13326    /// E2E: Op::FusedLinear — F32. a[1,2,3] @ b[1,3,2] + bias[2].
13327    /// a = [[[1,2,3],[4,5,6]]], b = [[[1,0],[0,1],[1,1]]], bias=[10,20]
13328    /// matmul = [[1+0+3, 0+2+3], [4+0+6, 0+5+6]] = [[4, 5], [10, 11]]
13329    /// + bias = [[14, 25], [20, 31]]
13330    #[test]
13331    fn pipelined_realize_fused_linear_f32() {
13332        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
13333        let b = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0]);
13334        let bias = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
13335        let graph = Arc::new(RwLock::new(Graph::new()));
13336        let (a_id, b_id, bias_id, op_id) = {
13337            let mut g = graph.write().unwrap();
13338            let a = g.push(Node {
13339                op: Op::Const,
13340                inputs: vec![],
13341                shape: Shape::from_dims(&[1, 2, 3]),
13342                dtype: DType::F32,
13343            });
13344            let b = g.push(Node {
13345                op: Op::Const,
13346                inputs: vec![],
13347                shape: Shape::from_dims(&[1, 3, 2]),
13348                dtype: DType::F32,
13349            });
13350            let bias = g.push(Node {
13351                op: Op::Const,
13352                inputs: vec![],
13353                shape: Shape::from_dims(&[2]),
13354                dtype: DType::F32,
13355            });
13356            let op = g.push(Node {
13357                op: Op::Fused(
13358                    fuel_graph::registry::FusedOps::FUSED_LINEAR,
13359                    fuel_graph::registry::FusedOpParams::FusedLinear,
13360                ),
13361                inputs: vec![a, b, bias],
13362                shape: Shape::from_dims(&[1, 2, 2]),
13363                dtype: DType::F32,
13364            });
13365            g.set_target_backend(op, BackendId::Cpu);
13366            (a, b, bias, op)
13367        };
13368        let mut inputs = StorageCache::new();
13369        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13370        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13371        inputs.insert(bias_id, Arc::new(RwLock::new(bias)));
13372        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13373        let guard = result_arc.read().unwrap();
13374        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13375            panic!("expected Cpu storage");
13376        };
13377        assert_eq!(c.as_slice::<f32>().unwrap(), &[14.0, 25.0, 20.0, 31.0]);
13378    }
13379
13380    /// E2E: FusedLinear F64 — same shape test on doubles.
13381    #[test]
13382    fn pipelined_realize_fused_linear_f64() {
13383        let a = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
13384        let b = fuel_memory::from_slice_cpu(&[1.0_f64, 0.0, 0.0, 1.0, 1.0, 1.0]);
13385        let bias = fuel_memory::from_slice_cpu(&[10.0_f64, 20.0]);
13386        let graph = Arc::new(RwLock::new(Graph::new()));
13387        let (a_id, b_id, bias_id, op_id) = {
13388            let mut g = graph.write().unwrap();
13389            let a = g.push(Node {
13390                op: Op::Const,
13391                inputs: vec![],
13392                shape: Shape::from_dims(&[1, 2, 3]),
13393                dtype: DType::F64,
13394            });
13395            let b = g.push(Node {
13396                op: Op::Const,
13397                inputs: vec![],
13398                shape: Shape::from_dims(&[1, 3, 2]),
13399                dtype: DType::F64,
13400            });
13401            let bias = g.push(Node {
13402                op: Op::Const,
13403                inputs: vec![],
13404                shape: Shape::from_dims(&[2]),
13405                dtype: DType::F64,
13406            });
13407            let op = g.push(Node {
13408                op: Op::Fused(
13409                    fuel_graph::registry::FusedOps::FUSED_LINEAR,
13410                    fuel_graph::registry::FusedOpParams::FusedLinear,
13411                ),
13412                inputs: vec![a, b, bias],
13413                shape: Shape::from_dims(&[1, 2, 2]),
13414                dtype: DType::F64,
13415            });
13416            g.set_target_backend(op, BackendId::Cpu);
13417            (a, b, bias, op)
13418        };
13419        let mut inputs = StorageCache::new();
13420        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13421        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13422        inputs.insert(bias_id, Arc::new(RwLock::new(bias)));
13423        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13424        let guard = result_arc.read().unwrap();
13425        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13426            panic!("expected Cpu storage");
13427        };
13428        assert_eq!(c.as_slice::<f64>().unwrap(), &[14.0, 25.0, 20.0, 31.0]);
13429    }
13430
13431    /// E2E: FusedLinear BF16 — tolerant compare.
13432    #[test]
13433    fn pipelined_realize_fused_linear_bf16() {
13434        let a_v: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]
13435            .iter()
13436            .map(|x| half::bf16::from_f32(*x))
13437            .collect();
13438        let b_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0]
13439            .iter()
13440            .map(|x| half::bf16::from_f32(*x))
13441            .collect();
13442        let bias_v: Vec<half::bf16> = [10.0_f32, 20.0]
13443            .iter()
13444            .map(|x| half::bf16::from_f32(*x))
13445            .collect();
13446        let a = fuel_memory::from_slice_cpu(&a_v);
13447        let b = fuel_memory::from_slice_cpu(&b_v);
13448        let bias = fuel_memory::from_slice_cpu(&bias_v);
13449        let graph = Arc::new(RwLock::new(Graph::new()));
13450        let (a_id, b_id, bias_id, op_id) = {
13451            let mut g = graph.write().unwrap();
13452            let a = g.push(Node {
13453                op: Op::Const,
13454                inputs: vec![],
13455                shape: Shape::from_dims(&[1, 2, 3]),
13456                dtype: DType::BF16,
13457            });
13458            let b = g.push(Node {
13459                op: Op::Const,
13460                inputs: vec![],
13461                shape: Shape::from_dims(&[1, 3, 2]),
13462                dtype: DType::BF16,
13463            });
13464            let bias = g.push(Node {
13465                op: Op::Const,
13466                inputs: vec![],
13467                shape: Shape::from_dims(&[2]),
13468                dtype: DType::BF16,
13469            });
13470            let op = g.push(Node {
13471                op: Op::Fused(
13472                    fuel_graph::registry::FusedOps::FUSED_LINEAR,
13473                    fuel_graph::registry::FusedOpParams::FusedLinear,
13474                ),
13475                inputs: vec![a, b, bias],
13476                shape: Shape::from_dims(&[1, 2, 2]),
13477                dtype: DType::BF16,
13478            });
13479            g.set_target_backend(op, BackendId::Cpu);
13480            (a, b, bias, op)
13481        };
13482        let mut inputs = StorageCache::new();
13483        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13484        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13485        inputs.insert(bias_id, Arc::new(RwLock::new(bias)));
13486        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13487        let guard = result_arc.read().unwrap();
13488        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13489            panic!("expected Cpu storage");
13490        };
13491        let got: Vec<f32> = c
13492            .as_slice::<half::bf16>()
13493            .unwrap()
13494            .iter()
13495            .map(|v| v.to_f32())
13496            .collect();
13497        let want = [14.0_f32, 25.0, 20.0, 31.0];
13498        for (g, w) in got.iter().zip(want.iter()) {
13499            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
13500        }
13501    }
13502
13503    /// E2E: Op::ReduceSumTo — sum the leading axis of a [2,3] tensor.
13504    /// Input [[1,2,3],[4,5,6]] → output [5,7,9].
13505    #[test]
13506    fn pipelined_realize_reduce_sum_to_f32_drops_leading_axis() {
13507        let v = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
13508        let graph = Arc::new(RwLock::new(Graph::new()));
13509        let (in_id, op_id) = {
13510            let mut g = graph.write().unwrap();
13511            let in_id = g.push(Node {
13512                op: Op::Const,
13513                inputs: vec![],
13514                shape: Shape::from_dims(&[2, 3]),
13515                dtype: DType::F32,
13516            });
13517            let op_id = g.push(Node {
13518                op: Op::ReduceSumTo(Shape::from_dims(&[3])),
13519                inputs: vec![in_id],
13520                shape: Shape::from_dims(&[3]),
13521                dtype: DType::F32,
13522            });
13523            g.set_target_backend(op_id, BackendId::Cpu);
13524            (in_id, op_id)
13525        };
13526        let mut inputs = StorageCache::new();
13527        inputs.insert(in_id, Arc::new(RwLock::new(v)));
13528        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13529        let guard = result_arc.read().unwrap();
13530        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13531            panic!("expected Cpu storage");
13532        };
13533        assert_eq!(c.as_slice::<f32>().unwrap(), &[5.0, 7.0, 9.0]);
13534    }
13535
13536    /// E2E: Op::ReduceSumTo — keep-dim with 1 in the middle.
13537    /// Input [2,3,4] → [2,1,4] sums along dim 1.
13538    #[test]
13539    fn pipelined_realize_reduce_sum_to_f32_keepdim_middle() {
13540        // [2,3,4]: layer 0 = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
13541        //          layer 1 = [[13..16],[17..20],[21..24]]
13542        let mut v: Vec<f32> = (1..=24).map(|x| x as f32).collect();
13543        let _ = &mut v;
13544        let s = fuel_memory::from_slice_cpu(&v);
13545        let graph = Arc::new(RwLock::new(Graph::new()));
13546        let (in_id, op_id) = {
13547            let mut g = graph.write().unwrap();
13548            let in_id = g.push(Node {
13549                op: Op::Const,
13550                inputs: vec![],
13551                shape: Shape::from_dims(&[2, 3, 4]),
13552                dtype: DType::F32,
13553            });
13554            let op_id = g.push(Node {
13555                op: Op::ReduceSumTo(Shape::from_dims(&[2, 1, 4])),
13556                inputs: vec![in_id],
13557                shape: Shape::from_dims(&[2, 1, 4]),
13558                dtype: DType::F32,
13559            });
13560            g.set_target_backend(op_id, BackendId::Cpu);
13561            (in_id, op_id)
13562        };
13563        let mut inputs = StorageCache::new();
13564        inputs.insert(in_id, Arc::new(RwLock::new(s)));
13565        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13566        let guard = result_arc.read().unwrap();
13567        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13568            panic!("expected Cpu storage");
13569        };
13570        // layer0 dim1-sum: col j = 1+5+9, 2+6+10, 3+7+11, 4+8+12 = [15,18,21,24]
13571        // layer1 dim1-sum: col j = 13+17+21, 14+18+22, 15+19+23, 16+20+24 = [51,54,57,60]
13572        assert_eq!(
13573            c.as_slice::<f32>().unwrap(),
13574            &[15.0, 18.0, 21.0, 24.0, 51.0, 54.0, 57.0, 60.0],
13575        );
13576    }
13577
13578    /// E2E: ReduceSumTo F64 — same drop-leading-axis test on doubles.
13579    #[test]
13580    fn pipelined_realize_reduce_sum_to_f64() {
13581        let v = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
13582        let graph = Arc::new(RwLock::new(Graph::new()));
13583        let (in_id, op_id) = {
13584            let mut g = graph.write().unwrap();
13585            let in_id = g.push(Node {
13586                op: Op::Const,
13587                inputs: vec![],
13588                shape: Shape::from_dims(&[2, 3]),
13589                dtype: DType::F64,
13590            });
13591            let op_id = g.push(Node {
13592                op: Op::ReduceSumTo(Shape::from_dims(&[3])),
13593                inputs: vec![in_id],
13594                shape: Shape::from_dims(&[3]),
13595                dtype: DType::F64,
13596            });
13597            g.set_target_backend(op_id, BackendId::Cpu);
13598            (in_id, op_id)
13599        };
13600        let mut inputs = StorageCache::new();
13601        inputs.insert(in_id, Arc::new(RwLock::new(v)));
13602        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13603        let guard = result_arc.read().unwrap();
13604        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13605            panic!("expected Cpu storage");
13606        };
13607        assert_eq!(c.as_slice::<f64>().unwrap(), &[5.0, 7.0, 9.0]);
13608    }
13609
13610    /// E2E: Op::ReduceMaxTo F32 — drop the leading axis with max-reduce.
13611    #[test]
13612    fn pipelined_realize_reduce_max_to_f32_drops_leading_axis() {
13613        // Input [2,3]: row 0 = [1, 7, 3], row 1 = [4, 2, 6]. Max along
13614        // dim 0: [4, 7, 6].
13615        let v = fuel_memory::from_slice_cpu(&[1.0_f32, 7.0, 3.0, 4.0, 2.0, 6.0]);
13616        let graph = Arc::new(RwLock::new(Graph::new()));
13617        let (in_id, op_id) = {
13618            let mut g = graph.write().unwrap();
13619            let in_id = g.push(Node {
13620                op: Op::Const,
13621                inputs: vec![],
13622                shape: Shape::from_dims(&[2, 3]),
13623                dtype: DType::F32,
13624            });
13625            let op_id = g.push(Node {
13626                op: Op::ReduceMaxTo(Shape::from_dims(&[3])),
13627                inputs: vec![in_id],
13628                shape: Shape::from_dims(&[3]),
13629                dtype: DType::F32,
13630            });
13631            g.set_target_backend(op_id, BackendId::Cpu);
13632            (in_id, op_id)
13633        };
13634        let mut inputs = StorageCache::new();
13635        inputs.insert(in_id, Arc::new(RwLock::new(v)));
13636        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13637        let guard = result_arc.read().unwrap();
13638        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13639            panic!("expected Cpu storage");
13640        };
13641        assert_eq!(c.as_slice::<f32>().unwrap(), &[4.0, 7.0, 6.0]);
13642    }
13643
13644    /// E2E: Op::ReduceMaxTo F32 — keep-dim with 1 in the trailing axis.
13645    /// Mirrors the SoftmaxLastDim lowering's max-side shape: input
13646    /// [..., last] → [..., 1].
13647    #[test]
13648    fn pipelined_realize_reduce_max_to_f32_keepdim_trailing() {
13649        // Input [2, 3]: row maxes = [3, 6].
13650        let v = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
13651        let graph = Arc::new(RwLock::new(Graph::new()));
13652        let (in_id, op_id) = {
13653            let mut g = graph.write().unwrap();
13654            let in_id = g.push(Node {
13655                op: Op::Const,
13656                inputs: vec![],
13657                shape: Shape::from_dims(&[2, 3]),
13658                dtype: DType::F32,
13659            });
13660            let op_id = g.push(Node {
13661                op: Op::ReduceMaxTo(Shape::from_dims(&[2, 1])),
13662                inputs: vec![in_id],
13663                shape: Shape::from_dims(&[2, 1]),
13664                dtype: DType::F32,
13665            });
13666            g.set_target_backend(op_id, BackendId::Cpu);
13667            (in_id, op_id)
13668        };
13669        let mut inputs = StorageCache::new();
13670        inputs.insert(in_id, Arc::new(RwLock::new(v)));
13671        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13672        let guard = result_arc.read().unwrap();
13673        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13674            panic!("expected Cpu storage");
13675        };
13676        assert_eq!(c.as_slice::<f32>().unwrap(), &[3.0, 6.0]);
13677    }
13678
13679    /// E2E: ReduceSumTo BF16 — tolerant compare via f32-acc.
13680    #[test]
13681    fn pipelined_realize_reduce_sum_to_bf16() {
13682        let v: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]
13683            .iter()
13684            .map(|x| half::bf16::from_f32(*x))
13685            .collect();
13686        let s = fuel_memory::from_slice_cpu(&v);
13687        let graph = Arc::new(RwLock::new(Graph::new()));
13688        let (in_id, op_id) = {
13689            let mut g = graph.write().unwrap();
13690            let in_id = g.push(Node {
13691                op: Op::Const,
13692                inputs: vec![],
13693                shape: Shape::from_dims(&[2, 3]),
13694                dtype: DType::BF16,
13695            });
13696            let op_id = g.push(Node {
13697                op: Op::ReduceSumTo(Shape::from_dims(&[3])),
13698                inputs: vec![in_id],
13699                shape: Shape::from_dims(&[3]),
13700                dtype: DType::BF16,
13701            });
13702            g.set_target_backend(op_id, BackendId::Cpu);
13703            (in_id, op_id)
13704        };
13705        let mut inputs = StorageCache::new();
13706        inputs.insert(in_id, Arc::new(RwLock::new(s)));
13707        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13708        let guard = result_arc.read().unwrap();
13709        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13710            panic!("expected Cpu storage");
13711        };
13712        let got: Vec<f32> = c
13713            .as_slice::<half::bf16>()
13714            .unwrap()
13715            .iter()
13716            .map(|v| v.to_f32())
13717            .collect();
13718        let want = [5.0_f32, 7.0, 9.0];
13719        for (g, w) in got.iter().zip(want.iter()) {
13720            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
13721        }
13722    }
13723
13724    /// E2E: Op::ConvTranspose2D — F32 spread test.
13725    /// x = [[1, 2], [3, 4]] shape [1,1,2,2], all-ones kernel
13726    /// shape [1,1,2,2], stride=1, padding=0, dilation=1, no bias.
13727    /// Expected output (3x3):
13728    ///   [[1,  3, 2],
13729    ///    [4, 10, 6],
13730    ///    [3,  7, 4]]
13731    #[test]
13732    fn pipelined_realize_conv_transpose2d_f32() {
13733        let x_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
13734        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
13735        let graph = Arc::new(RwLock::new(Graph::new()));
13736        let (x_id, w_id, c_id) = {
13737            let mut g = graph.write().unwrap();
13738            let x = g.push(Node {
13739                op: Op::Const,
13740                inputs: vec![],
13741                shape: Shape::from_dims(&[1, 1, 2, 2]),
13742                dtype: DType::F32,
13743            });
13744            let w = g.push(Node {
13745                op: Op::Const,
13746                inputs: vec![],
13747                shape: Shape::from_dims(&[1, 1, 2, 2]),
13748                dtype: DType::F32,
13749            });
13750            let c = g.push(Node {
13751                op: Op::Fused(
13752                    fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D,
13753                    fuel_graph::registry::FusedOpParams::ConvTranspose2D {
13754                        stride: (1, 1),
13755                        padding: (0, 0),
13756                        output_padding: (0, 0),
13757                        dilation: (1, 1),
13758                        groups: 1,
13759                    },
13760                ),
13761                inputs: vec![x, w],
13762                shape: Shape::from_dims(&[1, 1, 3, 3]),
13763                dtype: DType::F32,
13764            });
13765            g.set_target_backend(c, BackendId::Cpu);
13766            (x, w, c)
13767        };
13768        let mut inputs = StorageCache::new();
13769        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
13770        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
13771        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
13772        let guard = result_arc.read().unwrap();
13773        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13774            panic!("expected Cpu storage");
13775        };
13776        assert_eq!(
13777            c.as_slice::<f32>().unwrap(),
13778            &[1.0, 3.0, 2.0, 4.0, 10.0, 6.0, 3.0, 7.0, 4.0],
13779        );
13780    }
13781
13782    /// E2E: ConvTranspose2D F64 — same shape test.
13783    #[test]
13784    fn pipelined_realize_conv_transpose2d_f64() {
13785        let x_storage = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0]);
13786        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f64, 1.0, 1.0, 1.0]);
13787        let graph = Arc::new(RwLock::new(Graph::new()));
13788        let (x_id, w_id, c_id) = {
13789            let mut g = graph.write().unwrap();
13790            let x = g.push(Node {
13791                op: Op::Const,
13792                inputs: vec![],
13793                shape: Shape::from_dims(&[1, 1, 2, 2]),
13794                dtype: DType::F64,
13795            });
13796            let w = g.push(Node {
13797                op: Op::Const,
13798                inputs: vec![],
13799                shape: Shape::from_dims(&[1, 1, 2, 2]),
13800                dtype: DType::F64,
13801            });
13802            let c = g.push(Node {
13803                op: Op::Fused(
13804                    fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D,
13805                    fuel_graph::registry::FusedOpParams::ConvTranspose2D {
13806                        stride: (1, 1),
13807                        padding: (0, 0),
13808                        output_padding: (0, 0),
13809                        dilation: (1, 1),
13810                        groups: 1,
13811                    },
13812                ),
13813                inputs: vec![x, w],
13814                shape: Shape::from_dims(&[1, 1, 3, 3]),
13815                dtype: DType::F64,
13816            });
13817            g.set_target_backend(c, BackendId::Cpu);
13818            (x, w, c)
13819        };
13820        let mut inputs = StorageCache::new();
13821        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
13822        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
13823        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
13824        let guard = result_arc.read().unwrap();
13825        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13826            panic!("expected Cpu storage");
13827        };
13828        assert_eq!(
13829            c.as_slice::<f64>().unwrap(),
13830            &[1.0, 3.0, 2.0, 4.0, 10.0, 6.0, 3.0, 7.0, 4.0],
13831        );
13832    }
13833
13834    /// E2E: ConvTranspose2D BF16 — tolerant compare via f32-acc.
13835    #[test]
13836    fn pipelined_realize_conv_transpose2d_bf16() {
13837        let x: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0]
13838            .iter()
13839            .map(|v| half::bf16::from_f32(*v))
13840            .collect();
13841        let w: Vec<half::bf16> = [1.0_f32, 1.0, 1.0, 1.0]
13842            .iter()
13843            .map(|v| half::bf16::from_f32(*v))
13844            .collect();
13845        let x_storage = fuel_memory::from_slice_cpu(&x);
13846        let w_storage = fuel_memory::from_slice_cpu(&w);
13847        let graph = Arc::new(RwLock::new(Graph::new()));
13848        let (x_id, w_id, c_id) = {
13849            let mut g = graph.write().unwrap();
13850            let x = g.push(Node {
13851                op: Op::Const,
13852                inputs: vec![],
13853                shape: Shape::from_dims(&[1, 1, 2, 2]),
13854                dtype: DType::BF16,
13855            });
13856            let w = g.push(Node {
13857                op: Op::Const,
13858                inputs: vec![],
13859                shape: Shape::from_dims(&[1, 1, 2, 2]),
13860                dtype: DType::BF16,
13861            });
13862            let c = g.push(Node {
13863                op: Op::Fused(
13864                    fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D,
13865                    fuel_graph::registry::FusedOpParams::ConvTranspose2D {
13866                        stride: (1, 1),
13867                        padding: (0, 0),
13868                        output_padding: (0, 0),
13869                        dilation: (1, 1),
13870                        groups: 1,
13871                    },
13872                ),
13873                inputs: vec![x, w],
13874                shape: Shape::from_dims(&[1, 1, 3, 3]),
13875                dtype: DType::BF16,
13876            });
13877            g.set_target_backend(c, BackendId::Cpu);
13878            (x, w, c)
13879        };
13880        let mut inputs = StorageCache::new();
13881        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
13882        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
13883        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
13884        let guard = result_arc.read().unwrap();
13885        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13886            panic!("expected Cpu storage");
13887        };
13888        let got: Vec<f32> = c
13889            .as_slice::<half::bf16>()
13890            .unwrap()
13891            .iter()
13892            .map(|v| v.to_f32())
13893            .collect();
13894        let want = [1.0_f32, 3.0, 2.0, 4.0, 10.0, 6.0, 3.0, 7.0, 4.0];
13895        for (g, w) in got.iter().zip(want.iter()) {
13896            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
13897        }
13898    }
13899
13900    /// E2E: GQA-style matmul through the pipelined executor.
13901    /// lhs has 4 batch heads, rhs has 2; each rhs head is shared
13902    /// by 2 lhs heads. Output's batch dim follows lhs (4 heads).
13903    #[test]
13904    fn pipelined_realize_matmul_gqa() {
13905        // lhs [4, 1, 2]: heads 0..3 are [[1,2]], [[3,4]], [[5,6]], [[7,8]]
13906        // rhs [2, 2, 1]: heads 0,1 are [[1],[0]], [[0],[1]]
13907        // Expected out [4, 1, 1]: [[1]], [[3]], [[6]], [[8]]
13908        let lhs_storage =
13909            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]);
13910        let rhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13911
13912        let graph = Arc::new(RwLock::new(Graph::new()));
13913        let (lhs_id, rhs_id, mm_id) = {
13914            let mut g = graph.write().unwrap();
13915            let lhs = g.push(Node {
13916                op: Op::Const,
13917                inputs: vec![],
13918                shape: Shape::from_dims(&[4, 1, 2]),
13919                dtype: DType::F32,
13920            });
13921            let rhs = g.push(Node {
13922                op: Op::Const,
13923                inputs: vec![],
13924                shape: Shape::from_dims(&[2, 2, 1]),
13925                dtype: DType::F32,
13926            });
13927            let mm = g.push(Node {
13928                op: Op::MatMul,
13929                inputs: vec![lhs, rhs],
13930                shape: Shape::from_dims(&[4, 1, 1]),
13931                dtype: DType::F32,
13932            });
13933            g.set_target_backend(mm, BackendId::Cpu);
13934            (lhs, rhs, mm)
13935        };
13936        let mut inputs = StorageCache::new();
13937        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
13938        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
13939
13940        let (result_arc, result_layout) =
13941            PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
13942        assert_eq!(result_layout.shape().dims(), &[4, 1, 1]);
13943
13944        let guard = result_arc.read().unwrap();
13945        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13946            panic!("expected Cpu storage");
13947        };
13948        assert_eq!(c.as_slice::<f32>().unwrap(), &[1.0, 3.0, 6.0, 8.0]);
13949    }
13950
13951    /// E2E: matmul with a transposed rhs — proves stage 3+4
13952    /// integration carries through the matmul path. The transpose
13953    /// is metadata-only; auto-Contiguize materializes the strided
13954    /// rhs before the matmul kernel sees it.
13955    #[test]
13956    fn pipelined_realize_matmul_with_transposed_rhs() {
13957        // lhs [[1, 2], [3, 4]], rhs original [[5, 6], [7, 8]]
13958        // rhs.T = [[5, 7], [6, 8]]
13959        // lhs @ rhs.T = [[1*5+2*6, 1*7+2*8], [3*5+4*6, 3*7+4*8]]
13960        //             = [[17, 23], [39, 53]]
13961        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
13962        let rhs_storage = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0, 7.0, 8.0]);
13963
13964        let graph = Arc::new(RwLock::new(Graph::new()));
13965        let (lhs_id, rhs_id, t_id, mm_id) = {
13966            let mut g = graph.write().unwrap();
13967            let lhs = g.push(Node {
13968                op: Op::Const,
13969                inputs: vec![],
13970                shape: Shape::from_dims(&[2, 2]),
13971                dtype: DType::F32,
13972            });
13973            let rhs = g.push(Node {
13974                op: Op::Const,
13975                inputs: vec![],
13976                shape: Shape::from_dims(&[2, 2]),
13977                dtype: DType::F32,
13978            });
13979            let t = g.push(Node {
13980                op: Op::Transpose,
13981                inputs: vec![rhs],
13982                shape: Shape::from_dims(&[2, 2]),
13983                dtype: DType::F32,
13984            });
13985            let mm = g.push(Node {
13986                op: Op::MatMul,
13987                inputs: vec![lhs, t],
13988                shape: Shape::from_dims(&[2, 2]),
13989                dtype: DType::F32,
13990            });
13991            g.set_target_backend(mm, BackendId::Cpu);
13992            (lhs, rhs, t, mm)
13993        };
13994        let _ = t_id;
13995        let mut inputs = StorageCache::new();
13996        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
13997        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
13998
13999        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
14000        let guard = result_arc.read().unwrap();
14001        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14002            panic!("expected Cpu storage");
14003        };
14004        assert_eq!(c.as_slice::<f32>().unwrap(), &[17.0, 23.0, 39.0, 53.0]);
14005    }
14006
14007    /// E2E: Const + Reshape — contiguous-input reshape is zero
14008    /// copy. The output Storage Arc is the input Arc; the layout
14009    /// is contiguous in the new shape.
14010    #[test]
14011    fn pipelined_realize_reshape_zero_copy_when_contiguous() {
14012        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14013        let graph = Arc::new(RwLock::new(Graph::new()));
14014        let (in_id, r_id) = {
14015            let mut g = graph.write().unwrap();
14016            let in_id = g.push(Node {
14017                op: Op::Const,
14018                inputs: vec![],
14019                shape: Shape::from_dims(&[2, 3]),
14020                dtype: DType::F32,
14021            });
14022            let r_id = g.push(Node {
14023                op: Op::Reshape(Shape::from_dims(&[3, 2])),
14024                inputs: vec![in_id],
14025                shape: Shape::from_dims(&[3, 2]),
14026                dtype: DType::F32,
14027            });
14028            (in_id, r_id)
14029        };
14030        let mut inputs = StorageCache::new();
14031        let in_arc = Arc::new(RwLock::new(storage));
14032        inputs.insert(in_id, Arc::clone(&in_arc));
14033
14034        let (result_arc, result_layout) =
14035            PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
14036
14037        // Zero copy — same Arc.
14038        assert!(
14039            Arc::ptr_eq(&result_arc, &in_arc),
14040            "contiguous reshape must zero-copy"
14041        );
14042        assert_eq!(result_layout.shape().dims(), &[3, 2]);
14043        assert!(result_layout.is_contiguous());
14044
14045        // Bytes are unchanged; just reinterpreted as [3, 2].
14046        let guard = result_arc.read().unwrap();
14047        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14048            panic!("expected Cpu storage");
14049        };
14050        assert_eq!(
14051            c.as_slice::<f32>().unwrap(),
14052            &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
14053        );
14054    }
14055
14056    /// E2E: Const + Transpose + Reshape — reshape on a strided
14057    /// input auto-contiguizes the bytes. Output Arc is fresh
14058    /// (NOT the input Arc); the bytes are the materialized
14059    /// transposed layout.
14060    #[test]
14061    fn pipelined_realize_reshape_materializes_when_strided() {
14062        // shape [2, 3]: 1 2 3 / 4 5 6
14063        // Transpose → [3, 2] strided
14064        // Reshape → [6] (forces materialization)
14065        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14066        let graph = Arc::new(RwLock::new(Graph::new()));
14067        let (in_id, t_id, r_id) = {
14068            let mut g = graph.write().unwrap();
14069            let in_id = g.push(Node {
14070                op: Op::Const,
14071                inputs: vec![],
14072                shape: Shape::from_dims(&[2, 3]),
14073                dtype: DType::F32,
14074            });
14075            let t_id = g.push(Node {
14076                op: Op::Transpose,
14077                inputs: vec![in_id],
14078                shape: Shape::from_dims(&[3, 2]),
14079                dtype: DType::F32,
14080            });
14081            let r_id = g.push(Node {
14082                op: Op::Reshape(Shape::from_dims(&[6])),
14083                inputs: vec![t_id],
14084                shape: Shape::from_dims(&[6]),
14085                dtype: DType::F32,
14086            });
14087            (in_id, t_id, r_id)
14088        };
14089        let _ = t_id;
14090        let mut inputs = StorageCache::new();
14091        let in_arc = Arc::new(RwLock::new(storage));
14092        inputs.insert(in_id, Arc::clone(&in_arc));
14093
14094        let (result_arc, result_layout) =
14095            PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
14096
14097        // Fresh Arc — auto-contiguize allocated new bytes.
14098        assert!(!Arc::ptr_eq(&result_arc, &in_arc));
14099        assert_eq!(result_layout.shape().dims(), &[6]);
14100        assert!(result_layout.is_contiguous());
14101
14102        // Materialized transposed bytes flattened: [1, 4, 2, 5, 3, 6].
14103        let guard = result_arc.read().unwrap();
14104        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14105            panic!("expected Cpu storage");
14106        };
14107        assert_eq!(
14108            c.as_slice::<f32>().unwrap(),
14109            &[1.0, 4.0, 2.0, 5.0, 3.0, 6.0]
14110        );
14111    }
14112
14113    /// E2E: Const + Transpose + SumDim — exercises stage 3
14114    /// (metadata-only Transpose, strided intermediate Layout) +
14115    /// stage 4 (auto-Contiguize before reduce kernel) end-to-end.
14116    /// The transpose makes the intermediate non-contiguous; the
14117    /// reduce wrapper would have failed in stage 2; with stage 4's
14118    /// auto-Contiguize, the kernel sees the materialized contiguous
14119    /// transposed bytes and produces the right answer.
14120    #[test]
14121    fn pipelined_realize_transpose_then_sum_dim_e2e() {
14122        // shape [2, 3]: rows are [1, 2, 3], [4, 5, 6]
14123        // After transpose: shape [3, 2], rows are [1, 4], [2, 5], [3, 6]
14124        // After SumDim(1): shape [3], values [5, 7, 9]
14125        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14126        let graph = Arc::new(RwLock::new(Graph::new()));
14127        let (in_id, t_id, sum_id) = {
14128            let mut g = graph.write().unwrap();
14129            let in_id = g.push(Node {
14130                op: Op::Const,
14131                inputs: vec![],
14132                shape: Shape::from_dims(&[2, 3]),
14133                dtype: DType::F32,
14134            });
14135            let t_id = g.push(Node {
14136                op: Op::Transpose,
14137                inputs: vec![in_id],
14138                shape: Shape::from_dims(&[3, 2]),
14139                dtype: DType::F32,
14140            });
14141            let sum_id = g.push(Node {
14142                op: Op::SumDim(1),
14143                inputs: vec![t_id],
14144                shape: Shape::from_dims(&[3]),
14145                dtype: DType::F32,
14146            });
14147            // Only the reduce kernel runs on the backend; the
14148            // transpose is metadata-only and doesn't need a target.
14149            g.set_target_backend(sum_id, BackendId::Cpu);
14150            (in_id, t_id, sum_id)
14151        };
14152        let _ = t_id;
14153        let mut inputs = StorageCache::new();
14154        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14155
14156        let (result_arc, result_layout) =
14157            PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
14158
14159        // The reduce output is contiguous (kernel-produced).
14160        assert_eq!(result_layout.shape().dims(), &[3]);
14161        assert!(result_layout.is_contiguous());
14162
14163        let guard = result_arc.read().unwrap();
14164        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14165            panic!("expected Cpu storage");
14166        };
14167        let typed: &[f32] = c.as_slice().unwrap();
14168        assert_eq!(typed, &[5.0, 7.0, 9.0]);
14169    }
14170
14171    /// E2E: Const + BroadcastTo + Add — broadcast intermediate
14172    /// auto-contiguizes for the Add kernel; the result is the
14173    /// expected sum.
14174    #[test]
14175    fn pipelined_realize_broadcast_then_add_e2e() {
14176        // shape [3]: [10, 20, 30]
14177        // BroadcastTo [2, 3]: [[10, 20, 30], [10, 20, 30]]
14178        // Plus shape [2, 3]: [[1, 2, 3], [4, 5, 6]]
14179        // Result: [[11, 22, 33], [14, 25, 36]]
14180        let bc_input = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
14181        let plus_input = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14182        let graph = Arc::new(RwLock::new(Graph::new()));
14183        let (bc_in_id, plus_in_id, b_id, add_id) = {
14184            let mut g = graph.write().unwrap();
14185            let bc_in = g.push(Node {
14186                op: Op::Const,
14187                inputs: vec![],
14188                shape: Shape::from_dims(&[3]),
14189                dtype: DType::F32,
14190            });
14191            let plus_in = g.push(Node {
14192                op: Op::Const,
14193                inputs: vec![],
14194                shape: Shape::from_dims(&[2, 3]),
14195                dtype: DType::F32,
14196            });
14197            let b = g.push(Node {
14198                op: Op::BroadcastTo(Shape::from_dims(&[2, 3])),
14199                inputs: vec![bc_in],
14200                shape: Shape::from_dims(&[2, 3]),
14201                dtype: DType::F32,
14202            });
14203            let add = g.push(Node {
14204                op: Op::Add,
14205                inputs: vec![b, plus_in],
14206                shape: Shape::from_dims(&[2, 3]),
14207                dtype: DType::F32,
14208            });
14209            g.set_target_backend(add, BackendId::Cpu);
14210            (bc_in, plus_in, b, add)
14211        };
14212        let _ = b_id;
14213        let mut inputs = StorageCache::new();
14214        inputs.insert(bc_in_id, Arc::new(RwLock::new(bc_input)));
14215        inputs.insert(plus_in_id, Arc::new(RwLock::new(plus_input)));
14216
14217        let (result_arc, _result_layout) =
14218            PipelinedExecutor::realize(graph, add_id, inputs).expect("realize");
14219        let guard = result_arc.read().unwrap();
14220        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14221            panic!("expected Cpu storage");
14222        };
14223        let typed: &[f32] = c.as_slice().unwrap();
14224        assert_eq!(typed, &[11.0, 22.0, 33.0, 14.0, 25.0, 36.0]);
14225    }
14226
14227    /// E2E: Const + SumDim — verifies that `OpParams::Reduce`
14228    /// flows from the graph (input shape via `op_to_op_params`)
14229    /// through compile_one and reaches the reduce kernel.
14230    #[test]
14231    fn pipelined_realize_sum_dim() {
14232        // shape [2, 3]; reduce dim 1 → output shape [2]
14233        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14234        let graph = Arc::new(RwLock::new(Graph::new()));
14235        let (in_id, sum_id) = {
14236            let mut g = graph.write().unwrap();
14237            let in_id = g.push(Node {
14238                op: Op::Const,
14239                inputs: vec![],
14240                shape: Shape::from_dims(&[2, 3]),
14241                dtype: DType::F32,
14242            });
14243            let sum_id = g.push(Node {
14244                op: Op::SumDim(1),
14245                inputs: vec![in_id],
14246                shape: Shape::from_dims(&[2]),
14247                dtype: DType::F32,
14248            });
14249            g.set_target_backend(sum_id, BackendId::Cpu);
14250            (in_id, sum_id)
14251        };
14252        let mut inputs = StorageCache::new();
14253        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14254
14255        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
14256        let guard = result_arc.read().unwrap();
14257        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14258            let typed: &[f32] = c.as_slice().unwrap();
14259            assert_eq!(typed, &[6.0, 15.0]);
14260        }
14261    }
14262
14263    /// E2E: SumAll on a rank-3 input, exercising the all-dims branch
14264    /// of `op_to_op_params` (every dim reduced, rank-0 output).
14265    #[test]
14266    fn pipelined_realize_sum_all_rank3() {
14267        let data: Vec<f32> = (1..=24).map(|x| x as f32).collect();
14268        let storage = fuel_memory::from_slice_cpu(&data);
14269        let graph = Arc::new(RwLock::new(Graph::new()));
14270        let (in_id, sum_id) = {
14271            let mut g = graph.write().unwrap();
14272            let in_id = g.push(Node {
14273                op: Op::Const,
14274                inputs: vec![],
14275                shape: Shape::from_dims(&[2, 3, 4]),
14276                dtype: DType::F32,
14277            });
14278            let sum_id = g.push(Node {
14279                op: Op::SumAll,
14280                inputs: vec![in_id],
14281                shape: Shape::from_dims(&[]),
14282                dtype: DType::F32,
14283            });
14284            g.set_target_backend(sum_id, BackendId::Cpu);
14285            (in_id, sum_id)
14286        };
14287        let mut inputs = StorageCache::new();
14288        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14289
14290        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
14291        let guard = result_arc.read().unwrap();
14292        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14293            let typed: &[f32] = c.as_slice().unwrap();
14294            // 1 + 2 + ... + 24 = 300
14295            assert_eq!(typed, &[300.0]);
14296        }
14297    }
14298
14299    /// E2E: MaxDim + MeanDim chained — verifies all four reduce
14300    /// OpKinds reach their wrappers via the OpParams plumbing.
14301    #[test]
14302    fn pipelined_realize_max_then_mean() {
14303        // shape [2, 3], MaxDim(1) → [2], MeanDim(0) → []
14304        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 9.0, 3.0, 4.0, 2.0, 8.0]);
14305        let graph = Arc::new(RwLock::new(Graph::new()));
14306        let (in_id, mean_id) = {
14307            let mut g = graph.write().unwrap();
14308            let in_id = g.push(Node {
14309                op: Op::Const,
14310                inputs: vec![],
14311                shape: Shape::from_dims(&[2, 3]),
14312                dtype: DType::F32,
14313            });
14314            let max_id = g.push(Node {
14315                op: Op::MaxDim(1),
14316                inputs: vec![in_id],
14317                shape: Shape::from_dims(&[2]),
14318                dtype: DType::F32,
14319            });
14320            let mean_id = g.push(Node {
14321                op: Op::MeanDim(0),
14322                inputs: vec![max_id],
14323                shape: Shape::from_dims(&[]),
14324                dtype: DType::F32,
14325            });
14326            g.set_target_backend(max_id, BackendId::Cpu);
14327            g.set_target_backend(mean_id, BackendId::Cpu);
14328            (in_id, mean_id)
14329        };
14330        let mut inputs = StorageCache::new();
14331        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14332
14333        let (result_arc, _) = PipelinedExecutor::realize(graph, mean_id, inputs).expect("realize");
14334        let guard = result_arc.read().unwrap();
14335        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14336            let typed: &[f32] = c.as_slice().unwrap();
14337            // MaxDim(1) on [[1,9,3],[4,2,8]] = [9, 8]; MeanDim(0) = 8.5
14338            assert_eq!(typed, &[8.5]);
14339        }
14340    }
14341
14342    /// E2E: Sigmoid + Silu — exercises two of the more compositional
14343    /// new unary kernels through the pipelined executor. Verifies
14344    /// the additional `op_to_op_kind` mappings reach the right
14345    /// dispatch wrappers.
14346    #[test]
14347    fn pipelined_realize_sigmoid_then_silu() {
14348        let storage = fuel_memory::from_slice_cpu(&[0.0_f32, 1.0, -1.0]);
14349        let graph = Arc::new(RwLock::new(Graph::new()));
14350        let (in_id, sig_id, silu_id) = {
14351            let mut g = graph.write().unwrap();
14352            let in_id = g.push(Node {
14353                op: Op::Const,
14354                inputs: vec![],
14355                shape: Shape::from_dims(&[3]),
14356                dtype: DType::F32,
14357            });
14358            let sig_id = g.push(Node {
14359                op: Op::Sigmoid,
14360                inputs: vec![in_id],
14361                shape: Shape::from_dims(&[3]),
14362                dtype: DType::F32,
14363            });
14364            // Silu of the sigmoid output — chains to confirm cache flow.
14365            let silu_id = g.push(Node {
14366                op: Op::Silu,
14367                inputs: vec![sig_id],
14368                shape: Shape::from_dims(&[3]),
14369                dtype: DType::F32,
14370            });
14371            g.set_target_backend(sig_id, BackendId::Cpu);
14372            g.set_target_backend(silu_id, BackendId::Cpu);
14373            (in_id, sig_id, silu_id)
14374        };
14375        let _ = sig_id;
14376        let mut inputs = StorageCache::new();
14377        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14378
14379        let (result_arc, _) = PipelinedExecutor::realize(graph, silu_id, inputs).expect("realize");
14380        let guard = result_arc.read().unwrap();
14381        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14382            let typed: &[f32] = c.as_slice().unwrap();
14383            // sigmoid(0) = 0.5; silu(0.5) = 0.5 * sigmoid(0.5) ≈ 0.3112
14384            assert!((typed[0] - 0.5 * (1.0 / (1.0 + (-0.5_f32).exp()))).abs() < 1e-6);
14385        }
14386    }
14387
14388    /// E2E: chained unary ops — Const + Sqr + Sqrt should be a noop
14389    /// for non-negative inputs. Exercises the cache reuse path.
14390    #[test]
14391    fn pipelined_realize_chained_unary_sqr_then_sqrt() {
14392        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 4.0, 9.0]);
14393        let graph = Arc::new(RwLock::new(Graph::new()));
14394        let (in_id, sqrt_id) = {
14395            let mut g = graph.write().unwrap();
14396            let in_id = g.push(Node {
14397                op: Op::Const,
14398                inputs: vec![],
14399                shape: Shape::from_dims(&[3]),
14400                dtype: DType::F32,
14401            });
14402            let sqr_id = g.push(Node {
14403                op: Op::Sqr,
14404                inputs: vec![in_id],
14405                shape: Shape::from_dims(&[3]),
14406                dtype: DType::F32,
14407            });
14408            let sqrt_id = g.push(Node {
14409                op: Op::Sqrt,
14410                inputs: vec![sqr_id],
14411                shape: Shape::from_dims(&[3]),
14412                dtype: DType::F32,
14413            });
14414            g.set_target_backend(sqr_id, BackendId::Cpu);
14415            g.set_target_backend(sqrt_id, BackendId::Cpu);
14416            (in_id, sqrt_id)
14417        };
14418        let mut inputs = StorageCache::new();
14419        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14420
14421        let (result_arc, _) = PipelinedExecutor::realize(graph, sqrt_id, inputs).expect("realize");
14422        let guard = result_arc.read().unwrap();
14423        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14424            let typed: &[f32] = c.as_slice().unwrap();
14425            // sqrt(sqr(x)) == |x| == x for non-negative inputs.
14426            assert_eq!(typed, &[1.0, 4.0, 9.0]);
14427        }
14428    }
14429
14430    /// Multi-stage pipelined: Const + Const + Add + Add (chain of
14431    /// two adds). Tests that work items are processed in topo order
14432    /// and intermediate results are cached and reused.
14433    #[test]
14434    fn pipelined_realize_chained_adds() {
14435        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
14436        let b_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
14437        let c_storage = fuel_memory::from_slice_cpu(&[100.0_f32, 200.0]);
14438
14439        let graph = Arc::new(RwLock::new(Graph::new()));
14440        let (a_id, b_id, c_id, ab_id, abc_id) = {
14441            let mut g = graph.write().unwrap();
14442            let a = g.push(Node {
14443                op: Op::Const,
14444                inputs: vec![],
14445                shape: Shape::from_dims(&[2]),
14446                dtype: DType::F32,
14447            });
14448            let b = g.push(Node {
14449                op: Op::Const,
14450                inputs: vec![],
14451                shape: Shape::from_dims(&[2]),
14452                dtype: DType::F32,
14453            });
14454            let c = g.push(Node {
14455                op: Op::Const,
14456                inputs: vec![],
14457                shape: Shape::from_dims(&[2]),
14458                dtype: DType::F32,
14459            });
14460            let ab = g.push(Node {
14461                op: Op::Add,
14462                inputs: vec![a, b],
14463                shape: Shape::from_dims(&[2]),
14464                dtype: DType::F32,
14465            });
14466            let abc = g.push(Node {
14467                op: Op::Add,
14468                inputs: vec![ab, c],
14469                shape: Shape::from_dims(&[2]),
14470                dtype: DType::F32,
14471            });
14472            g.set_target_backend(ab, BackendId::Cpu);
14473            g.set_target_backend(abc, BackendId::Cpu);
14474            (a, b, c, ab, abc)
14475        };
14476
14477        let mut inputs = StorageCache::new();
14478        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
14479        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
14480        inputs.insert(c_id, Arc::new(RwLock::new(c_storage)));
14481
14482        let (result_arc, _) = PipelinedExecutor::realize(graph, abc_id, inputs).expect("realize");
14483        // Suppress unused warning for the intermediate id.
14484        let _ = ab_id;
14485
14486        let guard = result_arc.read().unwrap();
14487        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14488            let typed: &[f32] = c.as_slice().unwrap();
14489            // (1+10) + 100 = 111;  (2+20) + 200 = 222.
14490            assert_eq!(typed, &[111.0, 222.0]);
14491        }
14492    }
14493
14494    /// E2E: triu(diagonal=0) on a 3×3 matrix.
14495    /// Input:  [1 2 3 / 4 5 6 / 7 8 9]
14496    /// Output: [1 2 3 / 0 5 6 / 0 0 9]
14497    #[test]
14498    fn pipelined_realize_triu_3x3_diag0() {
14499        let storage =
14500            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
14501        let graph = Arc::new(RwLock::new(Graph::new()));
14502        let (in_id, out_id) = {
14503            let mut g = graph.write().unwrap();
14504            let in_id = g.push(Node {
14505                op: Op::Const,
14506                inputs: vec![],
14507                shape: Shape::from_dims(&[3, 3]),
14508                dtype: DType::F32,
14509            });
14510            let out_id = g.push(Node {
14511                op: Op::Triu { diagonal: 0 },
14512                inputs: vec![in_id],
14513                shape: Shape::from_dims(&[3, 3]),
14514                dtype: DType::F32,
14515            });
14516            g.set_target_backend(out_id, BackendId::Cpu);
14517            (in_id, out_id)
14518        };
14519        let mut inputs = StorageCache::new();
14520        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14521        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
14522        let guard = result_arc.read().unwrap();
14523        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14524            panic!("expected Cpu storage");
14525        };
14526        let out: &[f32] = c.as_slice().unwrap();
14527        assert_eq!(out, &[1.0, 2.0, 3.0, 0.0, 5.0, 6.0, 0.0, 0.0, 9.0,]);
14528    }
14529
14530    /// E2E: tril(diagonal=0) on a 3×3 matrix — the canonical causal mask.
14531    /// Output: [1 0 0 / 4 5 0 / 7 8 9]
14532    #[test]
14533    fn pipelined_realize_tril_3x3_diag0_causal_mask() {
14534        let storage =
14535            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
14536        let graph = Arc::new(RwLock::new(Graph::new()));
14537        let (in_id, out_id) = {
14538            let mut g = graph.write().unwrap();
14539            let in_id = g.push(Node {
14540                op: Op::Const,
14541                inputs: vec![],
14542                shape: Shape::from_dims(&[3, 3]),
14543                dtype: DType::F32,
14544            });
14545            let out_id = g.push(Node {
14546                op: Op::Tril { diagonal: 0 },
14547                inputs: vec![in_id],
14548                shape: Shape::from_dims(&[3, 3]),
14549                dtype: DType::F32,
14550            });
14551            g.set_target_backend(out_id, BackendId::Cpu);
14552            (in_id, out_id)
14553        };
14554        let mut inputs = StorageCache::new();
14555        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14556        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
14557        let guard = result_arc.read().unwrap();
14558        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14559            panic!("expected Cpu storage");
14560        };
14561        let out: &[f32] = c.as_slice().unwrap();
14562        assert_eq!(out, &[1.0, 0.0, 0.0, 4.0, 5.0, 0.0, 7.0, 8.0, 9.0,]);
14563    }
14564
14565    /// E2E: log_softmax over a 2×3 input. Rows are [1,2,3] and [3,2,1].
14566    /// log_softmax(row) = row - max - log(sum exp(row - max)).
14567    /// Row 0: max=3, exp(-2)+exp(-1)+exp(0) = 0.135+0.368+1.0 = 1.503;
14568    ///        log(1.503) ≈ 0.4076; out = [1-3-0.4076, 2-3-0.4076, 3-3-0.4076]
14569    ///                              = [-2.4076, -1.4076, -0.4076]
14570    /// Row 1 is row 0 reversed: [-0.4076, -1.4076, -2.4076].
14571    #[test]
14572    fn pipelined_realize_log_softmax_last_dim() {
14573        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 3.0, 2.0, 1.0]);
14574        let graph = Arc::new(RwLock::new(Graph::new()));
14575        let (in_id, out_id) = {
14576            let mut g = graph.write().unwrap();
14577            let in_id = g.push(Node {
14578                op: Op::Const,
14579                inputs: vec![],
14580                shape: Shape::from_dims(&[2, 3]),
14581                dtype: DType::F32,
14582            });
14583            let out_id = g.push(Node {
14584                op: Op::LogSoftmaxLastDim,
14585                inputs: vec![in_id],
14586                shape: Shape::from_dims(&[2, 3]),
14587                dtype: DType::F32,
14588            });
14589            g.set_target_backend(out_id, BackendId::Cpu);
14590            (in_id, out_id)
14591        };
14592        let mut inputs = StorageCache::new();
14593        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14594        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
14595        let guard = result_arc.read().unwrap();
14596        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14597            panic!("expected Cpu storage");
14598        };
14599        let out: &[f32] = c.as_slice().unwrap();
14600        let expected = [
14601            -2.407_606,
14602            -1.4076059,
14603            -0.40760595_f32,
14604            -0.40760595,
14605            -1.4076059,
14606            -2.407_606,
14607        ];
14608        for (a, b) in out.iter().zip(expected.iter()) {
14609            assert!((a - b).abs() < 1e-5, "log_softmax mismatch: {a} vs {b}");
14610        }
14611        // The exp() of the output should sum to 1 per row.
14612        for row in out.chunks(3) {
14613            let sum: f32 = row.iter().map(|x| x.exp()).sum();
14614            assert!(
14615                (sum - 1.0).abs() < 1e-5,
14616                "softmax(log_softmax) row sum != 1: {sum}"
14617            );
14618        }
14619    }
14620
14621    // --- side-effect roots + destructive cleanup (9c Phase B) -----
14622
14623    /// Side-effect roots get merged into the realize walk even when
14624    /// not reachable from the user's targets. The production trigger
14625    /// is `Op::Release` (emitted by `ResidencyEvictionRule`); this
14626    /// test uses that exact shape.
14627    ///
14628    /// Graph: Const(a) + Const(b) → Add (user target); separate
14629    /// Const(c) → Release(c) (side-effect root, not reachable from
14630    /// Add). After realize_many on `[add]`, the Add should be in the
14631    /// output AND the Release should have fired (verified by the
14632    /// fact that realize succeeded — Op::Release in the walk used to
14633    /// fail compilation pre-Phase B+).
14634    #[test]
14635    fn pipelined_realize_merges_op_release_side_effect_root() {
14636        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
14637        let b = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
14638        let c = fuel_memory::from_slice_cpu(&[100.0_f32, 200.0]);
14639        let graph = Arc::new(RwLock::new(Graph::new()));
14640        let (a_id, b_id, c_id, add_id, release_id) = {
14641            let mut g = graph.write().unwrap();
14642            let a = g.push(Node {
14643                op: Op::Const,
14644                inputs: vec![],
14645                shape: Shape::from_dims(&[2]),
14646                dtype: DType::F32,
14647            });
14648            let b = g.push(Node {
14649                op: Op::Const,
14650                inputs: vec![],
14651                shape: Shape::from_dims(&[2]),
14652                dtype: DType::F32,
14653            });
14654            // c is NOT reachable from add; its Release IS marked as
14655            // a side-effect root.
14656            let c = g.push(Node {
14657                op: Op::Const,
14658                inputs: vec![],
14659                shape: Shape::from_dims(&[2]),
14660                dtype: DType::F32,
14661            });
14662            let add = g.push(Node {
14663                op: Op::Add,
14664                inputs: vec![a, b],
14665                shape: Shape::from_dims(&[2]),
14666                dtype: DType::F32,
14667            });
14668            // Production shape: Op::Release on c, marked as
14669            // side-effect root so it fires even though no graph
14670            // node reads its output.
14671            let release = g.push(Node {
14672                op: Op::Release,
14673                inputs: vec![c],
14674                shape: Shape::from_dims(&[0]),
14675                dtype: DType::F32,
14676            });
14677            g.set_target_backend(add, BackendId::Cpu);
14678            g.set_target_backend(release, BackendId::Cpu);
14679            g.add_side_effect_root(release);
14680            (a, b, c, add, release)
14681        };
14682        let mut inputs = StorageCache::new();
14683        inputs.insert(a_id, Arc::new(RwLock::new(a)));
14684        inputs.insert(b_id, Arc::new(RwLock::new(b)));
14685        let c_arc = Arc::new(RwLock::new(c));
14686        let c_arc_external = Arc::clone(&c_arc);
14687        inputs.insert(c_id, c_arc);
14688
14689        // Only `add` is requested. The Release on c is a side-effect
14690        // root that must still fire.
14691        let out = PipelinedExecutor::realize_many(graph, &[add_id], inputs).expect("realize_many");
14692        assert_eq!(out.len(), 1);
14693        let add_guard = out[0].0.read().unwrap();
14694        let fuel_memory::BackendStorage::Cpu(arr) = &add_guard.inner else {
14695            panic!()
14696        };
14697        assert_eq!(arr.as_slice::<f32>().unwrap(), &[11.0, 22.0]);
14698
14699        // The Release's destructive_input cleanup dropped the
14700        // cache's Arc to c. The only Arc to c that survives is the
14701        // external one this test holds — confirms the eviction
14702        // actually freed the cache's reference.
14703        assert_eq!(
14704            Arc::strong_count(&c_arc_external),
14705            1,
14706            "Op::Release should evict the cache's Arc to its source; \
14707             only the test's external clone should remain",
14708        );
14709        let _ = release_id;
14710    }
14711
14712    /// `compile_one` emits a `WorkItemKind::ReleaseMarker` for
14713    /// `Op::Release` with `destructive_input = Some(0)`. Verify
14714    /// the WorkItem shape via a direct compile_one call.
14715    #[test]
14716    fn compile_one_emits_release_marker_with_destructive_input() {
14717        let graph_rc = Arc::new(RwLock::new(Graph::new()));
14718        let (src_id, release_id) = {
14719            let mut g = graph_rc.write().unwrap();
14720            let src = g.push(Node {
14721                op: Op::Const,
14722                inputs: vec![],
14723                shape: Shape::from_dims(&[2]),
14724                dtype: DType::F32,
14725            });
14726            let release = g.push(Node {
14727                op: Op::Release,
14728                inputs: vec![src],
14729                shape: Shape::from_dims(&[0]),
14730                dtype: DType::F32,
14731            });
14732            g.set_target_backend(release, BackendId::Cpu);
14733            (src, release)
14734        };
14735        let g = graph_rc.read().unwrap();
14736        let bindings = crate::dispatch::global_bindings();
14737        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
14738        let item = compile_one(
14739            &g,
14740            release_id,
14741            &mut layout_cache,
14742            &bindings,
14743            &SymEnv::default(),
14744        )
14745        .expect("compile_one Op::Release");
14746        assert!(matches!(item.kind, WorkItemKind::ReleaseMarker));
14747        assert_eq!(item.destructive_input, Some(0));
14748        assert_eq!(item.inputs, vec![src_id]);
14749        assert_eq!(
14750            item.elem_count, 0,
14751            "Release output is the zero-element marker"
14752        );
14753    }
14754
14755    // --- Op::Move (executor-unification Session 1, gap 13) --------
14756
14757    /// `compile_one` emits a `WorkItemKind::Move` for `Op::Move` with
14758    /// `destructive_input = Some(0)` and a resolved transfer kernel
14759    /// (binding-table lookup at `(OpKind::Copy, [dt, dt], source
14760    /// backend)` — Move shares Op::Copy's data-movement kernel).
14761    #[test]
14762    fn compile_one_emits_move_with_destructive_input() {
14763        let graph_rc = Arc::new(RwLock::new(Graph::new()));
14764        let (src_id, move_id) = {
14765            let mut g = graph_rc.write().unwrap();
14766            let src = g.push(Node {
14767                op: Op::Const,
14768                inputs: vec![],
14769                shape: Shape::from_dims(&[2]),
14770                dtype: DType::F32,
14771            });
14772            let mv = g.push(Node {
14773                op: Op::Move {
14774                    target: DeviceLocation::Cpu,
14775                },
14776                inputs: vec![src],
14777                shape: Shape::from_dims(&[2]),
14778                dtype: DType::F32,
14779            });
14780            g.set_target_backend(mv, BackendId::Cpu);
14781            (src, mv)
14782        };
14783        let g = graph_rc.read().unwrap();
14784        let bindings = crate::dispatch::global_bindings();
14785        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
14786        let item = compile_one(
14787            &g,
14788            move_id,
14789            &mut layout_cache,
14790            &bindings,
14791            &SymEnv::default(),
14792        )
14793        .expect("compile_one Op::Move");
14794        assert!(matches!(
14795            item.kind,
14796            WorkItemKind::Move {
14797                target_location: DeviceLocation::Cpu
14798            },
14799        ));
14800        assert_eq!(item.destructive_input, Some(0), "Move destroys its source");
14801        assert_eq!(item.inputs, vec![src_id]);
14802        assert!(
14803            item.compiled.is_some(),
14804            "Move resolves a transfer kernel at (OpKind::Copy, [dt, dt], source backend)",
14805        );
14806    }
14807
14808    // --- runtime fused op (JIT-adopted Tier-2 kernel) --------------
14809
14810    /// `compile_one` resolves an `Op::Fused(fid, Runtime)` node with
14811    /// `fid.is_runtime()` from the runtime-kernel sidecar (never the
14812    /// binding table): `WorkItemKind::Kernel`, `compiled.op ==
14813    /// OpKind::RuntimeFused`, and the kernel pointer is exactly the one
14814    /// `adopt_runtime_fused` bound.
14815    #[test]
14816    fn compile_one_resolves_runtime_fused_from_the_sidecar() {
14817        fn sentinel_kernel(
14818            _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
14819            _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
14820            _layouts: &[Layout],
14821            _params: &crate::kernel::OpParams,
14822        ) -> Result<()> {
14823            Ok(())
14824        }
14825        // A region shape unique to this test (process-global sidecar; see
14826        // runtime_fused_pathfinder's tests for the collision rationale).
14827        let region = fuel_graph::jit::PatternNode::Op {
14828            op: fuel_graph::jit::OpTag::Exp,
14829            attrs: fuel_graph::jit::OpAttrs::default(),
14830            operands: vec![fuel_graph::jit::PatternNode::Op {
14831                op: fuel_graph::jit::OpTag::Sub,
14832                attrs: fuel_graph::jit::OpAttrs::default(),
14833                operands: vec![
14834                    fuel_graph::jit::PatternNode::Bind { index: 0 },
14835                    fuel_graph::jit::PatternNode::Bind { index: 1 },
14836                ],
14837            }],
14838        };
14839        let rid = crate::runtime_fused_kernels::adopt_runtime_fused(
14840            "test::compile_one::exp_sub",
14841            region,
14842            sentinel_kernel as crate::kernel::KernelRef,
14843            vec![DType::F32, DType::F32, DType::F32],
14844            BackendId::Cpu,
14845        )
14846        .expect("registrable region");
14847
14848        let graph_rc = Arc::new(RwLock::new(Graph::new()));
14849        let fused_id = {
14850            let mut g = graph_rc.write().unwrap();
14851            let s = Shape::from_dims(&[4]);
14852            let a = g.push(Node {
14853                op: Op::Const,
14854                inputs: vec![],
14855                shape: s.clone(),
14856                dtype: DType::F32,
14857            });
14858            let b = g.push(Node {
14859                op: Op::Const,
14860                inputs: vec![],
14861                shape: s.clone(),
14862                dtype: DType::F32,
14863            });
14864            let fused = g.push(Node {
14865                op: Op::Fused(
14866                    rid,
14867                    fuel_graph::registry::FusedOpParams::Runtime {
14868                        scalars: Vec::new(),
14869                    },
14870                ),
14871                inputs: vec![a, b],
14872                shape: s,
14873                dtype: DType::F32,
14874            });
14875            // The arm emitter pins the backend; mirror that here.
14876            g.set_target_backend(fused, BackendId::Cpu);
14877            fused
14878        };
14879        let g = graph_rc.read().unwrap();
14880        let bindings = crate::dispatch::global_bindings();
14881        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
14882        let item = compile_one(
14883            &g,
14884            fused_id,
14885            &mut layout_cache,
14886            &bindings,
14887            &SymEnv::default(),
14888        )
14889        .expect("compile_one runtime fused op");
14890        assert!(matches!(item.kind, WorkItemKind::Kernel));
14891        let compiled = item.compiled.expect("resolved a kernel");
14892        assert_eq!(compiled.op, fuel_ir::dispatch::OpKind::RuntimeFused);
14893        assert_eq!(compiled.backend, BackendId::Cpu);
14894        assert!(
14895            std::ptr::fn_addr_eq(compiled.kernel, sentinel_kernel as crate::kernel::KernelRef),
14896            "the kernel pointer is exactly the adopted one",
14897        );
14898        assert!(
14899            layout_cache.contains_key(&fused_id),
14900            "output layout cached for consumers"
14901        );
14902    }
14903
14904    /// The dtype belt-and-suspenders guard: an `Op::Fused(runtime)` node
14905    /// whose per-operand dtypes disagree with the adopted kernel's tuple is
14906    /// a typed error, not a silent wrong-kernel dispatch.
14907    #[test]
14908    fn compile_one_rejects_runtime_fused_dtype_mismatch() {
14909        fn noop_kernel(
14910            _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
14911            _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
14912            _layouts: &[Layout],
14913            _params: &crate::kernel::OpParams,
14914        ) -> Result<()> {
14915            Ok(())
14916        }
14917        let region = fuel_graph::jit::PatternNode::Op {
14918            op: fuel_graph::jit::OpTag::Log,
14919            attrs: fuel_graph::jit::OpAttrs::default(),
14920            operands: vec![fuel_graph::jit::PatternNode::Op {
14921                op: fuel_graph::jit::OpTag::Maximum,
14922                attrs: fuel_graph::jit::OpAttrs::default(),
14923                operands: vec![
14924                    fuel_graph::jit::PatternNode::Bind { index: 0 },
14925                    fuel_graph::jit::PatternNode::Bind { index: 1 },
14926                ],
14927            }],
14928        };
14929        // Adopted for F32 operands…
14930        let rid = crate::runtime_fused_kernels::adopt_runtime_fused(
14931            "test::compile_one::log_maximum",
14932            region,
14933            noop_kernel as crate::kernel::KernelRef,
14934            vec![DType::F32, DType::F32, DType::F32],
14935            BackendId::Cpu,
14936        )
14937        .expect("registrable region");
14938
14939        let graph_rc = Arc::new(RwLock::new(Graph::new()));
14940        let fused_id = {
14941            let mut g = graph_rc.write().unwrap();
14942            let s = Shape::from_dims(&[4]);
14943            // …but the node's operands are F64.
14944            let a = g.push(Node {
14945                op: Op::Const,
14946                inputs: vec![],
14947                shape: s.clone(),
14948                dtype: DType::F64,
14949            });
14950            let b = g.push(Node {
14951                op: Op::Const,
14952                inputs: vec![],
14953                shape: s.clone(),
14954                dtype: DType::F64,
14955            });
14956            let fused = g.push(Node {
14957                op: Op::Fused(
14958                    rid,
14959                    fuel_graph::registry::FusedOpParams::Runtime {
14960                        scalars: Vec::new(),
14961                    },
14962                ),
14963                inputs: vec![a, b],
14964                shape: s,
14965                dtype: DType::F64,
14966            });
14967            g.set_target_backend(fused, BackendId::Cpu);
14968            fused
14969        };
14970        let g = graph_rc.read().unwrap();
14971        let bindings = crate::dispatch::global_bindings();
14972        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
14973        let err = match compile_one(
14974            &g,
14975            fused_id,
14976            &mut layout_cache,
14977            &bindings,
14978            &SymEnv::default(),
14979        ) {
14980            Ok(_) => panic!("dtype mismatch must be a typed error"),
14981            Err(e) => e,
14982        };
14983        // Post-fold, the dtype tuple IS the binding key: a mismatch is the
14984        // same honest `NoBackendForOp` miss as an absent kernel — reported
14985        // with the `RuntimeFused` diagnostic op tag, never a wrong-kernel bind.
14986        assert!(
14987            matches!(
14988                err,
14989                fuel_ir::Error::NoBackendForOp {
14990                    op: fuel_ir::dispatch::OpKind::RuntimeFused,
14991                    ..
14992                }
14993            ),
14994            "a dtype mismatch is an honest binding miss: {err}",
14995        );
14996    }
14997
14998    /// A runtime fused node carrying live `Runtime { scalars }` compiles with
14999    /// `OpParams::JitScalars` — the launch channel for the kernel's trailing
15000    /// `p{i}` args. (A param-free node keeps `OpParams::None`, covered by
15001    /// `compile_one_resolves_runtime_fused_from_the_sidecar`.)
15002    #[test]
15003    fn compile_one_maps_runtime_scalars_to_jit_scalars() {
15004        fn noop_kernel(
15005            _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
15006            _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
15007            _layouts: &[Layout],
15008            _params: &crate::kernel::OpParams,
15009        ) -> Result<()> {
15010            Ok(())
15011        }
15012        // Unique slot-template region (process-global sidecar).
15013        let region = fuel_graph::jit::PatternNode::Op {
15014            op: fuel_graph::jit::OpTag::Floor,
15015            attrs: fuel_graph::jit::OpAttrs::default(),
15016            operands: vec![fuel_graph::jit::PatternNode::Op {
15017                op: fuel_graph::jit::OpTag::MulScalar,
15018                attrs: fuel_graph::jit::OpAttrs::default(), // open slot
15019                operands: vec![fuel_graph::jit::PatternNode::Bind { index: 0 }],
15020            }],
15021        };
15022        let rid = crate::runtime_fused_kernels::adopt_runtime_fused(
15023            "test::compile_one::floor_mul_scalar",
15024            region,
15025            noop_kernel as crate::kernel::KernelRef,
15026            vec![DType::F32, DType::F32],
15027            BackendId::Cpu,
15028        )
15029        .expect("slot template registrable");
15030
15031        let graph_rc = Arc::new(RwLock::new(Graph::new()));
15032        let fused_id = {
15033            let mut g = graph_rc.write().unwrap();
15034            let s = Shape::from_dims(&[4]);
15035            let x = g.push(Node {
15036                op: Op::Const,
15037                inputs: vec![],
15038                shape: s.clone(),
15039                dtype: DType::F32,
15040            });
15041            let fused = g.push(Node {
15042                op: Op::Fused(
15043                    rid,
15044                    fuel_graph::registry::FusedOpParams::Runtime {
15045                        scalars: vec![3.5, -1.25],
15046                    },
15047                ),
15048                inputs: vec![x],
15049                shape: s,
15050                dtype: DType::F32,
15051            });
15052            g.set_target_backend(fused, BackendId::Cpu);
15053            fused
15054        };
15055        let g = graph_rc.read().unwrap();
15056        let bindings = crate::dispatch::global_bindings();
15057        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
15058        let item = compile_one(
15059            &g,
15060            fused_id,
15061            &mut layout_cache,
15062            &bindings,
15063            &SymEnv::default(),
15064        )
15065        .expect("compile_one runtime fused op with scalars");
15066        let compiled = item.compiled.expect("resolved a kernel");
15067        assert!(
15068            matches!(
15069                &compiled.op_params,
15070                crate::kernel::OpParams::JitScalars { scalars } if scalars == &vec![3.5, -1.25]
15071            ),
15072            "Runtime scalars ride into OpParams::JitScalars, got {:?}",
15073            compiled.op_params,
15074        );
15075    }
15076
15077    /// Move-to-same-device is the degenerate case: per the legacy
15078    /// `GraphExecutor` contract (`Op::Copy | Op::Move` shared arm →
15079    /// `backend.copy_to`) it is a plain copy — fresh storage on the
15080    /// same device, data intact — and the source is still evicted
15081    /// afterward (destructive semantics don't depend on the devices
15082    /// differing).
15083    #[test]
15084    fn pipelined_op_move_same_device_is_plain_copy() {
15085        let src = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
15086        let graph = Arc::new(RwLock::new(Graph::new()));
15087        let (src_id, move_id) = {
15088            let mut g = graph.write().unwrap();
15089            let src = g.push(Node {
15090                op: Op::Const,
15091                inputs: vec![],
15092                shape: Shape::from_dims(&[4]),
15093                dtype: DType::F32,
15094            });
15095            let mv = g.push(Node {
15096                op: Op::Move {
15097                    target: DeviceLocation::Cpu,
15098                },
15099                inputs: vec![src],
15100                shape: Shape::from_dims(&[4]),
15101                dtype: DType::F32,
15102            });
15103            g.set_target_backend(mv, BackendId::Cpu);
15104            (src, mv)
15105        };
15106        let src_arc = Arc::new(RwLock::new(src));
15107        let src_arc_external = Arc::clone(&src_arc);
15108        let mut inputs = StorageCache::new();
15109        inputs.insert(src_id, src_arc);
15110
15111        let (out, layout) =
15112            PipelinedExecutor::realize(graph, move_id, inputs).expect("realize Op::Move");
15113        let guard = out.read().unwrap();
15114        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15115            panic!()
15116        };
15117        assert_eq!(
15118            c.as_slice::<f32>().unwrap(),
15119            &[1.0, 2.0, 3.0, 4.0],
15120            "Op::Move output should carry input's data to target",
15121        );
15122        assert!(layout.is_contiguous());
15123        drop(guard);
15124        assert!(
15125            !Arc::ptr_eq(&out, &src_arc_external),
15126            "same-device Move is a plain copy — fresh storage, not an alias",
15127        );
15128        // The realize loop's destructive_input cleanup dropped the
15129        // cache's Arc to the source; only the test's external clone
15130        // survives.
15131        assert_eq!(
15132            Arc::strong_count(&src_arc_external),
15133            1,
15134            "Op::Move should evict the cache's Arc to its source",
15135        );
15136    }
15137
15138    /// The multiple-consumer-source case: a Move must NOT strand
15139    /// another consumer of its source. `execution_plan` (via
15140    /// `derive_ordering`, keyed off `destructive_input`) pins the
15141    /// Move AFTER the sibling reader; the executor's post-Move cache
15142    /// eviction then can't break the reader. Mirrors the legacy
15143    /// `op_move_pinned_after_sibling_reader_via_derive_ordering`
15144    /// test in fuel-graph-router/tests/cross_device.rs.
15145    ///
15146    ///   a   = const [1, 2, 3, 4]
15147    ///   b   = relu(a)        (non-destructive sibling reader)
15148    ///   m   = move(a, Cpu)   (destructive — evicts a once run)
15149    ///   out = add(b, m)      → [2, 4, 6, 8]
15150    #[test]
15151    fn pipelined_op_move_multi_consumer_source_not_stranded() {
15152        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
15153        let graph = Arc::new(RwLock::new(Graph::new()));
15154        let (a_id, out_id) = {
15155            let mut g = graph.write().unwrap();
15156            let a = g.push(Node {
15157                op: Op::Const,
15158                inputs: vec![],
15159                shape: Shape::from_dims(&[4]),
15160                dtype: DType::F32,
15161            });
15162            let b = g.push(Node {
15163                op: Op::Relu,
15164                inputs: vec![a],
15165                shape: Shape::from_dims(&[4]),
15166                dtype: DType::F32,
15167            });
15168            let m = g.push(Node {
15169                op: Op::Move {
15170                    target: DeviceLocation::Cpu,
15171                },
15172                inputs: vec![a],
15173                shape: Shape::from_dims(&[4]),
15174                dtype: DType::F32,
15175            });
15176            let out = g.push(Node {
15177                op: Op::Add,
15178                inputs: vec![b, m],
15179                shape: Shape::from_dims(&[4]),
15180                dtype: DType::F32,
15181            });
15182            g.set_target_backend(b, BackendId::Cpu);
15183            g.set_target_backend(m, BackendId::Cpu);
15184            g.set_target_backend(out, BackendId::Cpu);
15185            (a, out)
15186        };
15187        let mut inputs = StorageCache::new();
15188        inputs.insert(a_id, Arc::new(RwLock::new(a)));
15189
15190        let (out, _) = PipelinedExecutor::realize(graph, out_id, inputs)
15191            .expect("realize add(relu(a), move(a))");
15192        let guard = out.read().unwrap();
15193        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15194            panic!()
15195        };
15196        assert_eq!(
15197            c.as_slice::<f32>().unwrap(),
15198            &[2.0, 4.0, 6.0, 8.0],
15199            "relu(a) must run before move(a) evicts a",
15200        );
15201    }
15202
15203    /// A Move whose source is itself in the realize target set must
15204    /// not evict it — the caller asked for the source's storage. The
15205    /// destructive cleanup's `target_set` gate covers Move exactly
15206    /// like Release.
15207    #[test]
15208    fn pipelined_op_move_source_in_target_set_not_evicted() {
15209        let a = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0]);
15210        let graph = Arc::new(RwLock::new(Graph::new()));
15211        let (a_id, move_id) = {
15212            let mut g = graph.write().unwrap();
15213            let a = g.push(Node {
15214                op: Op::Const,
15215                inputs: vec![],
15216                shape: Shape::from_dims(&[2]),
15217                dtype: DType::F32,
15218            });
15219            let mv = g.push(Node {
15220                op: Op::Move {
15221                    target: DeviceLocation::Cpu,
15222                },
15223                inputs: vec![a],
15224                shape: Shape::from_dims(&[2]),
15225                dtype: DType::F32,
15226            });
15227            g.set_target_backend(mv, BackendId::Cpu);
15228            (a, mv)
15229        };
15230        let a_arc = Arc::new(RwLock::new(a));
15231        let a_arc_external = Arc::clone(&a_arc);
15232        let mut inputs = StorageCache::new();
15233        inputs.insert(a_id, a_arc);
15234
15235        let out = PipelinedExecutor::realize_many(graph, &[move_id, a_id], inputs)
15236            .expect("realize_many [move, source]");
15237        assert_eq!(out.len(), 2);
15238        let mv_guard = out[0].0.read().unwrap();
15239        let fuel_memory::BackendStorage::Cpu(c) = &mv_guard.inner else {
15240            panic!()
15241        };
15242        assert_eq!(c.as_slice::<f32>().unwrap(), &[5.0, 6.0]);
15243        assert!(
15244            Arc::ptr_eq(&out[1].0, &a_arc_external),
15245            "requested source must survive the Move's destructive cleanup",
15246        );
15247    }
15248
15249    // --- realize_many (Phase 7.6 step 9c Phase A) ----------------
15250
15251    /// realize_many on empty targets returns an empty Vec — no graph
15252    /// walk, no panic.
15253    #[test]
15254    fn pipelined_realize_many_empty_targets() {
15255        let graph = Arc::new(RwLock::new(Graph::new()));
15256        let inputs = StorageCache::new();
15257        let out = PipelinedExecutor::realize_many(graph, &[], inputs).expect("realize_many");
15258        assert!(out.is_empty());
15259    }
15260
15261    /// realize_many with two independent target chains. Each chain's
15262    /// output is in the cache; the shared topo walk realizes both.
15263    /// Verifies parallel chain handling + return order matches input.
15264    #[test]
15265    fn pipelined_realize_many_two_independent_targets() {
15266        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
15267        let rhs = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
15268        let graph = Arc::new(RwLock::new(Graph::new()));
15269        let (lhs_id, rhs_id, add_id, mul_id) = {
15270            let mut g = graph.write().unwrap();
15271            let lhs = g.push(Node {
15272                op: Op::Const,
15273                inputs: vec![],
15274                shape: Shape::from_dims(&[3]),
15275                dtype: DType::F32,
15276            });
15277            let rhs = g.push(Node {
15278                op: Op::Const,
15279                inputs: vec![],
15280                shape: Shape::from_dims(&[3]),
15281                dtype: DType::F32,
15282            });
15283            let add = g.push(Node {
15284                op: Op::Add,
15285                inputs: vec![lhs, rhs],
15286                shape: Shape::from_dims(&[3]),
15287                dtype: DType::F32,
15288            });
15289            let mul = g.push(Node {
15290                op: Op::Mul,
15291                inputs: vec![lhs, rhs],
15292                shape: Shape::from_dims(&[3]),
15293                dtype: DType::F32,
15294            });
15295            g.set_target_backend(add, BackendId::Cpu);
15296            g.set_target_backend(mul, BackendId::Cpu);
15297            (lhs, rhs, add, mul)
15298        };
15299        let mut inputs = StorageCache::new();
15300        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs)));
15301        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs)));
15302
15303        // Pass mul first to confirm return order matches targets order
15304        // (not graph order — graph order would put add first).
15305        let out = PipelinedExecutor::realize_many(graph, &[mul_id, add_id], inputs)
15306            .expect("realize_many");
15307        assert_eq!(out.len(), 2);
15308
15309        let mul_guard = out[0].0.read().unwrap();
15310        let fuel_memory::BackendStorage::Cpu(c) = &mul_guard.inner else {
15311            panic!()
15312        };
15313        assert_eq!(c.as_slice::<f32>().unwrap(), &[10.0, 40.0, 90.0]);
15314
15315        let add_guard = out[1].0.read().unwrap();
15316        let fuel_memory::BackendStorage::Cpu(c) = &add_guard.inner else {
15317            panic!()
15318        };
15319        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 22.0, 33.0]);
15320    }
15321
15322    /// realize_many with the same NodeId twice — caller asking for
15323    /// the same output twice. Both outputs are the same Arc (cheap).
15324    #[test]
15325    fn pipelined_realize_many_duplicate_target_returns_same_arc() {
15326        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
15327        let graph = Arc::new(RwLock::new(Graph::new()));
15328        let (in_id, neg_id) = {
15329            let mut g = graph.write().unwrap();
15330            let in_id = g.push(Node {
15331                op: Op::Const,
15332                inputs: vec![],
15333                shape: Shape::from_dims(&[3]),
15334                dtype: DType::F32,
15335            });
15336            let neg = g.push(Node {
15337                op: Op::Neg,
15338                inputs: vec![in_id],
15339                shape: Shape::from_dims(&[3]),
15340                dtype: DType::F32,
15341            });
15342            g.set_target_backend(neg, BackendId::Cpu);
15343            (in_id, neg)
15344        };
15345        let mut inputs = StorageCache::new();
15346        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
15347
15348        let out = PipelinedExecutor::realize_many(graph, &[neg_id, neg_id], inputs)
15349            .expect("realize_many");
15350        assert_eq!(out.len(), 2);
15351        assert!(
15352            Arc::ptr_eq(&out[0].0, &out[1].0),
15353            "duplicate target should share the same storage Arc",
15354        );
15355    }
15356
15357    /// realize_many with shared upstream nodes evaluates the shared
15358    /// chunk exactly once. Two targets `f = a + b` and `g = (a + b) * a`
15359    /// — `a + b` is computed once.
15360    #[test]
15361    fn pipelined_realize_many_shared_subgraph_evaluates_once() {
15362        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
15363        let b_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
15364        let graph = Arc::new(RwLock::new(Graph::new()));
15365        let (a_id, b_id, add_id, mul_id) = {
15366            let mut g = graph.write().unwrap();
15367            let a = g.push(Node {
15368                op: Op::Const,
15369                inputs: vec![],
15370                shape: Shape::from_dims(&[3]),
15371                dtype: DType::F32,
15372            });
15373            let b = g.push(Node {
15374                op: Op::Const,
15375                inputs: vec![],
15376                shape: Shape::from_dims(&[3]),
15377                dtype: DType::F32,
15378            });
15379            let add = g.push(Node {
15380                op: Op::Add,
15381                inputs: vec![a, b],
15382                shape: Shape::from_dims(&[3]),
15383                dtype: DType::F32,
15384            });
15385            let mul = g.push(Node {
15386                op: Op::Mul,
15387                inputs: vec![add, a],
15388                shape: Shape::from_dims(&[3]),
15389                dtype: DType::F32,
15390            });
15391            g.set_target_backend(add, BackendId::Cpu);
15392            g.set_target_backend(mul, BackendId::Cpu);
15393            (a, b, add, mul)
15394        };
15395        let mut inputs = StorageCache::new();
15396        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
15397        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
15398
15399        let out = PipelinedExecutor::realize_many(graph, &[add_id, mul_id], inputs)
15400            .expect("realize_many");
15401        assert_eq!(out.len(), 2);
15402
15403        let add_guard = out[0].0.read().unwrap();
15404        let fuel_memory::BackendStorage::Cpu(c) = &add_guard.inner else {
15405            panic!()
15406        };
15407        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 22.0, 33.0]);
15408
15409        let mul_guard = out[1].0.read().unwrap();
15410        let fuel_memory::BackendStorage::Cpu(c) = &mul_guard.inner else {
15411            panic!()
15412        };
15413        // (a + b) * a = [11*1, 22*2, 33*3] = [11, 44, 99].
15414        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 44.0, 99.0]);
15415    }
15416
15417    /// E2E: masked_fill with -inf — the attention masking pattern.
15418    /// x = [1, 2, 3, 4]; mask = [0, 1, 0, 1]; value = -1000.
15419    /// out = [1, -1000, 3, -1000].
15420    #[test]
15421    fn pipelined_realize_masked_fill_attention_pattern() {
15422        let x_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
15423        let mut mask_storage = fuel_memory::from_slice_cpu(&[0u8, 1, 0, 1]);
15424        mask_storage.dtype = DType::Bool; // GAP-168(c): a Bool mask, not U8 bytes
15425        let graph = Arc::new(RwLock::new(Graph::new()));
15426        let (x_id, mask_id, out_id) = {
15427            let mut g = graph.write().unwrap();
15428            let x = g.push(Node {
15429                op: Op::Const,
15430                inputs: vec![],
15431                shape: Shape::from_dims(&[4]),
15432                dtype: DType::F32,
15433            });
15434            let mask = g.push(Node {
15435                op: Op::Const,
15436                inputs: vec![],
15437                shape: Shape::from_dims(&[4]),
15438                dtype: DType::Bool,
15439            });
15440            let out = g.push(Node {
15441                op: Op::MaskedFill {
15442                    value: fuel_ir::Scalar::F32(-1000.0),
15443                },
15444                inputs: vec![x, mask],
15445                shape: Shape::from_dims(&[4]),
15446                dtype: DType::F32,
15447            });
15448            g.set_target_backend(out, BackendId::Cpu);
15449            (x, mask, out)
15450        };
15451        let mut inputs = StorageCache::new();
15452        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
15453        inputs.insert(mask_id, Arc::new(RwLock::new(mask_storage)));
15454        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
15455        let guard = result_arc.read().unwrap();
15456        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15457            panic!("expected Cpu storage");
15458        };
15459        let out: &[f32] = c.as_slice().unwrap();
15460        assert_eq!(out, &[1.0, -1000.0, 3.0, -1000.0]);
15461    }
15462
15463    // ---- WriteSlice (Phase 7.6 step 9c E.3.2) -------------------------------
15464
15465    /// E2E: pipelined realize of `Op::WriteSlice` writing a [1, 3, 2]
15466    /// source slab into a [4, 3, 2] destination at axis-0 row 2 — the
15467    /// canonical KV-cache append shape.
15468    #[test]
15469    fn pipelined_realize_write_slice_kv_cache_append() {
15470        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 24]);
15471        let src_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
15472        let graph = Arc::new(RwLock::new(Graph::new()));
15473        let (dest_id, src_id, ws_id) = {
15474            let mut g = graph.write().unwrap();
15475            let dest = g.push(Node {
15476                op: Op::Const,
15477                inputs: vec![],
15478                shape: Shape::from_dims(&[4, 3, 2]),
15479                dtype: DType::F32,
15480            });
15481            let src = g.push(Node {
15482                op: Op::Const,
15483                inputs: vec![],
15484                shape: Shape::from_dims(&[1, 3, 2]),
15485                dtype: DType::F32,
15486            });
15487            let ws = g.push(Node {
15488                op: Op::WriteSlice {
15489                    ranges: vec![(2, 3), (0, 3), (0, 2)],
15490                    dyn_offset: None,
15491                },
15492                inputs: vec![dest, src],
15493                shape: Shape::from_dims(&[4, 3, 2]), // adopts dest shape
15494                dtype: DType::F32,
15495            });
15496            g.set_target_backend(ws, BackendId::Cpu);
15497            (dest, src, ws)
15498        };
15499        let mut inputs = StorageCache::new();
15500        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
15501        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
15502        let (result_arc, _) = PipelinedExecutor::realize(graph, ws_id, inputs).expect("realize");
15503        let guard = result_arc.read().unwrap();
15504        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15505            panic!("expected Cpu storage");
15506        };
15507        let out: &[f32] = c.as_slice().unwrap();
15508        let expected = [
15509            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,
15510            6.0, // row 2 = source
15511            0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
15512        ];
15513        assert_eq!(out, &expected);
15514    }
15515
15516    /// E2E: pipelined realize of `Op::WriteSlice` adopts the
15517    /// destination's Storage Arc as the output slot (in-place
15518    /// alias) — the resulting Arc points to the SAME bytes the
15519    /// destination was constructed from.
15520    #[test]
15521    fn pipelined_realize_write_slice_aliases_dest_storage() {
15522        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
15523        let src_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
15524        let graph = Arc::new(RwLock::new(Graph::new()));
15525        let (dest_id, src_id, ws_id, dest_arc_external) = {
15526            let mut g = graph.write().unwrap();
15527            let dest = g.push(Node {
15528                op: Op::Const,
15529                inputs: vec![],
15530                shape: Shape::from_dims(&[3, 2]),
15531                dtype: DType::F32,
15532            });
15533            let src = g.push(Node {
15534                op: Op::Const,
15535                inputs: vec![],
15536                shape: Shape::from_dims(&[1, 2]),
15537                dtype: DType::F32,
15538            });
15539            let ws = g.push(Node {
15540                op: Op::WriteSlice {
15541                    ranges: vec![(1, 2), (0, 2)],
15542                    dyn_offset: None,
15543                },
15544                inputs: vec![dest, src],
15545                shape: Shape::from_dims(&[3, 2]),
15546                dtype: DType::F32,
15547            });
15548            g.set_target_backend(ws, BackendId::Cpu);
15549            let arc = Arc::new(RwLock::new(dest_storage));
15550            (dest, src, ws, arc)
15551        };
15552        let mut inputs = StorageCache::new();
15553        inputs.insert(dest_id, Arc::clone(&dest_arc_external));
15554        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
15555        let (result_arc, _) = PipelinedExecutor::realize(graph, ws_id, inputs).expect("realize");
15556        // Bytes were written into the same Arc the caller held —
15557        // the WriteSlice op aliases dest's Storage Arc, not allocates
15558        // a fresh buffer.
15559        assert!(
15560            Arc::ptr_eq(&result_arc, &dest_arc_external),
15561            "WriteSlice output Arc must be the same Arc as the destination's"
15562        );
15563        let guard = dest_arc_external.read().unwrap();
15564        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15565            panic!("expected Cpu storage");
15566        };
15567        let out: &[f32] = c.as_slice().unwrap();
15568        assert_eq!(out, &[0.0, 0.0, 10.0, 20.0, 0.0, 0.0]);
15569    }
15570
15571    // ---- WriteSlice dynamic offset (Phase D symbolic extents) ---------------
15572
15573    /// E2E: pipelined realize of `Op::WriteSlice` with a runtime start
15574    /// offset (`dyn_offset`) resolved through a per-pass `SymEnv`. The
15575    /// width-2 source slab lands at the bound offset (3), not the static
15576    /// `ranges[0].0` placeholder (0) — the persistent-decode KV-cache
15577    /// write at a per-token `cached_len`.
15578    #[test]
15579    fn pipelined_realize_write_slice_dynamic_offset() {
15580        use fuel_ir::{DynScalar, SymId};
15581        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
15582        let src_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0]);
15583        let graph = Arc::new(RwLock::new(Graph::new()));
15584        let sym = SymId(0);
15585        let (dest_id, src_id, ws_id) = {
15586            let mut g = graph.write().unwrap();
15587            let dest = g.push(Node {
15588                op: Op::Const,
15589                inputs: vec![],
15590                shape: Shape::from_dims(&[6]),
15591                dtype: DType::F32,
15592            });
15593            let src = g.push(Node {
15594                op: Op::Const,
15595                inputs: vec![],
15596                shape: Shape::from_dims(&[2]),
15597                dtype: DType::F32,
15598            });
15599            let ws = g.push(Node {
15600                // ranges[0] = (0, 2): the start is a placeholder (ignored —
15601                // overridden by dyn_offset); only the width (2) is read.
15602                op: Op::WriteSlice {
15603                    ranges: vec![(0, 2)],
15604                    dyn_offset: Some((0, DynScalar::Sym(sym))),
15605                },
15606                inputs: vec![dest, src],
15607                shape: Shape::from_dims(&[6]),
15608                dtype: DType::F32,
15609            });
15610            g.set_target_backend(ws, BackendId::Cpu);
15611            (dest, src, ws)
15612        };
15613        let mut inputs = StorageCache::new();
15614        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
15615        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
15616
15617        // Bind cached_len = 3: the slab must land at indices [3, 4].
15618        let mut env = SymEnv::new();
15619        env.bind(sym, 3).unwrap();
15620
15621        let (result_arc, _) = PipelinedExecutor::realize_with_env(graph, ws_id, inputs, env)
15622            .expect("realize_with_env");
15623        let guard = result_arc.read().unwrap();
15624        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15625            panic!("expected Cpu storage");
15626        };
15627        let out: &[f32] = c.as_slice().unwrap();
15628        assert_eq!(
15629            out,
15630            &[0.0, 0.0, 0.0, 7.0, 8.0, 0.0],
15631            "slab must land at the SymEnv-bound offset 3, not the static placeholder 0",
15632        );
15633    }
15634
15635    /// Increment 2a — the data-determined bind seam. After
15636    /// `Op::NonZeroIndices` realizes, the executor reads its runtime count
15637    /// from bundle slot 1 and PUBLISHES it into the produced `SymEnv` under
15638    /// `count_sym`. This is the first op to bind a *data-determined* symbol
15639    /// mid-realize (all prior binds are host-known before realize) — the
15640    /// keystone capability for SSM decode / MoE sparsity / MLA KV.
15641    #[test]
15642    fn pipelined_realize_nonzero_indices_publishes_count() {
15643        use fuel_ir::SymId;
15644        use fuel_ir::storage::{OutputViewSpec, compose_bundle};
15645        // flat [0,1,0,1,1,0] → 3 nonzeros at 1,3,4; capacity 6.
15646        let x_storage = fuel_memory::from_slice_cpu(&[0.0_f32, 1.0, 0.0, 1.0, 1.0, 0.0]);
15647        let graph = Arc::new(RwLock::new(Graph::new()));
15648        let count_sym = SymId(0);
15649        let (x_id, nzi_id) = {
15650            let mut g = graph.write().unwrap();
15651            let x = g.push(Node {
15652                op: Op::Const,
15653                inputs: vec![],
15654                shape: Shape::from_dims(&[2, 3]),
15655                dtype: DType::F32,
15656            });
15657            let capacity = 6usize;
15658            let idx_shape = Shape::from_dims(&[capacity]);
15659            let cnt_shape = Shape::from_dims(&[1]);
15660            let specs = vec![
15661                OutputViewSpec {
15662                    dtype: DType::U32,
15663                    shape: idx_shape.clone(),
15664                    layout: Layout::contiguous(idx_shape.clone()),
15665                    name: Some("indices"),
15666                },
15667                OutputViewSpec {
15668                    dtype: DType::U32,
15669                    shape: cnt_shape.clone(),
15670                    layout: Layout::contiguous(cnt_shape),
15671                    name: Some("count"),
15672                },
15673            ];
15674            let (_bytes, views) = compose_bundle(&specs).unwrap();
15675            let nzi = g.push(Node {
15676                op: Op::NonZeroIndices { count_sym },
15677                inputs: vec![x],
15678                shape: idx_shape,
15679                dtype: DType::U32,
15680            });
15681            g.set_output_views(nzi, Arc::from(views.into_boxed_slice()))
15682                .unwrap();
15683            g.set_target_backend(nzi, BackendId::Cpu);
15684            (x, nzi)
15685        };
15686        let mut inputs = StorageCache::new();
15687        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
15688
15689        let (_arc, _layout, produced) =
15690            PipelinedExecutor::realize_with_env_producing(graph, nzi_id, inputs, SymEnv::new())
15691                .expect("realize_with_env_producing");
15692
15693        assert_eq!(
15694            produced.get(count_sym),
15695            Some(3),
15696            "the executor must publish the data-determined nonzero count into the SymEnv",
15697        );
15698    }
15699
15700    /// A `dyn_offset` whose symbol is unbound in the `SymEnv` surfaces a
15701    /// typed error at realize (never a panic).
15702    #[test]
15703    fn pipelined_realize_write_slice_dynamic_offset_unbound_errors() {
15704        use fuel_ir::{DynScalar, SymId};
15705        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
15706        let src_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0]);
15707        let graph = Arc::new(RwLock::new(Graph::new()));
15708        let (dest_id, src_id, ws_id) = {
15709            let mut g = graph.write().unwrap();
15710            let dest = g.push(Node {
15711                op: Op::Const,
15712                inputs: vec![],
15713                shape: Shape::from_dims(&[6]),
15714                dtype: DType::F32,
15715            });
15716            let src = g.push(Node {
15717                op: Op::Const,
15718                inputs: vec![],
15719                shape: Shape::from_dims(&[2]),
15720                dtype: DType::F32,
15721            });
15722            let ws = g.push(Node {
15723                op: Op::WriteSlice {
15724                    ranges: vec![(0, 2)],
15725                    dyn_offset: Some((0, DynScalar::Sym(SymId(0)))),
15726                },
15727                inputs: vec![dest, src],
15728                shape: Shape::from_dims(&[6]),
15729                dtype: DType::F32,
15730            });
15731            g.set_target_backend(ws, BackendId::Cpu);
15732            (dest, src, ws)
15733        };
15734        let mut inputs = StorageCache::new();
15735        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
15736        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
15737        // Empty env — the symbol is unbound.
15738        let result = PipelinedExecutor::realize_with_env(graph, ws_id, inputs, SymEnv::new());
15739        assert!(
15740            result.is_err(),
15741            "unbound dyn_offset symbol must surface a typed error, not a panic",
15742        );
15743    }
15744
15745    /// A runtime offset whose resolved slab runs past the destination
15746    /// capacity errors at realize (never an out-of-bounds write).
15747    #[test]
15748    fn pipelined_realize_write_slice_dynamic_offset_out_of_capacity_errors() {
15749        use fuel_ir::{DynScalar, SymId};
15750        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
15751        let src_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0]);
15752        let graph = Arc::new(RwLock::new(Graph::new()));
15753        let sym = SymId(0);
15754        let (dest_id, src_id, ws_id) = {
15755            let mut g = graph.write().unwrap();
15756            let dest = g.push(Node {
15757                op: Op::Const,
15758                inputs: vec![],
15759                shape: Shape::from_dims(&[6]),
15760                dtype: DType::F32,
15761            });
15762            let src = g.push(Node {
15763                op: Op::Const,
15764                inputs: vec![],
15765                shape: Shape::from_dims(&[2]),
15766                dtype: DType::F32,
15767            });
15768            let ws = g.push(Node {
15769                op: Op::WriteSlice {
15770                    ranges: vec![(0, 2)],
15771                    dyn_offset: Some((0, DynScalar::Sym(sym))),
15772                },
15773                inputs: vec![dest, src],
15774                shape: Shape::from_dims(&[6]),
15775                dtype: DType::F32,
15776            });
15777            g.set_target_backend(ws, BackendId::Cpu);
15778            (dest, src, ws)
15779        };
15780        let mut inputs = StorageCache::new();
15781        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
15782        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
15783        // offset 5 + width 2 = 7 > capacity 6.
15784        let mut env = SymEnv::new();
15785        env.bind(sym, 5).unwrap();
15786        let result = PipelinedExecutor::realize_with_env(graph, ws_id, inputs, env);
15787        assert!(
15788            result.is_err(),
15789            "resolved slab past destination capacity must surface a typed error",
15790        );
15791    }
15792
15793    /// Regression for the PipelinedExecutor ordering-integration session.
15794    ///
15795    /// Graph: `x = Const`, `step_x = Step(x)`, `y = SigmoidInplace(x)`.
15796    /// `Step` and `SigmoidInplace` are both readers of `x`; `Step` is
15797    /// non-destructive, `SigmoidInplace` mutates `x`'s storage. The
15798    /// correct semantic is for `Step` to read PRE-mutation bytes.
15799    ///
15800    /// Pre-this-session (raw `topo_order_multi`): the two are siblings
15801    /// in topo order and the tie-break is unspecified — `SigmoidInplace`
15802    /// could run first, making `step_x` see post-sigmoid bytes
15803    /// (`[1, 1, 1, 1]` because every sigmoid output is positive).
15804    ///
15805    /// Post-this-session: `execution_plan` consults `derive_ordering`,
15806    /// which pins `SigmoidInplace` AFTER every other reader of `x`.
15807    /// `step_x` deterministically sees `x` and is `[1, 0, 1, 0]`.
15808    #[test]
15809    fn pipelined_inplace_with_multiple_readers_orders_correctly() {
15810        use fuel_ir::Shape;
15811        let data = [1.0_f32, -2.0, 3.0, -4.0];
15812        let src_storage = fuel_memory::from_slice_cpu(&data);
15813
15814        let graph = Arc::new(RwLock::new(Graph::new()));
15815        let (x_id, step_id, sig_id) = {
15816            let mut g = graph.write().unwrap();
15817            let x = g.push(Node {
15818                op: Op::Const,
15819                inputs: vec![],
15820                shape: Shape::from_dims(&[4]),
15821                dtype: DType::F32,
15822            });
15823            let step = g.push(Node {
15824                op: Op::Step,
15825                inputs: vec![x],
15826                shape: Shape::from_dims(&[4]),
15827                dtype: DType::F32,
15828            });
15829            let sig = g.push(Node {
15830                op: Op::SigmoidInplace,
15831                inputs: vec![x],
15832                shape: Shape::from_dims(&[4]),
15833                dtype: DType::F32,
15834            });
15835            g.set_target_backend(step, BackendId::Cpu);
15836            g.set_target_backend(sig, BackendId::Cpu);
15837            (x, step, sig)
15838        };
15839
15840        let mut cache = StorageCache::new();
15841        cache.insert(x_id, Arc::new(RwLock::new(src_storage)));
15842
15843        let results = PipelinedExecutor::realize_many(graph, &[step_id, sig_id], cache)
15844            .expect("realize_many");
15845
15846        // step_x must reflect pre-mutation x: sign of [1, -2, 3, -4] →
15847        // [1, 0, 1, 0]. If the executor ran SigmoidInplace first, step
15848        // would see all-positive sigmoid outputs and produce [1, 1, 1, 1].
15849        let step_guard = results[0].0.read().unwrap();
15850        let fuel_memory::BackendStorage::Cpu(c) = &step_guard.inner else {
15851            panic!("expected Cpu storage for step output");
15852        };
15853        let step_out: &[f32] = c.as_slice().expect("f32 cast");
15854        assert_eq!(
15855            step_out,
15856            &[1.0_f32, 0.0, 1.0, 0.0],
15857            "Step must run before SigmoidInplace; got post-mutation bytes"
15858        );
15859        drop(step_guard);
15860
15861        // SigmoidInplace's output Arc IS the mutated cache entry — bytes
15862        // approximate sigmoid([1, -2, 3, -4]).
15863        let sig_guard = results[1].0.read().unwrap();
15864        let fuel_memory::BackendStorage::Cpu(c) = &sig_guard.inner else {
15865            panic!("expected Cpu storage for sigmoid output");
15866        };
15867        let sig_out: &[f32] = c.as_slice().expect("f32 cast");
15868        let sig_ref = [
15869            1.0_f32 / (1.0 + (-1.0_f32).exp()),
15870            1.0_f32 / (1.0 + (2.0_f32).exp()),
15871            1.0_f32 / (1.0 + (-3.0_f32).exp()),
15872            1.0_f32 / (1.0 + (4.0_f32).exp()),
15873        ];
15874        for (got, want) in sig_out.iter().zip(sig_ref.iter()) {
15875            assert!((got - want).abs() < 1e-6, "sigmoid: got {got}, want {want}");
15876        }
15877    }
15878
15879    /// Regression for the PipelinedExecutor ordering-integration session.
15880    ///
15881    /// Canonical residual-connection pattern:
15882    ///   `x = Const`, `y = ReluInplace(x)`, `z = Add(y, x)`.
15883    ///
15884    /// Pre-this-session: `derive_ordering` was never run, so the cycle
15885    /// (Add must precede ReluInplace per ordering edge; Add must follow
15886    /// ReluInplace per data-flow edge through y) was undetected. The
15887    /// executor produced `z = relu(x) + relu(x) = [2, 0, 6, 0]` —
15888    /// silently wrong.
15889    ///
15890    /// Post-this-session: `insert_safety_copies` runs before
15891    /// `execution_plan`, inserts `Op::Copy(x) → x_safe`, rewires Add's
15892    /// `x` input to `x_safe`. Result: `z = relu(x) + x = [2, -2, 6, -4]`.
15893    #[test]
15894    fn pipelined_residual_connection_inserts_safety_copy() {
15895        use fuel_ir::Shape;
15896        let data = [1.0_f32, -2.0, 3.0, -4.0];
15897        let src_storage = fuel_memory::from_slice_cpu(&data);
15898
15899        let graph = Arc::new(RwLock::new(Graph::new()));
15900        let (x_id, _y_id, z_id) = {
15901            let mut g = graph.write().unwrap();
15902            let x = g.push(Node {
15903                op: Op::Const,
15904                inputs: vec![],
15905                shape: Shape::from_dims(&[4]),
15906                dtype: DType::F32,
15907            });
15908            let y = g.push(Node {
15909                op: Op::ReluInplace,
15910                inputs: vec![x],
15911                shape: Shape::from_dims(&[4]),
15912                dtype: DType::F32,
15913            });
15914            let z = g.push(Node {
15915                op: Op::Add,
15916                inputs: vec![y, x],
15917                shape: Shape::from_dims(&[4]),
15918                dtype: DType::F32,
15919            });
15920            g.set_target_backend(y, BackendId::Cpu);
15921            g.set_target_backend(z, BackendId::Cpu);
15922            (x, y, z)
15923        };
15924
15925        let mut cache = StorageCache::new();
15926        cache.insert(x_id, Arc::new(RwLock::new(src_storage)));
15927
15928        let (result_arc, _) = PipelinedExecutor::realize(graph, z_id, cache)
15929            .expect("realize z — insert_safety_copies must break the cycle");
15930
15931        let guard = result_arc.read().unwrap();
15932        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15933            panic!("expected Cpu storage");
15934        };
15935        let got: &[f32] = c.as_slice().expect("f32 cast");
15936        assert_eq!(
15937            got,
15938            &[2.0_f32, -2.0, 6.0, -4.0],
15939            "Add must read pre-mutation x via the inserted safety copy"
15940        );
15941    }
15942
15943    // ------------------------------------------------------------------
15944    // Item 3 end-to-end: SelectiveScan through the bundled-output
15945    // PipelinedExecutor path. The producer allocates bundled
15946    // (y_bytes + last_state_bytes), the kernel writes both slots,
15947    // and the bundled-tuple builder returns each via Op::View.
15948    // ------------------------------------------------------------------
15949
15950    fn cpu_const_f32(
15951        graph: &Arc<RwLock<Graph>>,
15952        cache: &mut StorageCache,
15953        data: &[f32],
15954        dims: &[usize],
15955    ) -> NodeId {
15956        let id = {
15957            let mut g = graph.write().unwrap();
15958            g.push(Node {
15959                op: Op::Const,
15960                inputs: vec![],
15961                shape: Shape::from_dims(dims),
15962                dtype: DType::F32,
15963            })
15964        };
15965        cache.insert(id, Arc::new(RwLock::new(fuel_memory::from_slice_cpu(data))));
15966        id
15967    }
15968
15969    /// `selective_scan_bundled` realizes both `y` and `last_state` in
15970    /// a single `realize_many` pass; the Views project the same
15971    /// producer's bundled Storage Arc and the numerics match the
15972    /// hand-computed single-step kernel test (b=1,s=1,d=1,k=1).
15973    #[test]
15974    fn pipelined_realize_selective_scan_bundled_produces_y_and_last_state() {
15975        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
15976        let mut cache = StorageCache::new();
15977
15978        let u_id = cpu_const_f32(&graph, &mut cache, &[3.0], &[1, 1, 1]);
15979        let delta_id = cpu_const_f32(&graph, &mut cache, &[1.0], &[1, 1, 1]);
15980        let a_id = cpu_const_f32(&graph, &mut cache, &[-1.0], &[1, 1]);
15981        let b_id = cpu_const_f32(&graph, &mut cache, &[2.0], &[1, 1, 1]);
15982        let c_id = cpu_const_f32(&graph, &mut cache, &[0.5], &[1, 1, 1]);
15983
15984        let (y_id, last_state_id) = {
15985            let u_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), u_id);
15986            let delta_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), delta_id);
15987            let a_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), a_id);
15988            let b_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), b_id);
15989            let c_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), c_id);
15990            let (y, last_state) = u_t
15991                .selective_scan_bundled(&delta_t, &a_t, &b_t, &c_t, /* delta_softplus */ false)
15992                .expect("selective_scan_bundled");
15993            (y.id(), last_state.id())
15994        };
15995        // Set target_backend on the producer (View nodes inherit it).
15996        {
15997            let mut g = graph.write().unwrap();
15998            let producer = g.node(y_id).inputs[0];
15999            g.set_target_backend(producer, BackendId::Cpu);
16000        }
16001
16002        let outputs =
16003            PipelinedExecutor::realize_many(Arc::clone(&graph), &[y_id, last_state_id], cache)
16004                .expect("realize_many");
16005        let (y_arc, y_layout) = outputs[0].clone();
16006        let (last_state_arc, last_state_layout) = outputs[1].clone();
16007
16008        // Both Views project the same bundled producer Storage Arc.
16009        assert!(
16010            Arc::ptr_eq(&y_arc, &last_state_arc),
16011            "y and last_state Views project the SAME bundled producer Storage",
16012        );
16013
16014        // Hand-computed numerics (single-step recurrence):
16015        // h[0,0,0] = exp(1.0 * -1.0) * 0 + 1.0 * 2.0 * 3.0 = 6.0
16016        // y[0,0,0] = h * c = 6.0 * 0.5 = 3.0
16017        // last_state[0,0,0] = h = 6.0
16018        let guard = y_arc.read().unwrap();
16019        let fuel_memory::BackendStorage::Cpu(c_bytes) = &guard.inner else {
16020            panic!("expected Cpu storage");
16021        };
16022        let typed: &[f32] = c_bytes.as_slice().expect("f32 cast");
16023        assert_eq!(y_layout.start_offset(), 0);
16024        let y_value = typed[y_layout.start_offset()];
16025        assert!((y_value - 3.0).abs() < 1e-5, "y expected 3.0 got {y_value}");
16026        assert_eq!(
16027            last_state_layout.start_offset(),
16028            1,
16029            "slot 1 byte_offset 4 / sizeof(f32) = 1",
16030        );
16031        let ls_value = typed[last_state_layout.start_offset()];
16032        assert!(
16033            (ls_value - 6.0).abs() < 1e-5,
16034            "last_state expected 6.0 got {ls_value}"
16035        );
16036    }
16037
16038    // ---- Ordering-defect repros (MLA decode multi-round WriteSlice) -----
16039
16040    /// DIAGNOSTIC (not a repro by itself): a plain single-hop view chain
16041    /// `S = Slice(X); K = Relu(S)` competing with a SECOND destructive
16042    /// WriteSlice on `X` (`Y = WriteSlice(X, ...)`) within one
16043    /// `realize_many` call. `collect_alias_set` adds `S` to `X`'s alias
16044    /// set (Slice IS `is_view_op`), so `derive_ordering` pins `Y` after
16045    /// `S`'s reader `K` directly. This form is expected to STAY GREEN —
16046    /// recorded here as the control that isolates the Reshape-specific
16047    /// gap exercised by the next test.
16048    #[test]
16049    fn pipelined_write_slice_round2_plain_slice_reader_not_stranded() {
16050        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16051        let mut cache = StorageCache::new();
16052
16053        let b_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16054        let src1_id = cpu_const_f32(&graph, &mut cache, &[1.0, 2.0], &[2]);
16055        let src2_id = cpu_const_f32(&graph, &mut cache, &[99.0, 98.0], &[2]);
16056
16057        let (k_id, y_id) = {
16058            let mut g = graph.write().unwrap();
16059            let x_id = g.push(Node {
16060                op: Op::WriteSlice {
16061                    ranges: vec![(0, 2)],
16062                    dyn_offset: None,
16063                },
16064                inputs: vec![b_id, src1_id],
16065                shape: Shape::from_dims(&[4]),
16066                dtype: DType::F32,
16067            });
16068            let s_id = g.push(Node {
16069                op: Op::Slice {
16070                    dim: 0,
16071                    start: 0,
16072                    len: 2,
16073                },
16074                inputs: vec![x_id],
16075                shape: Shape::from_dims(&[2]),
16076                dtype: DType::F32,
16077            });
16078            let k_id = g.push(Node {
16079                op: Op::Relu,
16080                inputs: vec![s_id],
16081                shape: Shape::from_dims(&[2]),
16082                dtype: DType::F32,
16083            });
16084            // Round 2 OVERLAPS round 1's [0,2) range so a wrong-order
16085            // execution would be numerically visible in K's output.
16086            let y_id = g.push(Node {
16087                op: Op::WriteSlice {
16088                    ranges: vec![(0, 2)],
16089                    dyn_offset: None,
16090                },
16091                inputs: vec![x_id, src2_id],
16092                shape: Shape::from_dims(&[4]),
16093                dtype: DType::F32,
16094            });
16095            g.set_target_backend(x_id, BackendId::Cpu);
16096            g.set_target_backend(k_id, BackendId::Cpu);
16097            g.set_target_backend(y_id, BackendId::Cpu);
16098            (k_id, y_id)
16099        };
16100
16101        let plan = fuel_graph::opt::execution_plan(&graph.read().unwrap(), &[k_id, y_id]);
16102        eprintln!("[diagnostic plain-slice] execution_plan = {:?}", plan,);
16103
16104        let outputs = PipelinedExecutor::realize_many(Arc::clone(&graph), &[k_id, y_id], cache)
16105            .expect("realize_many: plain slice reader must not error");
16106        let (k_arc, _) = &outputs[0];
16107        let guard = k_arc.read().unwrap();
16108        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16109            panic!("expected Cpu storage");
16110        };
16111        let out: &[f32] = c.as_slice().unwrap();
16112        assert_eq!(
16113            out,
16114            &[1.0, 2.0],
16115            "K = relu(slice(X,0,2)) must read PRE-round-2 bytes; got {:?}",
16116            out,
16117        );
16118    }
16119
16120    /// CRITICAL SUSPECT #2 repro: `Op::Reshape`/`Op::Contiguize` compile
16121    /// to `WorkItemKind::ContiguizeOf`, which zero-copy ADOPTS the
16122    /// input's Storage Arc when the input is contiguous at offset 0 —
16123    /// but `Op::Reshape` is NOT in `collect_alias_set`'s alias-extending
16124    /// predicate (only `Op::is_view_op` + `Op::View{..}`). So for
16125    /// `X = write_slice(B, src1); S = X.slice(0, 0, 2) [offset-0
16126    /// contiguous]; R = S.reshape([2]); K = relu(R); Y =
16127    /// write_slice(X, src2)`, `collect_alias_set(X)` stops at `{X, S}`
16128    /// — `R` never enters the alias set, so `derive_ordering` never
16129    /// scans `R`'s consumers (`K`) for pinning against `Y`. `K` and `Y`
16130    /// become simultaneously "ready" once `R` completes, and
16131    /// `execution_plan`'s stable tiebreak (smaller `topo_order_multi`
16132    /// position wins) can schedule `Y` (destructive) BEFORE `K` — `K`
16133    /// then dereferences `R`'s adopted Arc (== `X`'s Arc, mutated
16134    /// in-place by `Y`) and silently reads POST-`Y` bytes. No error;
16135    /// wrong numbers.
16136    #[test]
16137    fn pipelined_write_slice_reshape_adopted_arc_reader_reads_pre_write_bytes() {
16138        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16139        let mut cache = StorageCache::new();
16140
16141        let b_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16142        let src1_id = cpu_const_f32(&graph, &mut cache, &[1.0, 2.0], &[2]);
16143        let src2_id = cpu_const_f32(&graph, &mut cache, &[99.0, 98.0], &[2]);
16144
16145        let (x_id, k_id, y_id) = {
16146            let mut g = graph.write().unwrap();
16147            let x_id = g.push(Node {
16148                op: Op::WriteSlice {
16149                    ranges: vec![(0, 2)],
16150                    dyn_offset: None,
16151                },
16152                inputs: vec![b_id, src1_id],
16153                shape: Shape::from_dims(&[4]),
16154                dtype: DType::F32,
16155            });
16156            let s_id = g.push(Node {
16157                // OFFSET-0 contiguous prefix slice — ContiguizeOf's
16158                // zero-copy fast path requires this at execute time.
16159                op: Op::Slice {
16160                    dim: 0,
16161                    start: 0,
16162                    len: 2,
16163                },
16164                inputs: vec![x_id],
16165                shape: Shape::from_dims(&[2]),
16166                dtype: DType::F32,
16167            });
16168            let r_id = g.push(Node {
16169                op: Op::Reshape(Shape::from_dims(&[2])),
16170                inputs: vec![s_id],
16171                shape: Shape::from_dims(&[2]),
16172                dtype: DType::F32,
16173            });
16174            let k_id = g.push(Node {
16175                op: Op::Relu,
16176                inputs: vec![r_id],
16177                shape: Shape::from_dims(&[2]),
16178                dtype: DType::F32,
16179            });
16180            // Round 2 OVERLAPS round 1's [0,2) range (not the [2,4)
16181            // tail) so a wrong-order execution is numerically visible
16182            // in K's output — a disjoint round 2 would corrupt bytes
16183            // K never reads, masking the defect.
16184            let y_id = g.push(Node {
16185                op: Op::WriteSlice {
16186                    ranges: vec![(0, 2)],
16187                    dyn_offset: None,
16188                },
16189                inputs: vec![x_id, src2_id],
16190                shape: Shape::from_dims(&[4]),
16191                dtype: DType::F32,
16192            });
16193            g.set_target_backend(x_id, BackendId::Cpu);
16194            g.set_target_backend(k_id, BackendId::Cpu);
16195            g.set_target_backend(y_id, BackendId::Cpu);
16196            (x_id, k_id, y_id)
16197        };
16198        let _ = x_id;
16199
16200        let plan = fuel_graph::opt::execution_plan(&graph.read().unwrap(), &[k_id, y_id]);
16201        eprintln!(
16202            "[diagnostic reshape-adopted-arc] execution_plan = {:?}",
16203            plan,
16204        );
16205
16206        let outputs = PipelinedExecutor::realize_many(Arc::clone(&graph), &[k_id, y_id], cache)
16207            .expect("realize_many");
16208        let (k_arc, _) = &outputs[0];
16209        let guard = k_arc.read().unwrap();
16210        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16211            panic!("expected Cpu storage");
16212        };
16213        let out: &[f32] = c.as_slice().unwrap();
16214        // K = relu(reshape(slice(X,0,2))) must read PRE-round-2 bytes:
16215        // relu([1.0, 2.0]) = [1.0, 2.0]. Round 2 overwrites the SAME
16216        // [0,2) range with [99.0, 98.0] — if Y (round 2) runs before K
16217        // (the ordering defect), K instead observes [99.0, 98.0].
16218        assert_eq!(
16219            out,
16220            &[1.0, 2.0],
16221            "K must read PRE-round-2 bytes through the adopted Arc; got {:?} \
16222             (post-round-2 corruption if this fails)",
16223            out,
16224        );
16225    }
16226
16227    /// The MLA-decode shape from `rebind_latent_cache_fresh_graph`'s doc
16228    /// (`fuel-core/src/lazy_deepseek2.rs`): layer L's post-append buffer
16229    /// `X_L_N` (round N) is read TWICE within one realize call — once
16230    /// (non-destructively) through a Slice+Reshape "attention math" view
16231    /// chain whose result becomes an ancestor of layer L+1's round-N
16232    /// write, and again as the DESTINATION of layer L's round-(N+1)
16233    /// append. Reproduces the same Reshape-adoption gap as
16234    /// `pipelined_write_slice_reshape_adopted_arc_reader_reads_pre_write_bytes`
16235    /// at 2-layer scale, confirming the defect is not an artifact of the
16236    /// single-hop minimal form.
16237    #[test]
16238    fn pipelined_write_slice_mla_two_layer_round2_reshape_reader_not_stranded() {
16239        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16240        let mut cache = StorageCache::new();
16241
16242        let b_l_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16243        let src_l_n_id = cpu_const_f32(&graph, &mut cache, &[1.0, 2.0], &[2]);
16244        let b_l1_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16245        let src_l_n1_id = cpu_const_f32(&graph, &mut cache, &[99.0, 98.0], &[2]);
16246
16247        let (x_l_n1_id, x_l1_n_id) = {
16248            let mut g = graph.write().unwrap();
16249            // Round N, layer L: append src_l_n into b_l.
16250            let x_l_n = g.push(Node {
16251                op: Op::WriteSlice {
16252                    ranges: vec![(0, 2)],
16253                    dyn_offset: None,
16254                },
16255                inputs: vec![b_l_id, src_l_n_id],
16256                shape: Shape::from_dims(&[4]),
16257                dtype: DType::F32,
16258            });
16259            // "Attention math" for round N at layer L: read the filled
16260            // prefix, reshape (head-split-style hop), then a kernel.
16261            let s_l_n = g.push(Node {
16262                op: Op::Slice {
16263                    dim: 0,
16264                    start: 0,
16265                    len: 2,
16266                },
16267                inputs: vec![x_l_n],
16268                shape: Shape::from_dims(&[2]),
16269                dtype: DType::F32,
16270            });
16271            let rs_l_n = g.push(Node {
16272                op: Op::Reshape(Shape::from_dims(&[2])),
16273                inputs: vec![s_l_n],
16274                shape: Shape::from_dims(&[2]),
16275                dtype: DType::F32,
16276            });
16277            let r_l_n = g.push(Node {
16278                op: Op::Relu,
16279                inputs: vec![rs_l_n],
16280                shape: Shape::from_dims(&[2]),
16281                dtype: DType::F32,
16282            });
16283            // Round N, layer L+1: append the attention-math result.
16284            let x_l1_n = g.push(Node {
16285                op: Op::WriteSlice {
16286                    ranges: vec![(0, 2)],
16287                    dyn_offset: None,
16288                },
16289                inputs: vec![b_l1_id, r_l_n],
16290                shape: Shape::from_dims(&[4]),
16291                dtype: DType::F32,
16292            });
16293            // Round N+1, layer L: append into x_l_n directly (SAME node
16294            // s_l_n/rs_l_n/r_l_n read from) — OVERLAPPING range so a
16295            // wrong-order execution is numerically visible downstream.
16296            let x_l_n1 = g.push(Node {
16297                op: Op::WriteSlice {
16298                    ranges: vec![(0, 2)],
16299                    dyn_offset: None,
16300                },
16301                inputs: vec![x_l_n, src_l_n1_id],
16302                shape: Shape::from_dims(&[4]),
16303                dtype: DType::F32,
16304            });
16305            g.set_target_backend(x_l_n, BackendId::Cpu);
16306            g.set_target_backend(r_l_n, BackendId::Cpu);
16307            g.set_target_backend(x_l1_n, BackendId::Cpu);
16308            g.set_target_backend(x_l_n1, BackendId::Cpu);
16309            (x_l_n1, x_l1_n)
16310        };
16311
16312        let plan = fuel_graph::opt::execution_plan(&graph.read().unwrap(), &[x_l1_n_id, x_l_n1_id]);
16313        eprintln!("[diagnostic mla-2-layer] execution_plan = {:?}", plan);
16314
16315        let outputs =
16316            PipelinedExecutor::realize_many(Arc::clone(&graph), &[x_l1_n_id, x_l_n1_id], cache)
16317                .expect("realize_many");
16318        // outputs[0] = x_l1_n = write_slice(b_l1, relu(reshape(slice(x_l_n))))
16319        // Must reflect round-N's PRE-round-(N+1) bytes: relu([1,2]) = [1,2].
16320        let (x_l1_n_arc, _) = &outputs[0];
16321        let guard = x_l1_n_arc.read().unwrap();
16322        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16323            panic!("expected Cpu storage");
16324        };
16325        let out: &[f32] = c.as_slice().unwrap();
16326        assert_eq!(
16327            out,
16328            &[1.0, 2.0, 0.0, 0.0],
16329            "layer L+1's round-N append must reflect PRE-round-(N+1) attention \
16330             math output; got {:?} (post-round-(N+1) corruption if this fails)",
16331            out,
16332        );
16333    }
16334}