Skip to main content

fuel_dispatch/
pipelined.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Pipelined compile + execute. Phase 7.5 B4.
3//!
4//! [`PipelinedExecutor::realize`] runs compilation and execution on
5//! separate threads connected by a channel: a compiler thread walks
6//! the graph in topological order and emits work items; the
7//! executor (this thread) consumes them, allocates output Storage,
8//! calls the kernel, and stores the result in an internal cache.
9//! Both threads run concurrently so execution can begin while
10//! compilation is still resolving later nodes.
11//!
12//! Today's "compile" step is a single binding-table lookup —
13//! roughly nanoseconds per node. The threading delivers no
14//! measurable speedup in this regime. The pipelining infrastructure
15//! exists *now* — built on the [`compile_node`] / [`crate::compiled::execute_compiled`]
16//! interface from B5 — so future work that grows the compile step
17//! (residency-aware planning, transfer-cost minimization, kernel
18//! auto-tuning) plugs in without revisiting call sites.
19//!
20//! ## Storage during the migration
21//!
22//! `fuel_graph::Graph::storage_map` uses the legacy
23//! `fuel_backend_contract::Storage` (the `Box<dyn DynBackendStorage>`
24//! newtype). The pipelined executor uses the new
25//! `fuel_memory::Storage` (BackendStorage enum + dtype). During
26//! the migration the two coexist — neither is converted on the fly.
27//! The pipelined executor takes pre-realized inputs as a
28//! `HashMap<NodeId, Arc<RwLock<fuel_memory::Storage>>>` rather
29//! than reading from the graph's storage_map. Phase D unifies the
30//! two paths once kernel migration completes.
31//!
32//! ## Op coverage
33//!
34//! B4 supports `Op::Const` (input-cache adoption — no kernel call)
35//! and `Op::Add` on f32 (mapped to `OpKind::AddElementwise`).
36//! Phase C adds the rest as more (op, dtype) bindings register.
37
38use std::collections::{HashMap, HashSet};
39use std::sync::mpsc::{Sender, channel};
40use std::sync::{Arc, RwLock};
41use std::thread;
42
43use fuel_graph::opt::{execution_plan, insert_safety_copies};
44use fuel_graph::registry::FusedOpParams;
45use fuel_graph::{Graph, Node, NodeId, Op, PickedRoute};
46use fuel_ir::dispatch::OpKind;
47use fuel_ir::probe::BackendId;
48use fuel_ir::{DType, DeviceLocation, Error, Layout, Result, SymEnv};
49
50use crate::compiled::{
51    CompiledNode, CompletionHandle, compile_node, execute_compiled_with_wait_hint,
52};
53use crate::dispatch::global_bindings;
54use crate::kernel::{KernelBindingTable, KernelDTypes, MatmulM, OpParams};
55use crate::optimize::OptimizedGraph;
56use crate::ranker::{BackendRuntimeLookup, RuntimeSelector, resolve_branch};
57// `pick_route` is called only by the streamed-vs-one-shot equivalence test
58// below; the executor itself resolves branch-by-branch via `resolve_branch`.
59#[cfg(test)]
60use crate::ranker::pick_route;
61use fuel_memory::Storage;
62
63/// How the executor derives its dispatch order + topology-generation
64/// stamp for the `TopologyChanged` chunk-boundary check.
65///
66/// PR-A3b-1 of the "plan IS the graph" rebuild: the realize bridge can
67/// now drive the executor from `optimize_graph`'s in-place form via
68/// [`OptimizedGraph::dispatch_order`] (`extract_runs`/`lower_run`)
69/// instead of the legacy `ExecutionPlan`-supplied order. Both arms
70/// compute the *same* `NodeId` sequence on a branchless graph (the
71/// A3a equivalence gate proved `dispatch_order == compile_plan(...).order`);
72/// the only difference is the source of truth.
73///
74/// - [`OrderSource::Default`] — recompute via `execution_plan` inside
75///   the executor (the pre-A3b-1 behavior; the legacy `ExecutionPlan`
76///   path and the plain `realize`/`realize_many` entries use this).
77/// - [`OrderSource::Optimized`] — derive from the `OptimizedGraph`'s
78///   run lowering, computed AFTER `insert_safety_copies` so the order
79///   covers any safety-copy nodes the executor just inserted. Carries
80///   the optimize-time `generation` so the chunk-boundary
81///   `TopologyChanged` check still fires (the new path dispatches with
82///   `plan: None`, so the generation must come from here instead).
83///
84///   PR-C1: it also carries an optional **route** ([`PickedRoute`]) — the
85///   runtime route picker (Picker 2) chose one arm per `Op::Branch`. When
86///   `Some`, the order is the route-aware lowering
87///   ([`fuel_graph::lower_picked_route`]); when `None` (or empty) it is
88///   the arm-0 lowering (`lower_runs_arm0`), byte-identical to Phase B.
89enum OrderSource<'a> {
90    Default,
91    Optimized {
92        optimized: &'a OptimizedGraph,
93        /// The route the picker resolved (one arm per branch). `None` ⇒
94        /// arm-0 everywhere (no picker / no pressure ⇒ Phase B behavior).
95        route: Option<&'a PickedRoute>,
96    },
97    /// Step E Phase C, PR C1 — the **streaming run-walk**. Instead of a
98    /// route resolved up front, the compiler thread resolves each branch
99    /// **lazily, as the topo walk reaches its arm-entry**, via
100    /// [`resolve_branch`] over the threaded [`StreamingPick`]. The order is
101    /// never pre-flattened: the compiler thread interleaves arm resolution,
102    /// node compilation, and dispatch (so C2 can later read live device
103    /// load at the moment a branch resolves). Still VRAM-only selection in
104    /// C1, so the streamed order equals the one-shot
105    /// [`OrderSource::Optimized`]`{route: Some(pick_route(..))}` order
106    /// byte-for-byte.
107    Streaming {
108        optimized: &'a OptimizedGraph,
109        pick: &'a StreamingPick,
110    },
111    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
112    /// §5): memoizes the `Optimized { route: None }` arm's dispatch order
113    /// WHOLESALE in `order_cache`, computed once and reused by the caller
114    /// across repeated calls over an unchanged graph/roots — the plan-once
115    /// persistent-decode shape, where only leaf values are rebound between
116    /// tokens, never the graph's structure. Safe because that recompute is
117    /// a pure function of (graph structure, roots, generation) when none of
118    /// those change — proven, not assumed, by
119    /// `dispatch_order_is_stable_across_repeated_calls_with_no_mutation`
120    /// (`fuel-dispatch/src/optimize.rs`). A cache miss falls back to the
121    /// exact `Optimized { route: None }` computation and populates the
122    /// cache for next time; `generation_for` still reports `optimized`'s
123    /// generation, so the existing `TopologyChanged` chunk-boundary check
124    /// fires exactly as it would for `Optimized` — if the topology changes
125    /// underneath a cached session, realize fails loudly (the existing
126    /// contract), it does not silently serve a stale order.
127    Cached {
128        optimized: &'a OptimizedGraph,
129        order_cache: &'a std::sync::OnceLock<Vec<NodeId>>,
130    },
131}
132
133/// Owned arm-resolution config threaded into the compiler thread for the
134/// [`OrderSource::Streaming`] walk (Step E Phase C, PR C1). The selector +
135/// lookup are owned `Arc`s (not borrows) so they can be `move`d into the
136/// spawned compiler thread; both are `Send + Sync`. The per-arm candidate
137/// bindings are read from [`global_bindings`] inside the thread (as the
138/// eager `pick_route_for` does), so they are not carried here.
139///
140/// The streaming walk consults the SAME selector chain as the one-shot
141/// picker (the production `ChainedSelector`). As of C2 that chain is
142/// load-aware: its key is `(pressure_tier, load_tier, latency_ns,
143/// original_index)`, and the `load_tier` leg reads B1's in-flight counter
144/// through the selector's own `BackendRuntimeLookup` handle (the
145/// `BackendStreams` seam). Under no load / no pressure every leg is the
146/// no-signal default, so the lazy resolution yields the same arm as the
147/// eager `pick_route` on every input — byte-identical to pre-C2.
148#[derive(Clone)]
149pub(crate) struct StreamingPick {
150    /// The runtime selector the streaming walk consults at each branch —
151    /// the production `ChainedSelector` (VRAM-pressure guard + load tier +
152    /// Judge rank). It holds its own `BackendRuntimeLookup`, so it reads
153    /// both VRAM fit and live device load off that lookup's handles.
154    pub selector: Arc<dyn RuntimeSelector>,
155}
156
157/// Map from NodeId to a realized Storage Arc. Used both as the
158/// input cache (passed in by the caller for pre-realized leaves)
159/// and as the output cache (built up during execution).
160pub type StorageCache = HashMap<NodeId, Arc<RwLock<Storage>>>;
161
162/// The per-realize device handles live in [`crate::device_registry`] (ROADMAP row 137, seam S3 step 3b-3);
163/// re-exported here so the path every caller already uses keeps working.
164pub use crate::device_registry::DeviceRegistry;
165
166/// A registry holding the CUDA device of every CUDA storage among a captured decode's inputs. The capture API
167/// takes tensors, not devices, so the devices are read off the caller's own inputs once, here, and handed to the
168/// executor like any other caller's registry; the executor no longer scans a cache for them.
169#[cfg(feature = "cuda")]
170fn cuda_registry_of_inputs(inputs: &StorageCache) -> DeviceRegistry {
171    let mut registry = DeviceRegistry::new();
172    for arc in inputs.values() {
173        if let Ok(guard) = arc.read()
174            && let fuel_memory::BackendStorage::Cuda(c) = &guard.inner
175        {
176            registry = registry.with_cuda(c.device().clone());
177        }
178    }
179    registry
180}
181
182/// Persistent per-node output buffers for CUDA-graph capture (the
183/// "CapturedRun executor" build-out). Maps each compute node's [`NodeId`]
184/// to a FIXED-ADDRESS output [`Storage`] Arc that survives across realizes,
185/// so a captured graph's baked kernel-argument addresses stay valid on
186/// replay.
187///
188/// Two modes, both driven by the executor's Kernel arm:
189/// - **`Record`** (warm run): the executor allocates each kernel output as
190///   usual AND records the Arc here. Produces the fixed buffers.
191/// - **`Reuse`** (capture / replay run): the executor REUSES the recorded
192///   Arc for each node — no allocation (mandatory inside a capture scope) —
193///   and the kernel's write-into path writes into it in place.
194///
195/// `None` (the param default at every existing realize call site) preserves
196/// byte-identical behavior: fresh alloc every realize, nothing recorded.
197pub struct PersistentOutputs {
198    map: HashMap<NodeId, Arc<RwLock<Storage>>>,
199    mode: PersistentMode,
200}
201
202#[derive(Clone, Copy, PartialEq, Eq)]
203enum PersistentMode {
204    /// Warm run: allocate + record each kernel output.
205    Record,
206    /// Capture / replay run: reuse the recorded buffer (no alloc).
207    Reuse,
208}
209
210impl PersistentOutputs {
211    /// A fresh recording map for the warm run.
212    pub fn recording() -> Self {
213        Self {
214            map: HashMap::new(),
215            mode: PersistentMode::Record,
216        }
217    }
218
219    /// A reuse map for the capture / replay run, seeded with the buffers
220    /// a prior warm run recorded.
221    pub fn reuse(map: HashMap<NodeId, Arc<RwLock<Storage>>>) -> Self {
222        Self {
223            map,
224            mode: PersistentMode::Reuse,
225        }
226    }
227
228    /// Consume, yielding the recorded NodeId→buffer map (to seed a
229    /// [`reuse`](Self::reuse) map for the capture run).
230    pub fn into_map(self) -> HashMap<NodeId, Arc<RwLock<Storage>>> {
231        self.map
232    }
233}
234
235/// Whether a kernel op's CUDA dispatch wrapper writes its result INTO the
236/// executor-provided `outputs[0]` buffer (rather than allocating a fresh
237/// output and replacing it). Only write-into ops are safe in the
238/// executor's Reuse (capture) mode: a replace-the-buffer wrapper would
239/// allocate inside the capture scope AND change the output's device
240/// address, invalidating the captured graph. [`capture_decode`] rejects
241/// any graph whose compute nodes fall outside this set — a surfaced
242/// capability gap (telemetry-worthy), never a silent miscompile.
243///
244/// The set is the full decode op-set, all VERIFIED to replay bit-exact under
245/// capture (each with a forced-freed-memory-reuse test — see the `diag_*` and
246/// `capture_decode_*` GPU tests).
247///
248/// **History / the big correction (2026-07-10):** `MatMul` and `IndexSelect`
249/// were *briefly* excluded on the belief they weren't capture-safe (matmul's
250/// "cuBLAS internal state", index_select's "host arrays / driver anomaly").
251/// That was ALL WRONG — it was a single Fuel-side bug: `capture_decode`
252/// consumed `inputs` and retained only compute OUTPUTS, so any input buffer
253/// (weights, embedding table) the caller didn't independently hold was FREED
254/// after capture, and the captured graph replayed against freed/reused memory
255/// → intermittent partial-wrong output (cuBLAS "split-K columns", index_select
256/// "element 0"). Fixed by `CapturedDecode::retained_inputs`. cuBLAS gemm +
257/// index_select then replay bit-exact (0/50 even with forced reuse), so the
258/// baracuda GEMV + gather_rows are NOT needed for capture-safety.
259///
260/// **`Rope` (`OpKind::Rope`, corrected 2026-07-11)**: previously excluded on
261/// the (now-disproven) assumption that decode's rope always goes through
262/// `rope_with_tables` (decomposed to elementwise ops including `Concat`, see
263/// below) rather than this fused single-input kernel. Tracing a real Llama
264/// decode graph's capture_decode rejection (`capture_decode_matches_persistent`
265/// GPU test, `fuel-core`) found `Op::Rope` nodes placed by the optimizer
266/// (`rope_with_tables` is not always selected — shape-dependent). The
267/// dispatch wrapper (`cuda_rope_baracuda_wrapper!` in
268/// `baracuda_dispatch.rs`) already delegates to baracuda's write-into
269/// `rope_*_into` FFI — that mechanism predates this predicate fix, it was
270/// simply never added here. `rope.fkc.md`'s CUDA kernel is audited
271/// (`docs/architecture/10-decisions-log.md`, 2026-07-11): grid-stride,
272/// one thread per output element, reads only its own rotation-pair partner,
273/// no atomics/shared-memory/cross-thread state — genuinely capture-safe.
274///
275/// **`Concat` (4b-γ) is capture-safe ONLY for N==2 inputs** — baracuda's
276/// `concat2_into` write-into path covers exactly the decode graph's only
277/// Concat (the rope rotate-half's 2-input `concat(-x2, x1)`, from
278/// `rope_with_tables`'s CUDA decomposition). This predicate alone can't
279/// express the N-arity condition (a pure `OpKind -> bool` fn has no access
280/// to `OpParams`); `capture_decode`'s validation loop adds an explicit N>2
281/// rejection alongside the `op_kind_is_capture_writeinto` check so N>2
282/// Concat is refused at validation time, before the warm pass ever runs —
283/// the write-into wrapper's N>2 fallback (which still allocates internally
284/// for its N-2 intermediates) is therefore provably never invoked while
285/// `persistent.mode == Reuse`. N-ary write-into concat is a real future gap
286/// if a consumer needs it; not built here (no consumer today).
287///
288/// **`Op::Contiguize` (4b-γ)** — `WorkItemKind::ContiguizeOf`, not a
289/// `Kernel` work item, so this predicate never even sees it — became
290/// capture-safe via a separate write-into path (`contiguize_into`) wired
291/// directly into the `ContiguizeOf` executor arm's `PersistentOutputs`
292/// consultation, mirroring how `Kernel` nodes consult this predicate. No
293/// change needed here or in `capture_decode`'s validation loop: a given
294/// `ContiguizeOf` node's allocate-vs-zero-copy branch is a static
295/// layout/stride property, identical across the warm and capture passes
296/// (both replay the same compiled item list), so it's unconditionally safe
297/// once wired to `PersistentOutputs`.
298///
299/// LESSON: a bug reproduced through the full harness but not in isolation is
300/// the harness's fault, not the callee's — chase the differentiator (here,
301/// input lifetime), don't conclude "kernel/library not capture-safe" from it.
302///
303/// [`capture_decode`]: PipelinedExecutor::capture_decode
304/// GAP-217b: gated on `cuda` because its ONLY caller is
305/// `capture_decode` (`#[cfg(feature = "cuda")]`, ~:1266). Without this it
306/// reports as dead code on every default build — a false signal on a
307/// predicate whose doc comment is a record of hard-won capture-safety
308/// findings, i.e. exactly the kind of item someone eventually deletes for
309/// being "unused". Gating it makes the reachability claim honest instead of
310/// leaving a warning to argue the opposite.
311#[cfg(feature = "cuda")]
312fn op_kind_is_capture_writeinto(op: OpKind) -> bool {
313    matches!(
314        op,
315        // Binary elementwise — residual + gating.
316        OpKind::AddElementwise
317            | OpKind::SubElementwise
318            | OpKind::MulElementwise
319            | OpKind::DivElementwise
320            | OpKind::MaximumElementwise
321            | OpKind::MinimumElementwise
322            | OpKind::PowElementwise
323            | OpKind::RemElementwise
324            // Softmax.
325            | OpKind::SoftmaxLastDim
326            | OpKind::LogSoftmaxLastDim
327            // Affine (mul_scalar/add_scalar — the 1/√d attention scale).
328            | OpKind::Affine
329            // Dense matmul (cuBLAS gemm_dense — capture-safe; the earlier
330            // "not replay-stable" was the dangling-input bug, now fixed).
331            | OpKind::MatMul
332            // Embedding lookup (was the same dangling-input bug, not a kernel issue).
333            | OpKind::IndexSelect
334            // RMS-norm: capture-safe via the device's fixed workspace for its
335            // per-row RMS scratch (warm sizes it; capture + replay reuse, no alloc).
336            | OpKind::RmsNormLastDim
337            // Unary activations (write-into + workspace-free).
338            | OpKind::SiluElementwise
339            | OpKind::GeluTanhElementwise
340            | OpKind::GeluElementwise
341            // Negation (write-into + workspace-free) — the rope rotate-half
342            // decomposition's `neg_second` half (CapturedRun 4b-resume: rope
343            // runs decomposed on CUDA since there's no rotate-half fused kernel).
344            | OpKind::NegElementwise
345            // N==2 concat only (rope rotate-half) — see the doc comment
346            // above; N>2 is rejected explicitly in capture_decode's
347            // validation loop, not by this predicate.
348            | OpKind::Concat
349            // Rotary position embedding (fused single-input kernel) — see
350            // the doc comment above.
351            | OpKind::Rope
352    )
353}
354
355/// The product of [`PipelinedExecutor::capture_decode`]: a replayable
356/// CUDA-graph capture of a single-device decode step plus the handle to
357/// the fixed output buffer the captured launches write into.
358///
359/// Replay contract: update the fixed INPUT buffers (the Arcs passed into
360/// `capture_decode`) in place via H2D, call [`run`](Self::run)`.replay()`,
361/// then read [`output`](Self::output) — the captured launches recompute
362/// into it at the same device addresses. `persistent` holds every compute
363/// node's fixed buffer (the same addresses baked into the graph), exposed
364/// so a caller can inspect / retain them across replays.
365#[cfg(feature = "cuda")]
366pub struct CapturedDecode {
367    /// The instantiated, replayable capture.
368    pub run: fuel_cuda_backend::CapturedRun,
369    /// The realize target's fixed output buffer (written by replay).
370    pub output: Arc<RwLock<Storage>>,
371    /// The target's resolved output [`Layout`].
372    pub output_layout: Layout,
373    /// Every compute node's fixed output buffer (the capture-baked
374    /// addresses). Retained so they outlive the [`CapturedRun`].
375    pub persistent: HashMap<NodeId, Arc<RwLock<Storage>>>,
376    /// EVERY input buffer's Arc (weights, KV, per-token inputs), retained so
377    /// their device addresses — baked into the captured graph — stay valid
378    /// for the life of the capture. Without this, an input buffer the CALLER
379    /// doesn't independently hold is freed when `capture_decode` returns
380    /// (it consumes `inputs`), and replay reads freed/reused memory. This is
381    /// the fix for the "index_select / matmul mis-replay" — a dangling input
382    /// pointer, NOT a kernel/cuBLAS/driver capture issue.
383    pub retained_inputs: Vec<Arc<RwLock<Storage>>>,
384}
385
386/// Warm→capture→replay orchestration over [`capture_decode`] for a
387/// persistent decode loop (the CapturedRun build-out, Increment 4a).
388///
389/// Owns the FIXED per-token INPUT buffers — the ones that change each token
390/// (token-id, rope position, mask, KV write offset) — at stable device
391/// addresses, plus the [`CapturedDecode`]. Each generated token is one
392/// [`replay_token`](Self::replay_token): H2D-update the fixed input buffers
393/// IN PLACE (same addresses the captured graph reads), replay the captured
394/// graph (one `cuGraphLaunch`, no per-op launch overhead), then read the
395/// output at its fixed address.
396///
397/// The mechanism is graph-agnostic: [`capture`](Self::capture) runs a
398/// single-device CUDA decode graph through the persistent-output executor;
399/// the model layer (fuel-core's `DecodeSession`) supplies the held graph +
400/// the fixed buffers and drives the per-token updates. Every compute op must
401/// be capture-safe (`op_kind_is_capture_writeinto`) — `capture` surfaces any
402/// that are not (today: matmul, index_select — pending baracuda kernels).
403///
404/// [`capture_decode`]: PipelinedExecutor::capture_decode
405#[cfg(feature = "cuda")]
406pub struct CapturedDecodeSession {
407    device: fuel_cuda_backend::CudaDevice,
408    captured: CapturedDecode,
409    /// Per-token input buffers, keyed by NodeId — fixed device addresses
410    /// updated in place each token (the input addresses the captured graph
411    /// reads). A subset of the `inputs` handed to [`capture`](Self::capture).
412    per_token_inputs: HashMap<NodeId, Arc<RwLock<Storage>>>,
413    /// EVERY input buffer's Arc (weights, KV, per-token), retained so their
414    /// device addresses stay valid for the life of the capture. `capture_decode`
415    /// consumes `inputs` and only `CapturedDecode` retains the compute-output
416    /// buffers, so without this the WEIGHT input buffers would be freed and the
417    /// captured graph would replay against freed memory.
418    _retained_inputs: Vec<Arc<RwLock<Storage>>>,
419}
420
421#[cfg(feature = "cuda")]
422impl CapturedDecodeSession {
423    /// Capture the decode graph once against the given fixed input buffers.
424    ///
425    /// `inputs` are ALL the graph's leaves (weights, KV, per-token data) at
426    /// fixed device addresses; `per_token_input_ids` names the subset that
427    /// changes each token. The per-token Arcs are snapshotted (shared, not
428    /// copied) so overwriting them in place later feeds the captured graph's
429    /// fixed input reads. Returns a session ready for
430    /// [`replay_token`](Self::replay_token). Errors (never panics) if the
431    /// graph carries a capture-unsafe op or a per-token id is not an input.
432    pub fn capture(
433        graph: Arc<RwLock<Graph>>,
434        target: NodeId,
435        inputs: StorageCache,
436        per_token_input_ids: &[NodeId],
437        sym_env: SymEnv,
438    ) -> Result<Self> {
439        use fuel_memory::BackendStorage;
440        // Snapshot the per-token input Arcs + retain EVERY input Arc BEFORE
441        // `inputs` is consumed by capture_decode (so no input buffer's device
442        // address is freed while the captured graph still bakes it).
443        let retained_inputs: Vec<Arc<RwLock<Storage>>> = inputs.values().cloned().collect();
444        let mut per_token_inputs = HashMap::with_capacity(per_token_input_ids.len());
445        for &id in per_token_input_ids {
446            let arc = inputs.get(&id).cloned().ok_or_else(|| {
447                Error::Msg(format!(
448                    "CapturedDecodeSession::capture: per-token input {:?} not in inputs",
449                    id,
450                ))
451                .bt()
452            })?;
453            per_token_inputs.insert(id, arc);
454        }
455        // Derive the CUDA device from any input.
456        let device = {
457            let any = per_token_inputs
458                .values()
459                .next()
460                .or_else(|| inputs.values().next())
461                .ok_or_else(|| {
462                    Error::Msg("CapturedDecodeSession::capture: no inputs".into()).bt()
463                })?;
464            let guard = any.read().map_err(|_| poisoned("input storage"))?;
465            match &guard.inner {
466                BackendStorage::Cuda(c) => c.device().clone(),
467                other => {
468                    return Err(Error::Msg(format!(
469                        "CapturedDecodeSession::capture: input is BackendStorage::{:?}, not Cuda",
470                        other.backend_id(),
471                    ))
472                    .bt());
473                }
474            }
475        };
476        let captured = PipelinedExecutor::capture_decode(graph, target, inputs, sym_env)?;
477        Ok(Self {
478            device,
479            captured,
480            per_token_inputs,
481            _retained_inputs: retained_inputs,
482        })
483    }
484
485    /// Replay one token. For each `(node_id, host_bytes)` in `updates`,
486    /// overwrite that per-token input buffer IN PLACE (H2D, same device
487    /// address), then replay the captured graph and return the output buffer
488    /// (now holding this token's result). `host_bytes.len()` must equal the
489    /// buffer's byte length.
490    /// **Every compute node's output buffer, keyed by `NodeId`** — the
491    /// capture's inspection surface.
492    ///
493    /// Capture is usually described as a launch-overhead optimization, and that
494    /// is what Fuel currently exploits (measured 4.28x at k=1). But recording
495    /// the graph has a second, unexploited consequence: **every intermediate
496    /// gets a FIXED device address that survives across replays.** On the
497    /// ordinary path intermediates are transient — allocated, consumed, freed —
498    /// so there is nothing to look at after the fact.
499    ///
500    /// That makes a captured session a **whole-graph, per-node, addressable
501    /// snapshot of what actually executed**, which is a different artifact from
502    /// anything the planner records. `OptimizedGraph::placement_of` says what
503    /// the optimizer DECIDED; this says what the device HELD. Those can
504    /// disagree, and an independent second instrument is the only way to notice.
505    ///
506    /// Uses this enables, none of which need re-running the model:
507    /// - read any intermediate after a token;
508    /// - compare per-node against a CPU oracle — whole-graph differential,
509    ///   where FKC verification today is per-KERNEL;
510    /// - measure real per-op divergence for the tolerance/Judge work instead of
511    ///   modelling it.
512    ///
513    /// Buffers are live device memory owned by the capture; they are overwritten
514    /// by the next `replay_token`. Read them before replaying again.
515    pub fn node_outputs(&self) -> &HashMap<NodeId, Arc<RwLock<Storage>>> {
516        &self.captured.persistent
517    }
518
519    pub fn replay_token(&self, updates: &[(NodeId, &[u8])]) -> Result<Arc<RwLock<Storage>>> {
520        use fuel_memory::BackendStorage;
521        for (id, bytes) in updates {
522            let arc = self.per_token_inputs.get(id).ok_or_else(|| {
523                Error::Msg(format!(
524                    "CapturedDecodeSession::replay_token: {:?} is not a per-token input",
525                    id,
526                ))
527                .bt()
528            })?;
529            let guard = arc.read().map_err(|_| poisoned("per-token input"))?;
530            match &guard.inner {
531                BackendStorage::Cuda(c) => c.write_from_host(bytes)?,
532                other => {
533                    return Err(Error::Msg(format!(
534                        "CapturedDecodeSession::replay_token: input {:?} is \
535                         BackendStorage::{:?}, not Cuda",
536                        id,
537                        other.backend_id(),
538                    ))
539                    .bt());
540                }
541            }
542        }
543        self.captured.run.replay(&self.device)?;
544        self.device.synchronize()?;
545        Ok(Arc::clone(&self.captured.output))
546    }
547
548    /// The fixed output buffer, updated by each
549    /// [`replay_token`](Self::replay_token). Holds the warm-run result until
550    /// the first replay.
551    pub fn output(&self) -> &Arc<RwLock<Storage>> {
552        &self.captured.output
553    }
554
555    /// The output's resolved [`Layout`].
556    pub fn output_layout(&self) -> &Layout {
557        &self.captured.output_layout
558    }
559}
560
561/// What flavor of work item the executor is processing.
562/// Disambiguates the four cases:
563enum WorkItemKind {
564    /// `Op::Const` — its Storage Arc is already in the input cache.
565    /// Executor verifies the entry exists and moves on.
566    ConstAdopt,
567    /// Metadata-only view op (`Op::Transpose`, `Op::Permute`,
568    /// `Op::BroadcastTo`): the output's Storage Arc IS the
569    /// input's Storage Arc (bytes shared); `output_layout`
570    /// describes the strided view.
571    ViewOf { input: NodeId },
572    /// Reshape-style adoption: the output is contiguous in
573    /// `output_layout.shape()`. If the input is already contiguous
574    /// + zero offset, the output Arc is the input Arc (zero copy).
575    ///
576    /// Otherwise, the executor auto-contiguizes the input into a
577    /// fresh Arc and uses that.
578    ContiguizeOf { input: NodeId },
579    /// Computational kernel: allocate output, run the compiled
580    /// kernel, store the result. `compiled` is `Some(...)`.
581    Kernel,
582    /// `Op::Iota { len }` — 0-input F32 position generator
583    /// `[0.0, 1.0, …, (len-1)]`. Direct executor dispatch (no kernel /
584    /// binding-table lookup), like `WorkItemKind::Alloc`: a leaf has no
585    /// `inputs[0]` to inherit a backend from, so it can't take the normal
586    /// kernel path. The executor fills the sequence on CPU.
587    ///
588    /// `target_location` is the node's resolved placement when the planner stamped one: the CUDA
589    /// arm reads its GPU ordinal from it (`None` on an unplaced graph, which falls back to GPU 0).
590    Iota {
591        len: usize,
592        target_location: Option<DeviceLocation>,
593    },
594    /// `Op::Release` — metadata-only "this storage is no longer
595    /// needed" directive. Per `Op::Release`'s contract: the output
596    /// is a zero-element marker (NodeId placeholder for graph
597    /// bookkeeping; never read by any consumer). The executor emits
598    /// a zero-byte CPU `Storage` at the node's slot so downstream
599    /// cache lookups don't surface "missing slot" errors; the actual
600    /// deallocation of `inputs[0]` is driven by `destructive_input`
601    /// in the realize loop (Phase B), which drops the Arc held by
602    /// the cache. The held Arc's Drop chain frees device memory
603    /// (sync for CPU, stream-deferred for async backends).
604    ReleaseMarker,
605    /// `Op::WriteSlice` — in-place scatter write. The output adopts
606    /// the destination input's Storage Arc (zero-copy alias); the
607    /// kernel mutates that Arc's bytes via a write lock. The source
608    /// input's slab is copied into the destination's rectangular
609    /// region defined by `OpParams::WriteSlice`'s `ranges`.
610    ///
611    /// Carries `dest`/`source` NodeIds so the executor can:
612    /// 1. Adopt the dest's Arc as the kernel's output slot.
613    /// 2. Pass only the source as a kernel input (the dest is not
614    ///    a read-input to the kernel; it's the destination buffer
615    ///    being mutated in place).
616    ///
617    /// The realize loop's `destructive_input` cleanup evicts the
618    /// `dest` NodeId from the cache after this op runs (per
619    /// `Op::WriteSlice`'s destructive_input == Some(0) contract).
620    /// Downstream consumers read post-write bytes via this op's
621    /// own NodeId, not the dest's.
622    WriteSlice { dest: NodeId, source: NodeId },
623    /// `Op::WriteSliceRotating` — like `WriteSlice` but the rotating
624    /// axis wraps modulo `modulus`. Carries `dest`/`source`/`position`
625    /// NodeIds; the kernel reads the U32 position from `position`'s
626    /// storage and splits the write across the ring boundary if
627    /// `position % modulus + slab_len > modulus`.
628    WriteSliceRotating {
629        dest: NodeId,
630        source: NodeId,
631        position: NodeId,
632    },
633    /// `Op::WriteSliceDoff` — like `WriteSlice` but the start on `axis`
634    /// is read from a device-resident rank-0 `I64` scalar (`offset`)
635    /// at kernel launch, not host-baked. Carries `dest`/`source`/
636    /// `offset` NodeIds; the CUDA wrapper threads `offset`'s device
637    /// pointer straight to the kernel (no D2H) so a captured graph
638    /// replays at the host-updated position. No ring wrap.
639    WriteSliceDoff {
640        dest: NodeId,
641        source: NodeId,
642        offset: NodeId,
643    },
644    /// `Op::Copy { target }` — produce a fresh Storage on
645    /// `target_location`, copying bytes from `inputs[0]`'s residency.
646    ///
647    /// The kernel lookup goes through the standard binding-table path
648    /// at `(OpKind::Copy, [dt, dt], source_backend)`, so D2H is a peer
649    /// of every other op (architecture identity check #1). The
650    /// dedicated WorkItemKind exists because Op::Copy is the one op
651    /// whose output's device differs from `target_backend`:
652    /// `target_backend` is the **source** backend (where the kernel
653    /// runs — it owns the download path), while `target_location`
654    /// drives output allocation. WorkItemKind::Kernel always allocates
655    /// output on `target_backend`; Copy needs the override.
656    ///
657    /// Phase 2 of the bridge-retirement trajectory. Replaces the
658    /// per-variant `match self` in `BackendStorage::read_to_cpu_bytes`
659    /// (deleted alongside this commit) with a graph-level node the
660    /// optimizer can see, cost, and eventually fuse.
661    Copy { target_location: DeviceLocation },
662    /// `Op::Move { target }` — `Op::Copy`'s destructive sibling:
663    /// produce a fresh Storage on `target_location` via the same
664    /// data-movement kernel (binding-table lookup at
665    /// `(OpKind::Copy, [dt, dt], source_backend)`; output allocation
666    /// driven by `target_location`), then release the source. The
667    /// release half is NOT handled in the executor's arm — it rides
668    /// the realize loop's `destructive_input` cleanup
669    /// (`Op::Move::destructive_input() == Some(0)`), exactly like
670    /// `Op::Release`: the cache's Arc to the source drops after the
671    /// move runs and the Drop chain frees device memory (sync for
672    /// CPU, stream-deferred for async backends).
673    ///
674    /// Ordering safety is the graph's job, not this arm's:
675    /// `execution_plan` integrates `derive_ordering`, which pins the
676    /// Move AFTER every non-destructive reader of the source's alias
677    /// set, and `insert_safety_copies` snapshots the source for any
678    /// reader that data-flow-depends on the Move's output. A Move
679    /// therefore never strands a sibling consumer of its source.
680    ///
681    /// Same-device moves are legal and match the legacy
682    /// `GraphExecutor` contract: a plain copy producing fresh
683    /// storage on the same device, with the source still evicted
684    /// afterward.
685    Move { target_location: DeviceLocation },
686    /// `Op::Alloc { target }` — produce a freshly-allocated, zero-
687    /// initialized Storage on `target_location` with the node's shape
688    /// + dtype. Zero inputs.
689    ///
690    /// Doesn't dispatch through the binding table — the executor's
691    /// arm calls each backend's native allocator directly. For
692    /// non-CPU targets it takes the device handle from the
693    /// [`DeviceRegistry`] the caller handed the realize (a
694    /// `*_with_devices` entry point).
695    ///
696    /// Phase 3a of the bridge-retirement trajectory (post-9c).
697    /// Replaces `fuel-tensor::inference_context::alloc_zeroed_on`'s
698    /// per-`DeviceLocation` match with a graph node the optimizer
699    /// can see; the per-backend match moves from fuel-core's bridge
700    /// layer into fuel-storage's executor (the architectural dispatch
701    /// layer).
702    Alloc { target_location: DeviceLocation },
703    /// `Op::ZeroFill` — fill the input's storage bytes with zero,
704    /// in place. Adopts the input's Storage Arc as the output (same
705    /// Storage; bytes mutated). Destructive on `inputs[0]`.
706    ///
707    /// Direct executor dispatch (no binding-table lookup) per the
708    /// same rationale as `WorkItemKind::Alloc`: structural op,
709    /// per-backend dispatch. Per-backend behaviour:
710    /// - CPU: `bytes_mut().fill(0)` via the CoW path.
711    /// - CUDA: `CudaStorageBytes::zero_async` via baracuda alpha.30's
712    ///   `DeviceBuffer::zero_async` (cuMemsetD8Async, in-place).
713    /// - Vulkan: `VulkanBackend::fill_bytes_zero` via
714    ///   `vkCmdFillBuffer` — device-side, ~2× the bandwidth of the
715    ///   old host-staged zeros path that `alloc_zeroed_on` used.
716    ///
717    /// Phase 3a follow-up of bridge-retirement (post-9c). Pairs with
718    /// the uninit-alloc `WorkItemKind::Alloc` to give the
719    /// architecturally clean "Op::Alloc (uninit) → Op::ZeroFill
720    /// (explicit fill)" pipeline.
721    ZeroFill,
722    /// In-place kernel — the output adopts the input at index
723    /// `target_idx`'s Storage Arc and the kernel mutates that Arc's
724    /// bytes through a single write lock. Phase 3 of the in-place ops
725    /// infrastructure
726    /// (`docs/session-prompts/in-place-ops-infrastructure.md`).
727    ///
728    /// Kernel lookup goes through the standard binding table at
729    /// `(op_to_op_kind, [target_dtype], target_backend)`. The wrapper's
730    /// `inputs` slice is empty; `outputs[0]` is the target Arc. The
731    /// wrapper acquires `outputs[0]`'s write lock and calls the
732    /// underlying single-pointer kernel (e.g. baracuda's
733    /// `affine_inplace_*` on CUDA, or the chassis with `src == dst`
734    /// on CPU).
735    ///
736    /// Output Arc adoption: identical to `WorkItemKind::WriteSlice`
737    /// (the output's slot = the target's Arc; the realize loop's
738    /// `destructive_input` cleanup evicts the target's NodeId from the
739    /// cache afterward). Downstream consumers read post-mutation bytes
740    /// through this op's NodeId, not the target's.
741    InplaceKernel {
742        /// Index into `inputs` whose Storage Arc the output adopts.
743        /// Always equal to the source `Op::destructive_input().unwrap()`;
744        /// stored explicitly so the executor doesn't re-derive it.
745        target_idx: usize,
746    },
747    /// `Op::View { slot }` — multi-output projection (Option C,
748    /// Session 4). The output's Storage Arc IS the producer's Arc;
749    /// the WorkItem's `output_layout` was prepared by
750    /// [`fuel_graph::NodeHandle::view`] with the slot's `byte_offset`
751    /// baked into `Layout::start_offset` so downstream kernels reading
752    /// the producer's bytes as `slot_dtype` elements land on the
753    /// slot's first byte. Structurally identical to [`Self::ViewOf`]
754    /// at execute time — kept distinct so error messages and
755    /// telemetry have a clean dispatch point.
756    SlotView { producer: NodeId },
757    /// `Op::ViewOwned { slot }` — multi-output projection with an
758    /// independent destination buffer. At realize time, allocate a
759    /// fresh contiguous Storage of the slot's `(shape, dtype)` on
760    /// the producer's device, then memcpy
761    /// `producer.bytes[slot.byte_offset .. slot.byte_offset + slot.len_bytes]`
762    /// into the new storage. Session 4 ships the CPU path; non-CPU
763    /// backends return a typed error until their copy-with-offset
764    /// hooks land in the followup session.
765    SlotOwn { producer: NodeId, slot: u32 },
766}
767
768/// One unit of work emitted by the compiler thread to the executor
769/// thread.
770/// Phase name of a work item's kind, for the executor's host-phase accounting
771/// (`op_profile::PhaseTimer`). One name per variant so the table splits the
772/// per-item executor time by what the item is.
773fn work_item_kind_name(kind: &WorkItemKind) -> &'static str {
774    match kind {
775        WorkItemKind::ConstAdopt => "item.ConstAdopt",
776        WorkItemKind::ViewOf { .. } => "item.ViewOf",
777        WorkItemKind::ContiguizeOf { .. } => "item.ContiguizeOf",
778        WorkItemKind::Kernel => "item.Kernel",
779        WorkItemKind::Iota { .. } => "item.Iota",
780        WorkItemKind::ReleaseMarker => "item.ReleaseMarker",
781        WorkItemKind::WriteSlice { .. } => "item.WriteSlice",
782        WorkItemKind::WriteSliceRotating { .. } => "item.WriteSliceRotating",
783        WorkItemKind::WriteSliceDoff { .. } => "item.WriteSliceDoff",
784        WorkItemKind::Copy { .. } => "item.Copy",
785        WorkItemKind::Move { .. } => "item.Move",
786        WorkItemKind::Alloc { .. } => "item.Alloc",
787        WorkItemKind::ZeroFill => "item.ZeroFill",
788        WorkItemKind::InplaceKernel { .. } => "item.InplaceKernel",
789        WorkItemKind::SlotView { .. } => "item.SlotView",
790        WorkItemKind::SlotOwn { .. } => "item.SlotOwn",
791    }
792}
793
794/// Work items that choose no backend of their own: adopting an input-cache entry
795/// (`Op::Const`), the metadata-only view items, and `ContiguizeOf` (it runs on its
796/// input's backend; its `target_backend` is a `Cpu` placeholder, which made every
797/// Qwen3 decode step look like ~900 Vulkan -> Cpu -> Vulkan switches and forced a
798/// batch submit at each one). Their `target_backend` is a placeholder
799/// (a `Const` is always stamped `Cpu`; a view inherits its producer's or
800/// defaults to `Cpu`), so letting them take part in the chunk-boundary logic made
801/// every weight `Const` that sits between two Vulkan kernels look like a
802/// Vulkan -> Cpu -> Vulkan backend switch: the executor armed `multi_backend`,
803/// submitted the open Vulkan batch at each "switch", and then waited for it
804/// before the next Vulkan op. In Qwen3-0.6B decode that was about 400 forced
805/// submit-and-wait round trips per step (`docs/research/qwen3-vulkan-decode-profile.md`).
806fn is_backend_neutral(kind: &WorkItemKind) -> bool {
807    matches!(
808        kind,
809        WorkItemKind::ConstAdopt
810            | WorkItemKind::ViewOf { .. }
811            | WorkItemKind::SlotView { .. }
812            | WorkItemKind::ContiguizeOf { .. }
813    )
814}
815
816struct WorkItem {
817    node_id: NodeId,
818    inputs: Vec<NodeId>,
819    /// Number of elements in the output (for output Storage
820    /// allocation; multiplied by dtype size at allocation time).
821    elem_count: usize,
822    dtype: DType,
823    target_backend: BackendId,
824    /// What kind of work this represents (kernel vs adopt vs view).
825    kind: WorkItemKind,
826    /// `Some` for [`WorkItemKind::Kernel`]; `None` for the other
827    /// two. Carries the resolved kernel ref + op_params.
828    compiled: Option<CompiledNode>,
829    /// The output's [`Layout`]. For kernels: always
830    /// `Layout::contiguous(node.shape)`. For metadata-only view
831    /// ops: a strided/broadcast Layout pointing at the input's
832    /// Storage. Carried so the executor can publish the right
833    /// Layout into its layout cache and ultimately return it from
834    /// [`PipelinedExecutor::realize`].
835    output_layout: Layout,
836    /// Index into `inputs` whose storage gets destroyed by this op
837    /// (`Op::Release` / `Op::Move` → `Some(0)`; non-destructive ops
838    /// → `None`). The executor evicts the destroyed input from the
839    /// cache after the op runs, unless it's also in the realize
840    /// target set. Snapshot of `node.op.destructive_input()` at
841    /// compile time.
842    destructive_input: Option<usize>,
843    /// Multi-output bundle metadata (Option C, item 3). `Some(_)`
844    /// when the node was declared multi-output via
845    /// `Graph::set_output_views`; the Kernel arm allocates one
846    /// contiguous output Storage sized to fit every slot's bytes,
847    /// then attaches the bundle via `Storage::with_bundle` so
848    /// downstream `Op::View`/`Op::ViewOwned` nodes resolve
849    /// correctly.
850    output_bundle: Option<Arc<[fuel_ir::storage::OutputView]>>,
851}
852
853/// Merge the graph's side-effect roots into the caller's requested
854/// roots. Preserves caller order (user roots come first), dedupes,
855/// and appends side-effect-bearing nodes (`Op::Print`, `Op::Save`,
856/// etc.) so their effects fire even when not reachable from the
857/// caller's roots. Mirrors `fuel-graph-executor::extend_with_side_effect_roots`.
858///
859/// Short-circuits to a borrow-equivalent `Vec<NodeId>` when the graph
860/// has no side-effect roots — the common case during inference.
861fn extend_with_side_effect_roots(graph: &Graph, user_roots: &[NodeId]) -> Vec<NodeId> {
862    let side = graph.side_effect_roots();
863    if side.is_empty() {
864        return user_roots.to_vec();
865    }
866    let mut out = Vec::with_capacity(user_roots.len() + side.len());
867    out.extend_from_slice(user_roots);
868    for &s in side {
869        if !out.contains(&s) {
870            out.push(s);
871        }
872    }
873    out
874}
875
876/// Pipelined executor: walks a graph, compiles each node in a
877/// dedicated thread, executes the compiled stream on the calling
878/// thread.
879///
880/// # Architectural commitments (Phase 7.6 step 9c)
881///
882/// ## Fail-fast dispatch — no runtime CPU fallback
883///
884/// The binding-table lookup is fail-fast. If
885/// `global_bindings().lookup(op_kind, dtypes, backend)` returns
886/// `None`, `realize` / `realize_many` surface a typed `Error::Msg`
887/// at compile time. There is **no runtime fallback** to a CPU
888/// sibling when a registered kernel returns `Err`; we commit to the
889/// backend contract that registered kernels must succeed for shapes
890/// matching their declared coverage.
891///
892/// Rationale: per-decision-point alternatives (architecture v1.0
893/// §04) already let multiple backends register at the same key. If
894/// a backend's coverage is partial, the right answer is to register
895/// only the shapes it actually handles — not to silently fall back
896/// at runtime, which masks bugs and slows the hot path. The
897/// long-term home for "this op on this device" is graph-level
898/// dispatch insertion (Op::Copy edges to a backend that does
899/// support the shape), which makes the routing decision visible in
900/// the IR rather than hidden in the executor. Picker-arc step 4b
901/// landed exactly that: `compile_plan`'s off-device fallback
902/// (`PlanOptions::fallback_placements_for`) admits a candidate on
903/// another device when the pinned device lacks the implementation,
904/// and the bridge's cross-device-copy pass stitches residency
905/// around the off-device winner. There is exactly ONE fallback
906/// owner — the plan-time picker; this executor still dispatches
907/// fail-fast, and ops with no implementation anywhere surface the
908/// plan-time `NoBackendForOp` error.
909///
910/// This is a deliberate departure from the legacy executor's
911/// `cpu_fallback(op, inputs, shape, dtype, cache)` semantics.
912///
913/// ## Optimizer separation — callers compose
914///
915/// The pipelined executor does **not** run `fuel_graph::opt` or any
916/// `RuleRegistry` pass itself. Callers that want graph-level
917/// optimization compose it at the call site:
918///
919/// ```ignore
920/// let optimized_targets = registry.optimize_to_fixpoint(&graph, &targets);
921/// PipelinedExecutor::realize_many(graph, &optimized_targets, inputs)?;
922/// ```
923///
924/// Rationale: the legacy `GraphExecutor<B>::with_optimization(bool)`
925/// coupling reflected its per-typed-entry API surface
926/// (`realize_f32`, etc.) where the convenience of a single
927/// optimize+realize call was load-bearing. The pipelined path has
928/// a uniform `realize_many` that composes trivially — no need to
929/// re-couple them at the executor layer. This keeps the executor
930/// focused on execution and lets the optimizer evolve
931/// independently (different rule registries per call site, mid-
932/// pipeline opt+realize+opt+realize patterns, etc.).
933pub struct PipelinedExecutor;
934
935impl PipelinedExecutor {
936    /// Realize `target` and every transitive dependency. Compilation
937    /// runs in a worker thread; execution runs on the calling
938    /// thread.
939    ///
940    /// Pre-conditions:
941    ///
942    /// - Every reachable `Op::Const` node must have a corresponding
943    ///   entry in `inputs` (pre-realized Storage Arc).
944    /// - Every reachable non-`Const` node must have its
945    ///   `target_backend` set in the graph
946    ///   (`Graph::set_target_backend`).
947    /// - The op + dtype must be registered in `global_bindings()`.
948    ///
949    /// Returns the realized `Storage` Arc for `target` plus its
950    /// resolved [`Layout`]. The Layout is contiguous for kernel
951    /// outputs; for graphs whose target is a metadata-only view
952    /// op (`Op::Transpose`, `Op::Permute`, `Op::BroadcastTo`),
953    /// the returned Storage shares its bytes with an upstream
954    /// node and the Layout encodes the view's strides + offset.
955    ///
956    /// Production-correct: errors on any unmet precondition rather
957    /// than panicking.
958    pub fn realize(
959        graph: Arc<RwLock<Graph>>,
960        target: NodeId,
961        inputs: StorageCache,
962    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
963        Self::realize_inner(
964            graph,
965            target,
966            inputs,
967            OrderSource::Default,
968            SymEnv::default(),
969        )
970        .map(|(s, l, _produced)| (s, l))
971    }
972
973    /// [`Self::realize`] with the device handles the caller already holds (ROADMAP row 137, seam S3 step 3c):
974    /// a CUDA or Vulkan place named in `devices` is where the executor finds its handle. Use this for any
975    /// graph that allocates on, or copies to, a GPU; the plain [`Self::realize`] has no handle to give the
976    /// executor, so it is for CPU graphs and for graphs whose GPU work needs none.
977    pub fn realize_with_devices(
978        graph: Arc<RwLock<Graph>>,
979        target: NodeId,
980        inputs: StorageCache,
981        devices: DeviceRegistry,
982    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
983        Self::realize_inner_with(
984            graph,
985            target,
986            inputs,
987            OrderSource::Default,
988            SymEnv::default(),
989            devices,
990        )
991        .map(|(s, l, _produced)| (s, l))
992    }
993
994    /// Env-carrying sibling of [`Self::realize`]: realize `target` with a
995    /// per-pass [`SymEnv`] supplying the runtime bindings for any
996    /// `DynScalar` op params (today: `Op::WriteSlice`'s dynamic start
997    /// offset — Phase D symbolic extents). An **empty** env is
998    /// byte-identical to [`Self::realize`]; the env is consulted only by ops
999    /// that carry a `DynScalar`, so a graph with none ignores it. Uses
1000    /// the default (`execution_plan`) dispatch order.
1001    ///
1002    /// This is the input-determined path for persistent decode (the
1003    /// per-token `cached_len` write offset). The `OptimizedGraph`/route
1004    /// entry points keep an empty env until the realize bridge threads
1005    /// the session env through them (Phase D step 1, fuel-core).
1006    pub fn realize_with_env(
1007        graph: Arc<RwLock<Graph>>,
1008        target: NodeId,
1009        inputs: StorageCache,
1010        sym_env: SymEnv,
1011    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1012        Self::realize_inner(graph, target, inputs, OrderSource::Default, sym_env)
1013            .map(|(s, l, _produced)| (s, l))
1014    }
1015
1016    /// Producing sibling of [`Self::realize_with_env`]: realize `target` and
1017    /// ALSO return the [`SymEnv`] of symbols BOUND BY PRODUCERS during the
1018    /// pass — data-determined dynamic shapes (`Op::NonZeroIndices`'s
1019    /// runtime count, etc.). The returned env is disjoint from the input
1020    /// `sym_env` (which is input-determined). Empty when the graph has no
1021    /// data-determined producer. This is the observation point for the
1022    /// increment-2a bind seam; a downstream pass consumes these bindings
1023    /// as dynamic extents.
1024    pub fn realize_with_env_producing(
1025        graph: Arc<RwLock<Graph>>,
1026        target: NodeId,
1027        inputs: StorageCache,
1028        sym_env: SymEnv,
1029    ) -> Result<(Arc<RwLock<Storage>>, Layout, SymEnv)> {
1030        Self::realize_inner(graph, target, inputs, OrderSource::Default, sym_env)
1031    }
1032
1033    /// PR-A3b-1 entry: realize `target` driven from `optimized`'s
1034    /// in-place "plan IS the graph" form. The dispatch order is the
1035    /// `OptimizedGraph`'s `extract_runs`/`lower_run` lowering (computed
1036    /// after safety-copy insertion); per-node kernel resolution uses
1037    /// the binding-table-lookup path (no `ExecutionPlan`, so no
1038    /// route-picking — A3b-1 is branchless). The optimize-time
1039    /// `generation` drives the `TopologyChanged` chunk-boundary check.
1040    ///
1041    /// Pre-conditions match [`Self::realize`]: every reachable kernel-bearing
1042    /// node must have `target_backend` set (the bridge's
1043    /// `stamp_plan_backends` does this) and a registered binding.
1044    pub fn realize_with_optimized(
1045        graph: Arc<RwLock<Graph>>,
1046        target: NodeId,
1047        inputs: StorageCache,
1048        optimized: &OptimizedGraph,
1049    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1050        Self::realize_inner(
1051            graph,
1052            target,
1053            inputs,
1054            OrderSource::Optimized {
1055                optimized,
1056                route: None,
1057            },
1058            SymEnv::default(),
1059        )
1060        .map(|(s, l, _produced)| (s, l))
1061    }
1062
1063    /// [`Self::realize_with_optimized`] with the device handles the caller already holds (ROADMAP row 137,
1064    /// seam S3 step 3b): a CUDA or Vulkan place named in `devices` is not looked for in the storage cache.
1065    pub fn realize_with_optimized_with_devices(
1066        graph: Arc<RwLock<Graph>>,
1067        target: NodeId,
1068        inputs: StorageCache,
1069        optimized: &OptimizedGraph,
1070        devices: DeviceRegistry,
1071    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1072        Self::realize_inner_with(
1073            graph,
1074            target,
1075            inputs,
1076            OrderSource::Optimized {
1077                optimized,
1078                route: None,
1079            },
1080            SymEnv::default(),
1081            devices,
1082        )
1083        .map(|(s, l, _produced)| (s, l))
1084    }
1085
1086    /// [`Self::realize_with_optimized_picking_env`] with the device handles the caller already holds.
1087    #[allow(clippy::too_many_arguments)]
1088    pub fn realize_with_optimized_picking_env_with_devices(
1089        graph: Arc<RwLock<Graph>>,
1090        target: NodeId,
1091        inputs: StorageCache,
1092        optimized: &OptimizedGraph,
1093        selector: Option<Arc<dyn RuntimeSelector>>,
1094        lookup: Option<BackendRuntimeLookup>,
1095        sym_env: SymEnv,
1096        devices: DeviceRegistry,
1097    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1098        let order_source = match Self::streaming_pick_for(&graph, selector, lookup)? {
1099            Some(pick) => {
1100                return Self::realize_inner_with(
1101                    graph,
1102                    target,
1103                    inputs,
1104                    OrderSource::Streaming {
1105                        optimized,
1106                        pick: &pick,
1107                    },
1108                    sym_env,
1109                    devices,
1110                )
1111                .map(|(s, l, _produced)| (s, l));
1112            }
1113            None => OrderSource::Optimized {
1114                optimized,
1115                route: None,
1116            },
1117        };
1118        Self::realize_inner_with(graph, target, inputs, order_source, sym_env, devices)
1119            .map(|(s, l, _produced)| (s, l))
1120    }
1121
1122    /// [`Self::realize_with_optimized_picking_cached_env`] with the device handles the caller already holds.
1123    #[allow(clippy::too_many_arguments)]
1124    pub fn realize_with_optimized_picking_cached_env_with_devices(
1125        graph: Arc<RwLock<Graph>>,
1126        target: NodeId,
1127        inputs: StorageCache,
1128        optimized: &OptimizedGraph,
1129        order_cache: &std::sync::OnceLock<Vec<NodeId>>,
1130        selector: Option<Arc<dyn RuntimeSelector>>,
1131        lookup: Option<BackendRuntimeLookup>,
1132        sym_env: SymEnv,
1133        devices: DeviceRegistry,
1134    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1135        let order_source = match Self::streaming_pick_for(&graph, selector, lookup)? {
1136            Some(pick) => {
1137                return Self::realize_inner_with(
1138                    graph,
1139                    target,
1140                    inputs,
1141                    OrderSource::Streaming {
1142                        optimized,
1143                        pick: &pick,
1144                    },
1145                    sym_env,
1146                    devices,
1147                )
1148                .map(|(s, l, _produced)| (s, l));
1149            }
1150            None => OrderSource::Cached {
1151                optimized,
1152                order_cache,
1153            },
1154        };
1155        Self::realize_inner_with(graph, target, inputs, order_source, sym_env, devices)
1156            .map(|(s, l, _produced)| (s, l))
1157    }
1158
1159    /// Env-carrying sibling of [`Self::realize_with_optimized`]: same
1160    /// optimized-graph dispatch, but with a per-pass [`SymEnv`] supplying
1161    /// the runtime bindings for `DynScalar` op params (Phase D symbolic
1162    /// extents). An empty env is byte-identical to
1163    /// [`Self::realize_with_optimized`]. The realize bridge threads its session
1164    /// env through here for persistent decode.
1165    pub fn realize_with_optimized_env(
1166        graph: Arc<RwLock<Graph>>,
1167        target: NodeId,
1168        inputs: StorageCache,
1169        optimized: &OptimizedGraph,
1170        sym_env: SymEnv,
1171    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1172        Self::realize_inner(
1173            graph,
1174            target,
1175            inputs,
1176            OrderSource::Optimized {
1177                optimized,
1178                route: None,
1179            },
1180            sym_env,
1181        )
1182        .map(|(s, l, _produced)| (s, l))
1183    }
1184
1185    /// PR-C1 entry: realize `target` driven from `optimized`'s in-place
1186    /// form **following the runtime route picker's chosen arms**. The
1187    /// dispatch order is the route-aware lowering
1188    /// ([`fuel_graph::lower_picked_route`]) over `route` — the per-branch
1189    /// arm the picker (Picker 2) selected by live telemetry. A branch
1190    /// absent from `route` defaults to arm 0, so an **empty** route is
1191    /// byte-identical to [`Self::realize_with_optimized`] (the no-pressure /
1192    /// no-telemetry contract). A branchless graph has no branches ⇒ the
1193    /// route is empty ⇒ this is exactly the arm-0 path.
1194    pub fn realize_with_optimized_route(
1195        graph: Arc<RwLock<Graph>>,
1196        target: NodeId,
1197        inputs: StorageCache,
1198        optimized: &OptimizedGraph,
1199        route: &PickedRoute,
1200    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1201        Self::realize_inner(
1202            graph,
1203            target,
1204            inputs,
1205            OrderSource::Optimized {
1206                optimized,
1207                route: Some(route),
1208            },
1209            SymEnv::default(),
1210        )
1211        .map(|(s, l, _produced)| (s, l))
1212    }
1213
1214    /// Env-carrying sibling of [`Self::realize_with_optimized_route`] — the
1215    /// route-aware lowering with a per-pass [`SymEnv`]. An empty env is
1216    /// byte-identical to [`Self::realize_with_optimized_route`].
1217    pub fn realize_with_optimized_route_env(
1218        graph: Arc<RwLock<Graph>>,
1219        target: NodeId,
1220        inputs: StorageCache,
1221        optimized: &OptimizedGraph,
1222        route: &PickedRoute,
1223        sym_env: SymEnv,
1224    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1225        Self::realize_inner(
1226            graph,
1227            target,
1228            inputs,
1229            OrderSource::Optimized {
1230                optimized,
1231                route: Some(route),
1232            },
1233            sym_env,
1234        )
1235        .map(|(s, l, _produced)| (s, l))
1236    }
1237
1238    /// Cleanup Step C/D entry: the executor OWNS `Op::Branch` arm-selection.
1239    /// Given the runtime `selector` + the live device `lookup` (built
1240    /// bridge-side from the realize `Device` + Judge oracle and passed in,
1241    /// exactly like the residency `input_residency` provider), pick one arm per
1242    /// branch HERE — at dispatch — then lower the chosen route. The per-arm
1243    /// candidates are re-enumerated from the runtime binding registry + the
1244    /// graph (Step D: no threaded `ExecutionPlan`).
1245    ///
1246    /// No `selector` (the `runtime_selector_disabled()` opt-out) or a
1247    /// branchless graph yields the arm-0 lowering, byte-identical to Phase B.
1248    ///
1249    /// **Step E Phase C, PR C1 — STREAMING.** A branched graph WITH a
1250    /// selector no longer resolves the whole route up front: it routes to the
1251    /// `OrderSource::Streaming` walk, where the compiler thread resolves
1252    /// each branch lazily as the frontier reaches it (via
1253    /// [`resolve_branch`]). C1 keeps the SAME VRAM-only selector chain — so
1254    /// the streamed route equals the one-shot `pick_route` route byte-for-byte
1255    /// — and only changes *when* a branch resolves; C2 makes that moment read
1256    /// live device load.
1257    pub fn realize_with_optimized_picking_env(
1258        graph: Arc<RwLock<Graph>>,
1259        target: NodeId,
1260        inputs: StorageCache,
1261        optimized: &OptimizedGraph,
1262        selector: Option<Arc<dyn RuntimeSelector>>,
1263        lookup: Option<BackendRuntimeLookup>,
1264        sym_env: SymEnv,
1265    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1266        match Self::streaming_pick_for(&graph, selector, lookup)? {
1267            Some(pick) => Self::realize_inner(
1268                graph,
1269                target,
1270                inputs,
1271                OrderSource::Streaming {
1272                    optimized,
1273                    pick: &pick,
1274                },
1275                sym_env,
1276            )
1277            .map(|(s, l, _produced)| (s, l)),
1278            None => Self::realize_with_optimized_env(graph, target, inputs, optimized, sym_env),
1279        }
1280    }
1281
1282    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
1283    /// §5) — cached sibling of [`Self::realize_with_optimized_picking_env`]
1284    /// for the plan-once persistent-decode caller, which holds `order_cache`
1285    /// across repeated calls over the SAME graph/roots/`optimized` (one per
1286    /// `DecodeSession`, initially empty). On a branchless graph with no
1287    /// selector pressure (the decode shape this is for), dispatches via
1288    /// [`OrderSource::Cached`] — computed once, reused thereafter, see that
1289    /// variant's doc for the safety argument. A branched graph WITH a
1290    /// resolved selector pick falls back to the uncached
1291    /// [`OrderSource::Streaming`] path unchanged (caching doesn't apply
1292    /// there; this entry point exists for the decode case, not to cover
1293    /// every caller).
1294    pub fn realize_with_optimized_picking_cached_env(
1295        graph: Arc<RwLock<Graph>>,
1296        target: NodeId,
1297        inputs: StorageCache,
1298        optimized: &OptimizedGraph,
1299        order_cache: &std::sync::OnceLock<Vec<NodeId>>,
1300        selector: Option<Arc<dyn RuntimeSelector>>,
1301        lookup: Option<BackendRuntimeLookup>,
1302        sym_env: SymEnv,
1303    ) -> Result<(Arc<RwLock<Storage>>, Layout)> {
1304        match Self::streaming_pick_for(&graph, selector, lookup)? {
1305            Some(pick) => Self::realize_inner(
1306                graph,
1307                target,
1308                inputs,
1309                OrderSource::Streaming {
1310                    optimized,
1311                    pick: &pick,
1312                },
1313                sym_env,
1314            )
1315            .map(|(s, l, _produced)| (s, l)),
1316            None => Self::realize_inner(
1317                graph,
1318                target,
1319                inputs,
1320                OrderSource::Cached {
1321                    optimized,
1322                    order_cache,
1323                },
1324                sym_env,
1325            )
1326            .map(|(s, l, _produced)| (s, l)),
1327        }
1328    }
1329
1330    /// Build the [`StreamingPick`] for the executor's picking entry points —
1331    /// the streaming successor of the one-shot `pick_route_for` (which was the
1332    /// relocated body of the bridge's old `resolve_runtime_route`). Returns
1333    /// `None` (⇒ arm-0 lowering, the untouched `route: None` /
1334    /// `dispatch_order` path) when there is no `selector` (the disabled
1335    /// opt-out) or the graph has no `Op::Branch` (the branchless fast-path:
1336    /// skip the streaming machinery entirely so the common case is unchanged
1337    /// and byte-identical). Otherwise it carries the selector + lookup into
1338    /// the [`OrderSource::Streaming`] walk, which resolves each branch at the
1339    /// frontier (PR C1). The per-arm candidates are re-enumerated from the
1340    /// runtime binding registry inside the compiler thread (Step D — was the
1341    /// threaded `ExecutionPlan`).
1342    fn streaming_pick_for(
1343        graph: &Arc<RwLock<Graph>>,
1344        selector: Option<Arc<dyn RuntimeSelector>>,
1345        // Accepted for call-site parity with `pick_route` but not stored: the
1346        // streaming walk reads VRAM + load through the selector, which holds its
1347        // own `BackendRuntimeLookup`.
1348        _lookup: Option<BackendRuntimeLookup>,
1349    ) -> Result<Option<StreamingPick>> {
1350        let Some(selector) = selector else {
1351            return Ok(None);
1352        };
1353        let g = graph
1354            .read()
1355            .map_err(|_| Error::Msg("graph lock poisoned".into()).bt())?;
1356        let has_branch = (0..g.len()).any(|i| matches!(g.node(NodeId(i)).op, Op::Branch { .. }));
1357        if !has_branch {
1358            return Ok(None);
1359        }
1360        Ok(Some(StreamingPick { selector }))
1361    }
1362
1363    /// Capture a single-device CUDA decode step's kernel launches into a
1364    /// replayable [`CapturedRun`] (the CapturedRun executor build-out).
1365    ///
1366    /// Runs the graph TWICE against fixed-address buffers:
1367    ///   1. **Warm (record)**: realize normally into a fresh cache cloned
1368    ///      from `inputs`, recording every compute node's output Arc as its
1369    ///      fixed capture buffer, and synchronizing so the result is stable.
1370    ///   2. **Capture (reuse)**: re-issue the same launch sequence — each
1371    ///      node writing INTO its recorded buffer via the write-into kernel
1372    ///      path (no allocation) — inside [`CudaDevice::capture_run`],
1373    ///      producing an instantiated [`CapturedRun`].
1374    ///
1375    /// Both passes share the SAME input Arcs (cloned map, shared buffers)
1376    /// and the SAME recorded output buffers, so every device address the
1377    /// captured graph bakes in is stable for replay. To replay a later
1378    /// token: overwrite the fixed input buffers in place (H2D), call
1379    /// `run.replay(dev)`, then read `output`.
1380    ///
1381    /// Contract (surfaced as `Err`, never a panic or a mid-capture alloc):
1382    ///   - CUDA-only, single device: every compute node targets `Cuda`;
1383    ///     no cross-device `Op::Copy`/`Move` in the graph.
1384    ///   - Every compute node's op must have a write-into CUDA wrapper
1385    ///     (`op_kind_is_capture_writeinto`); an unsupported op surfaces a
1386    ///     clear capability gap rather than silently breaking the capture.
1387    ///   - Inputs must be contiguous (no auto-Contiguize alloc in capture).
1388    #[cfg(feature = "cuda")]
1389    pub fn capture_decode(
1390        graph: Arc<RwLock<Graph>>,
1391        target: NodeId,
1392        inputs: StorageCache,
1393        sym_env: SymEnv,
1394    ) -> Result<CapturedDecode> {
1395        use fuel_memory::BackendStorage;
1396
1397        // Front matter mirrors realize_inner: safety copies + frozen order.
1398        {
1399            let mut g = graph.write().map_err(|_| poisoned("graph lock"))?;
1400            let effective_roots = extend_with_side_effect_roots(&g, &[target]);
1401            insert_safety_copies(&mut g, &effective_roots);
1402        }
1403        let (compiler_work, _wait_set, seed_layouts) = {
1404            let g = graph.read().map_err(|_| poisoned("graph lock"))?;
1405            let effective_roots = extend_with_side_effect_roots(&g, &[target]);
1406            let (work, wait_set) =
1407                compiler_work_and_wait_set_for(&g, &effective_roots, &OrderSource::Default);
1408            let mut layouts: HashMap<NodeId, Layout> = HashMap::with_capacity(inputs.len());
1409            for &id in inputs.keys() {
1410                layouts.insert(id, g.layout(id));
1411            }
1412            (work, wait_set, layouts)
1413        };
1414
1415        // Compile every WorkItem once (one compiler thread) and collect them
1416        // so both passes replay the identical sequence.
1417        let (tx, rx) = channel::<Result<WorkItem>>();
1418        let graph_for_compiler = Arc::clone(&graph);
1419        let compiler = thread::spawn(move || {
1420            compiler_thread_body(graph_for_compiler, compiler_work, sym_env, tx);
1421        });
1422        let mut items: Vec<WorkItem> = Vec::new();
1423        for item in rx {
1424            items.push(item?);
1425        }
1426        compiler
1427            .join()
1428            .map_err(|_| Error::Msg("compiler thread panicked".to_string()).bt())?;
1429
1430        // CapturedRun 4b Step-4 diagnostic: name every kernel placed OFF Cuda
1431        // (an unseeded / audited-loser op that forces a cross-device copy and
1432        // blocks capture), so verification-ledger seeding can target it
1433        // precisely. Fires only when a capture is attempted AND something is
1434        // mis-placed — otherwise silent.
1435        {
1436            let off: Vec<String> = items
1437                .iter()
1438                .filter_map(|it| match &it.kind {
1439                    WorkItemKind::Kernel if it.target_backend != BackendId::Cuda => {
1440                        let desc = it
1441                            .compiled
1442                            .as_ref()
1443                            .map(|c| format!("{:?} dtypes={:?}", c.op, c.dtypes))
1444                            .unwrap_or_else(|| "?".to_string());
1445                        Some(format!(
1446                            "node {:?}: {desc} on {:?}",
1447                            it.node_id, it.target_backend
1448                        ))
1449                    }
1450                    _ => None,
1451                })
1452                .collect();
1453            if !off.is_empty() {
1454                eprintln!(
1455                    "[capture-diag] {} kernel(s) placed OFF Cuda (these block capture): {}",
1456                    off.len(),
1457                    off.join("; "),
1458                );
1459            }
1460        }
1461
1462        // Capture-safety validation — surface every gap up front, before any
1463        // launch, so a capture scope is never entered on an unsupported graph.
1464        for item in &items {
1465            match &item.kind {
1466                // Op::Move: the destructive half (releasing the source) is
1467                // driven by the realize loop's `destructive_input` cleanup,
1468                // which runs once per REALIZE call — not once per `replay()`.
1469                // A captured graph's `replay()` re-executes the same baked
1470                // launches repeatedly without re-running that surrounding
1471                // cleanup between replays, so whether a repeat-replayed Move
1472                // is even meaningful is unclear; out of scope here (4b-ζ) —
1473                // keep rejecting every Move unconditionally.
1474                WorkItemKind::Move { .. } => {
1475                    return Err(Error::Msg(format!(
1476                        "capture_decode: graph has an Op::Move at node {:?}; \
1477                         Move's destructive source-release half is driven by \
1478                         per-realize cleanup, not per-replay, so capture is \
1479                         not supported for Move (out of scope — see the \
1480                         `capture_decode` validation loop's Move arm).",
1481                        item.node_id,
1482                    ))
1483                    .bt());
1484                }
1485                // Op::Copy: a same-device CUDA→CUDA copy (e.g. an
1486                // `insert_safety_copies` snapshot) has a write-into wrapper
1487                // (`copy_from_cuda_wrapper`'s `BackendStorage::Cuda` branch,
1488                // via `CudaStorageBytes::copy_from_device`) and is
1489                // capture-safe. A copy whose `target_location` is `Cpu` or
1490                // `Vulkan` is a genuine host round-trip / cross-backend
1491                // transfer and can never be part of a CUDA graph capture —
1492                // keep rejecting those. (`gpu_id` is not cross-checked
1493                // against the capture device, matching the `Kernel` arm's
1494                // `target_backend` check just above: today's decode graphs
1495                // are single-GPU only.)
1496                WorkItemKind::Copy { target_location } => {
1497                    if !matches!(target_location, DeviceLocation::Cuda { .. }) {
1498                        return Err(Error::Msg(format!(
1499                            "capture_decode: graph has a cross-device Op::Copy at \
1500                             node {:?} (target {:?}); capture requires a \
1501                             single-device CUDA decode step — only same-device \
1502                             CUDA→CUDA copies are capture-safe.",
1503                            item.node_id, target_location,
1504                        ))
1505                        .bt());
1506                    }
1507                }
1508                WorkItemKind::Kernel => {
1509                    if item.target_backend != BackendId::Cuda {
1510                        return Err(Error::Msg(format!(
1511                            "capture_decode: kernel node {:?} targets {:?}, not Cuda",
1512                            item.node_id, item.target_backend,
1513                        ))
1514                        .bt());
1515                    }
1516                    let compiled = item.compiled.as_ref().ok_or_else(|| {
1517                        Error::Msg(format!(
1518                            "capture_decode: kernel node {:?} has no compiled op",
1519                            item.node_id,
1520                        ))
1521                        .bt()
1522                    })?;
1523                    let op = compiled.op;
1524                    if !op_kind_is_capture_writeinto(op) {
1525                        return Err(Error::Msg(format!(
1526                            "capture_decode: op {:?} (node {:?}) has no write-into CUDA \
1527                             wrapper yet — capture unsupported for this op. Extend \
1528                             op_kind_is_capture_writeinto once its write-into variant lands.",
1529                            op, item.node_id,
1530                        ))
1531                        .bt());
1532                    }
1533                    // Concat's capture-safety is conditional on arity — N==2
1534                    // has a write-into path (concat2_into), N>2 does not (its
1535                    // wrapper falls back to an allocating N-1 chain). This
1536                    // can't be expressed by op_kind_is_capture_writeinto (a
1537                    // pure OpKind -> bool predicate with no OpParams access),
1538                    // so reject N>2 explicitly here, BEFORE the warm pass —
1539                    // see op_kind_is_capture_writeinto's doc comment.
1540                    if op == OpKind::Concat {
1541                        if let OpParams::Concat {
1542                            input_dim_sizes, ..
1543                        } = &compiled.op_params
1544                        {
1545                            if input_dim_sizes.len() != 2 {
1546                                return Err(Error::Msg(format!(
1547                                    "capture_decode: Concat node {:?} has {} inputs; only \
1548                                     2-input concat (the rope rotate-half shape) has a \
1549                                     write-into CUDA path today — N-ary (N>2) concat would \
1550                                     allocate mid-capture.",
1551                                    item.node_id,
1552                                    input_dim_sizes.len(),
1553                                ))
1554                                .bt());
1555                            }
1556                        }
1557                    }
1558                }
1559                // View / adopt / slot kinds: no alloc, no launch — capture-safe.
1560                _ => {}
1561            }
1562        }
1563
1564        // ---- Pass 1: warm (record) — fixed buffers + a synchronized result --
1565        let mut persistent = PersistentOutputs::recording();
1566        let mut warm_cache: StorageCache = inputs.clone();
1567        let mut warm_layouts = seed_layouts.clone();
1568        let mut warm_syms = SymEnv::new();
1569        let mut warm_devices = cuda_registry_of_inputs(&warm_cache);
1570        for item in &items {
1571            let _handle = execute_work_item(
1572                item,
1573                &mut warm_cache,
1574                &mut warm_devices,
1575                &mut warm_layouts,
1576                &mut warm_syms,
1577                false,
1578                Some(&mut persistent),
1579            )
1580            .map_err(|e| with_node_location(&graph, item.node_id, e))?;
1581        }
1582        // Flush all warm launches before capture (device idle; result stable).
1583        sync_active_cuda_devices(&warm_cache)?;
1584
1585        let output = warm_cache.get(&target).cloned().ok_or_else(|| {
1586            Error::Msg(format!(
1587                "capture_decode: target {:?} not realized in warm run",
1588                target,
1589            ))
1590            .bt()
1591        })?;
1592        let output_layout = warm_layouts.get(&target).cloned().ok_or_else(|| {
1593            Error::Msg(format!("capture_decode: target {:?} has no layout", target)).bt()
1594        })?;
1595
1596        // Derive the CUDA device from the target's storage for capture_run.
1597        let device = {
1598            let guard = output.read().map_err(|_| poisoned("output storage"))?;
1599            match &guard.inner {
1600                BackendStorage::Cuda(c) => c.device().clone(),
1601                other => {
1602                    return Err(Error::Msg(format!(
1603                        "capture_decode: target {:?} is BackendStorage::{:?}, not Cuda",
1604                        target,
1605                        other.backend_id(),
1606                    ))
1607                    .bt());
1608                }
1609            }
1610        };
1611
1612        // ---- Pass 2: capture (reuse) — record the launch sequence ----------
1613        let mut reuse = PersistentOutputs::reuse(persistent.into_map());
1614        // Retain EVERY input buffer before `inputs` is consumed: the captured
1615        // graph bakes their device addresses, so they must outlive it even if
1616        // the caller doesn't independently hold them.
1617        let retained_inputs: Vec<Arc<RwLock<Storage>>> = inputs.values().cloned().collect();
1618        let mut cap_cache: StorageCache = inputs;
1619        let mut cap_layouts = seed_layouts;
1620        let mut cap_syms = SymEnv::new();
1621        let mut cap_devices = cuda_registry_of_inputs(&cap_cache);
1622        let mut inner_err: Option<Error> = None;
1623        let items_ref = &items;
1624        let graph_ref = &graph;
1625        let run = device.capture_run(|_stream| {
1626            // Inside the capture scope: NO device alloc, NO host sync. Each
1627            // kernel launches on device.stream() (now capturing) and writes
1628            // into its reused fixed buffer.
1629            for item in items_ref {
1630                match execute_work_item(
1631                    item,
1632                    &mut cap_cache,
1633                    &mut cap_devices,
1634                    &mut cap_layouts,
1635                    &mut cap_syms,
1636                    false,
1637                    Some(&mut reuse),
1638                ) {
1639                    Ok(_handle) => {}
1640                    Err(e) => {
1641                        inner_err = Some(with_node_location(graph_ref, item.node_id, e));
1642                        break;
1643                    }
1644                }
1645            }
1646            Ok(())
1647        })?;
1648        if let Some(e) = inner_err {
1649            return Err(e);
1650        }
1651
1652        Ok(CapturedDecode {
1653            run,
1654            output,
1655            output_layout,
1656            retained_inputs,
1657            persistent: reuse.into_map(),
1658        })
1659    }
1660
1661    fn realize_inner(
1662        graph: Arc<RwLock<Graph>>,
1663        target: NodeId,
1664        inputs: StorageCache,
1665        order_source: OrderSource<'_>,
1666        sym_env: SymEnv,
1667    ) -> Result<(Arc<RwLock<Storage>>, Layout, SymEnv)> {
1668        Self::realize_inner_with(
1669            graph,
1670            target,
1671            inputs,
1672            order_source,
1673            sym_env,
1674            DeviceRegistry::new(),
1675        )
1676    }
1677
1678    /// [`Self::realize_inner`] with the device handles the caller already holds.
1679    fn realize_inner_with(
1680        graph: Arc<RwLock<Graph>>,
1681        target: NodeId,
1682        inputs: StorageCache,
1683        order_source: OrderSource<'_>,
1684        sym_env: SymEnv,
1685        device_handles: DeviceRegistry,
1686    ) -> Result<(Arc<RwLock<Storage>>, Layout, SymEnv)> {
1687        // Auto-insert safety copies for in-place ops whose target
1688        // has additional readers in this realize set (residual-
1689        // connection cycle break). No-op when no destructive ops
1690        // are present.
1691        {
1692            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.safety_copies");
1693            let mut g = graph.write().map_err(|_| poisoned("graph lock"))?;
1694            let effective_roots = extend_with_side_effect_roots(&g, &[target]);
1695            insert_safety_copies(&mut g, &effective_roots);
1696        }
1697
1698        // Execution plan + initial layouts for the input cache
1699        // entries, computed on the calling thread to keep the
1700        // compiler thread free of graph-locking responsibilities.
1701        // Side-effect roots (Op::Print, Op::Save, etc.) are merged
1702        // into the walk so their effects fire even when not
1703        // reachable from the user's `target`. `execution_plan`
1704        // integrates `derive_ordering`'s view-aware pinning so
1705        // destructive ops run AFTER non-destructive readers of
1706        // their targets.
1707        let (compiler_work, wait_set, mut layout_cache): (
1708            CompilerWork,
1709            WaitSet,
1710            HashMap<NodeId, Layout>,
1711        ) = {
1712            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.plan_order");
1713            let g = graph.read().map_err(|_| poisoned("graph lock"))?;
1714            let effective_roots = extend_with_side_effect_roots(&g, &[target]);
1715            // PR-A3b-1: the OptimizedGraph path lowers via
1716            // `extract_runs`/`lower_run` (computed here, AFTER
1717            // `insert_safety_copies`, so the order covers freshly
1718            // inserted safety-copy nodes). The default path keeps the
1719            // pre-A3b-1 `execution_plan` walk. On a branchless graph the
1720            // two sequences are identical (A3a equivalence gate).
1721            //
1722            // PR-C1: a `Streaming` source is NOT flattened here — it is
1723            // handed to the compiler thread as a `CompilerWork::Streaming`
1724            // spec so the thread resolves each branch lazily at the
1725            // frontier (see `compiler_thread_body`).
1726            //
1727            // Step E A4b open question #4: the SAME pass also derives the
1728            // `WaitSet` from the materialized order ("event only where
1729            // waited" — see `compiler_work_and_wait_set_for`).
1730            let (work, wait_set) =
1731                compiler_work_and_wait_set_for(&g, &effective_roots, &order_source);
1732            let mut layouts = HashMap::with_capacity(inputs.len());
1733            for &id in inputs.keys() {
1734                layouts.insert(id, g.layout(id));
1735            }
1736            (work, wait_set, layouts)
1737        };
1738
1739        let (tx, rx) = channel::<Result<WorkItem>>();
1740        let graph_for_compiler = Arc::clone(&graph);
1741
1742        // Compiler thread: read graph nodes, resolve kernels,
1743        // push WorkItems. On error, push the error and bail. PR-C1: for a
1744        // `Streaming` work spec the thread also resolves each branch's arm
1745        // at the frontier (the SAME VRAM-only selector the one-shot picker
1746        // uses) before compiling that arm's runs.
1747        let compiler = {
1748            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.spawn_compiler");
1749            thread::spawn(move || {
1750                let _t = crate::compiled::op_profile::PhaseTimer::start(
1751                    "compiler_thread (runs concurrently)",
1752                );
1753                compiler_thread_body(graph_for_compiler, compiler_work, sym_env, tx);
1754            })
1755        };
1756
1757        // Executor on this thread: consume WorkItems, gather
1758        // inputs from the cache, allocate outputs, call kernels,
1759        // populate the cache. After each destructive op
1760        // (Op::Release / Op::Move) evict the destroyed input from
1761        // the cache, unless it's the realize target.
1762        //
1763        // Phase 4.3: at each dispatch-chunk boundary (target_backend
1764        // change), check the live SystemTopology generation against
1765        // the plan's stamped generation. Mismatch surfaces
1766        // `Error::TopologyChanged`; the realize layer
1767        // (`pipelined_bridge`) catches it, rebuilds the plan against
1768        // the fresh topology, and retries.
1769        let plan_generation: Option<u64> = generation_for(&order_source);
1770        let mut current_chunk_backend: Option<BackendId> = None;
1771        let mut cache: StorageCache = inputs;
1772        let mut devices = device_handles;
1773        // Data-dependent dynamic-shapes: symbols BOUND BY PRODUCERS during
1774        // this pass (e.g. `Op::NonZeroIndices`'s runtime count). Distinct
1775        // from the compile-time `sym_env` (input-determined, moved into the
1776        // compiler thread): these become known only as ops execute. Returned
1777        // to the caller so a downstream pass can consume them.
1778        let mut produced_syms = SymEnv::new();
1779        // Step E A4b-1: per-node async-completion handles. Each producing node's
1780        // `execute_compiled` returns a `CompletionHandle` (CUDA → a recorded
1781        // `Event`; CPU/Vulkan → `Ready`) instead of being `wait`ed inline. We
1782        // store them here, wait the SOURCE producer's handle before a
1783        // cross-device copy (A4b-3, below), and drain whatever remains at
1784        // realize-end.
1785        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
1786        // Step E A4b-4: eagerly-submitted-but-not-yet-waited Vulkan batches. The
1787        // OVERLAP enabler — when we LEAVE a Vulkan chunk (or are about to block on
1788        // a CUDA copy) we `submit_pending` the open Vulkan batch so the iGPU runs
1789        // it while the executor records/dispatches the next (CUDA) chunk, instead
1790        // of letting it sit merely-recorded until realize-end (the A4b-2 behavior,
1791        // which never overlapped). Each submitted batch is tracked here and waited
1792        // at the in-flight-lifetime guard (before a Vulkan read / Vulkan-referenced
1793        // eviction / realize-end). `multi_backend` gates ALL eager submits so a
1794        // single-device realize never touches this path (byte-identical to A4b-2).
1795        let mut inflight_vulkan: Vec<InflightVulkan> = Vec::new();
1796        // ROADMAP row 158: the backlog this realize adds to the device queues; its `Drop` takes it back out on
1797        // the Ok path and when an error unwinds the walk.
1798        let mut backlog = crate::dispatch::BacklogLedger::new();
1799        // Step E A4b-4: set true the first time the dispatch order transitions
1800        // between two DIFFERENT non-CPU... actually any two distinct backends — a
1801        // genuine backend switch. On a pure-CUDA or pure-Vulkan graph there is no
1802        // switch, so this stays false and the eager-submit / in-flight machinery is
1803        // unreachable (single-device byte-identical + throughput-neutral, §5).
1804        let mut multi_backend = false;
1805        let loop_total = crate::compiled::op_profile::PhaseTimer::start("realize.loop_total");
1806        loop {
1807            let t_wait =
1808                crate::compiled::op_profile::PhaseTimer::start("realize.wait_for_compiler");
1809            let Ok(item) = rx.recv() else {
1810                break;
1811            };
1812            drop(t_wait);
1813            let item = item?;
1814            // Chunk-boundary hook (target_backend change). Existing duty: the
1815            // `TopologyChanged` generation check. Step E A4b-4 adds two duties:
1816            // (1) detect a genuine backend switch → arm `multi_backend`; (2) when
1817            // LEAVING a Vulkan chunk on a multi-backend graph, eager-submit the
1818            // open Vulkan batch so the iGPU starts it concurrently with the chunk
1819            // we are about to dispatch (the overlap win).
1820            if !is_backend_neutral(&item.kind) && current_chunk_backend != Some(item.target_backend)
1821            {
1822                if let Some(plan_gen) = plan_generation {
1823                    let live = crate::dispatch::topology_generation();
1824                    if live != plan_gen {
1825                        return Err(Error::TopologyChanged {
1826                            plan_generation: plan_gen,
1827                            current_generation: live,
1828                        }
1829                        .bt());
1830                    }
1831                }
1832                let leaving = current_chunk_backend;
1833                if let Some(prev) = leaving
1834                    && prev != item.target_backend
1835                {
1836                    // A real backend switch occurred — this realize is
1837                    // genuinely multi-backend.
1838                    multi_backend = true;
1839                    // Leaving a Vulkan chunk → submit it NOW so it runs on the
1840                    // iGPU while we record/dispatch the next chunk. Whole-chunk
1841                    // granularity (the open batch IS the just-finished Vulkan
1842                    // chunk with all its intra-CB barriers) — UAF/race-safe per
1843                    // `eager_submit_all_vulkan`'s contract.
1844                    if prev == BackendId::Vulkan {
1845                        {
1846                            let _pt = crate::compiled::op_profile::PhaseTimer::start(
1847                                "realize.eager_submit_vulkan",
1848                            );
1849                            eager_submit_all_vulkan(&cache, &mut inflight_vulkan)?;
1850                        }
1851                    }
1852                }
1853                current_chunk_backend = Some(item.target_backend);
1854            }
1855            // Vulkan realizes run the async path (deferred eviction, size-based eager
1856            // submit) even on a single device: ordering between batches is structural
1857            // (inter-batch barrier + epoch-gated buffer reuse), not a host wait.
1858            if item.target_backend == BackendId::Vulkan && matches!(item.kind, WorkItemKind::Kernel)
1859            {
1860                multi_backend = true;
1861            }
1862            // Same-device cross-chunk RAW/WAR safety between Vulkan batches (the old
1863            // "Invariant E": wait every in-flight Vulkan batch on the HOST before
1864            // recording a new Vulkan op) is now structural: the Vulkan recorder
1865            // starts every batch with a memory barrier whose first scope covers all
1866            // earlier submissions on the queue (`Recorder::record_inter_batch_barrier`),
1867            // so a later batch cannot read or overwrite what an earlier in-flight
1868            // one is still using. The host therefore keeps recording while the
1869            // GPU runs the batches already submitted; waits remain only where the
1870            // host needs a result (D2H reads), before freeing a buffer, and at
1871            // realize-end.
1872            // Step E A4b-3 + A4b-4: the cross-device residency boundary.
1873            if matches!(
1874                item.kind,
1875                WorkItemKind::Copy { .. } | WorkItemKind::Move { .. }
1876            ) {
1877                // A4b-4: before we (possibly) block the host on the CUDA producer,
1878                // eager-submit any open Vulkan chunk so the iGPU runs it WHILE we
1879                // wait on CUDA (the §5.1 ordering — submit Vulkan *before* draining
1880                // CUDA). Cheap + safe; gated to multi-backend (no-op single-device).
1881                if multi_backend {
1882                    {
1883                        let _pt = crate::compiled::op_profile::PhaseTimer::start(
1884                            "realize.eager_submit_vulkan",
1885                        );
1886                        eager_submit_all_vulkan(&cache, &mut inflight_vulkan)?;
1887                    }
1888                }
1889                if let Some(&producer) = item.inputs.first() {
1890                    // A4b-4: a VULKAN-source D2H must read COMPLETED data, and the
1891                    // Vulkan download path only flushes the OPEN batch (not our
1892                    // in-flight ones) — so wait the in-flight Vulkan batches here.
1893                    // For a CUDA/CPU source we do NOT wait Vulkan (the copy reads no
1894                    // Vulkan buffer); waiting it would needlessly serialize the
1895                    // independent Vulkan sub-DAG and kill the overlap. The Vulkan
1896                    // work that was eager-submitted at the chunk boundary keeps
1897                    // running concurrently until ITS result is the one being copied.
1898                    if multi_backend && copy_source_is_vulkan(&cache, producer)? {
1899                        {
1900                            let _pt = crate::compiled::op_profile::PhaseTimer::start(
1901                                "realize.drain_inflight_vulkan",
1902                            );
1903                            drain_inflight_vulkan(&mut inflight_vulkan)?;
1904                        }
1905                    }
1906                    // Step E A4b-3: FINER CUDA source-drain — wait ONLY the source
1907                    // producer's recorded event (not the whole source device), so
1908                    // the OTHER sub-DAG's independent in-flight CUDA work keeps
1909                    // running. No-op for a Vulkan/CPU producer (no CUDA handle).
1910                    wait_producer_handle(&mut handles, producer)?;
1911                }
1912            }
1913            let t_exec =
1914                crate::compiled::op_profile::PhaseTimer::start(work_item_kind_name(&item.kind));
1915            let handle = execute_work_item(
1916                &item,
1917                &mut cache,
1918                &mut devices,
1919                &mut layout_cache,
1920                &mut produced_syms,
1921                will_be_waited(&wait_set, item.node_id),
1922                // No persistent-output mode on the standard realize paths —
1923                // fresh alloc per node, byte-identical to pre-CapturedRun.
1924                None,
1925            )
1926            .map_err(|e| with_node_location(&graph, item.node_id, e))?;
1927            drop(t_exec);
1928            store_handle(&mut handles, item.node_id, handle);
1929            feed_backlog(&mut backlog, &cache, &item);
1930            if let Some(d_idx) = item.destructive_input
1931                && let Some(&destroyed) = item.inputs.get(d_idx)
1932                && destroyed != target
1933            {
1934                // Step E A2.1 (in-flight-batch DATA-BUFFER lifetime — the
1935                // UAF guard, now DEFERRED-DELETION instead of a drain). A
1936                // `SubmittedBatch` owns its CB/descriptors/transients but
1937                // NOT the DATA buffers it reads (those live here in the
1938                // cache); recycling a data buffer an in-flight/open CB still
1939                // reads is a use-after-free. PRE-A2.1 we host-blocked here —
1940                // `drain_inflight_vulkan` (wait every in-flight batch) +
1941                // `force_flush` (submit+wait the open batch) — which stalled
1942                // the iGPU work we were overlapping with CUDA at EVERY such
1943                // eviction. A2.1 instead RETAINS the evicted buffer until the
1944                // reader fences signal: it eager-submits the open batch (no
1945                // wait → it becomes a fenced in-flight batch) and moves a
1946                // refcount clone of the buffer into every in-flight batch, so
1947                // the buffer frees POST-fence on each batch's `Drop`
1948                // (follow-on #2) with NO host block. Conservative over all
1949                // batches (no cheap buffer→batch map — the same reason the old
1950                // drain waited all of them). CUDA eviction is stream-ordered-
1951                // safe via A3. Single-device (multi_backend == false) keeps the
1952                // pre-A2.1 blocking force_flush of the OPEN batch (the else
1953                // branch) — byte-identical + UAF-safe there; the deferred path is
1954                // unsafe single-device (no eager-submit/in-flight tracking, and the
1955                // cross-batch RAW guard at :832 doesn't run — see
1956                // force_flush_vulkan's doc).
1957                let _t =
1958                    crate::compiled::op_profile::PhaseTimer::start("realize.evict_destroyed_input");
1959                if multi_backend {
1960                    defer_evicted_vulkan_buffer(&cache, destroyed, &mut inflight_vulkan)?;
1961                } else if let Some(d_arc) = cache.get(&destroyed) {
1962                    let _f = crate::compiled::op_profile::PhaseTimer::start(
1963                        "realize.evict_force_flush_vulkan",
1964                    );
1965                    force_flush_vulkan(d_arc)?;
1966                }
1967                cache.remove(&destroyed);
1968                layout_cache.remove(&destroyed);
1969                // Drop the evicted node's CUDA handle (if still present)
1970                // so the realize-end drain's empty-map assert stays
1971                // meaningful. The free itself is stream-ordered-safe (A3).
1972                handles.remove(&destroyed);
1973            }
1974        }
1975
1976        drop(loop_total);
1977        {
1978            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.join_compiler");
1979            compiler
1980                .join()
1981                .map_err(|_| Error::Msg("compiler thread panicked".to_string()).bt())?;
1982        }
1983
1984        // Step E A4b-1: drain every outstanding async handle before the result is
1985        // read / the cache drops (freeing intermediates). For CUDA this waits the
1986        // recorded events (one stream/device ⇒ waiting the latest drains all prior
1987        // stream work too; see `drain_handles`).
1988        let post_loop = crate::compiled::op_profile::PhaseTimer::start("realize.post_loop_drains");
1989        drain_handles(&mut handles)?;
1990        // Step E A4b open question #4 — "event only where waited": most CUDA
1991        // nodes in this realize never got an Event (elided per the `WaitSet`),
1992        // so `drain_handles` above only retired the (typically few) tracked
1993        // handles. This blanket per-device `cuStreamSynchronize` flushes the
1994        // elided work too — safe + sufficient because of single-stream-per-
1995        // device ordering (see `sync_active_cuda_devices`'s doc).
1996        sync_active_cuda_devices(&cache)?;
1997        // Step E A4b-4: wait every eagerly-submitted (in-flight) Vulkan batch
1998        // before the cache drops, freeing the data buffers their CBs read. Empty
1999        // on a single-device realize (nothing was eager-submitted).
2000        {
2001            let _pt =
2002                crate::compiled::op_profile::PhaseTimer::start("realize.drain_inflight_vulkan");
2003            drain_inflight_vulkan(&mut inflight_vulkan)?;
2004        }
2005        // Step E A4b-2: drain all deferred Vulkan work before reading/returning
2006        // the result (and before the cache drops, freeing buffers). The A2
2007        // submit+wait is now SPLIT — `drain_vulkan_pending` submits the open
2008        // batch then waits it via a `VulkanCompletion` handle. Byte-identical to
2009        // A2 for pure-Vulkan (one submission at realize-end, just split).
2010        drain_vulkan_pending(&cache)?;
2011        debug_assert!(
2012            inflight_vulkan.is_empty(),
2013            "A4b-4: in-flight Vulkan batch list must be empty after realize-end drain",
2014        );
2015
2016        drop(post_loop);
2017        let storage = cache.remove(&target).ok_or_else(|| {
2018            Error::Msg(format!(
2019                "PipelinedExecutor::realize: target slot {:?} not populated after execution",
2020                target
2021            ))
2022            .bt()
2023        })?;
2024        let layout = layout_cache.remove(&target).ok_or_else(|| {
2025            Error::Msg(format!(
2026                "PipelinedExecutor::realize: target layout {:?} not populated after execution",
2027                target
2028            ))
2029            .bt()
2030        })?;
2031        {
2032            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.drop_cache");
2033            drop(cache);
2034            drop(handles);
2035            drop(layout_cache);
2036        }
2037        Ok((storage, layout, produced_syms))
2038    }
2039
2040    /// Realize multiple targets in one walk. Each target's transitive
2041    /// dependency set is collapsed into a single execution plan
2042    /// (via [`execution_plan`]); shared subgraphs are evaluated
2043    /// once. Returns a `Vec<(Storage, Layout)>` whose order matches
2044    /// `targets`.
2045    ///
2046    /// This is Phase A of Phase 7.6 step 9c — feature-parity with the
2047    /// legacy `GraphExecutor::realize_many_f32`. Multi-session
2048    /// migration target ([memory: project_phase_7_6_step_9c_parity_audit.md]).
2049    ///
2050    /// Pre-conditions: every reachable `Op::Const` must be in
2051    /// `inputs`; every reachable non-`Const` must have its
2052    /// `target_backend` set; the op + dtype must be registered in
2053    /// `global_bindings()`. Same as single-target [`Self::realize`].
2054    pub fn realize_many(
2055        graph: Arc<RwLock<Graph>>,
2056        targets: &[NodeId],
2057        inputs: StorageCache,
2058    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2059        Self::realize_many_inner(
2060            graph,
2061            targets,
2062            inputs,
2063            OrderSource::Default,
2064            SymEnv::default(),
2065        )
2066    }
2067
2068    /// [`Self::realize_many`] with the device handles the caller already holds (ROADMAP row 137, seam S3
2069    /// step 3b).
2070    pub fn realize_many_with_devices(
2071        graph: Arc<RwLock<Graph>>,
2072        targets: &[NodeId],
2073        inputs: StorageCache,
2074        devices: DeviceRegistry,
2075    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2076        Self::realize_many_inner_with(
2077            graph,
2078            targets,
2079            inputs,
2080            OrderSource::Default,
2081            SymEnv::default(),
2082            devices,
2083        )
2084    }
2085
2086    /// [`Self::realize_many_with_optimized_picking_env`] with the device handles the caller already holds.
2087    #[allow(clippy::too_many_arguments)]
2088    pub fn realize_many_with_optimized_picking_env_with_devices(
2089        graph: Arc<RwLock<Graph>>,
2090        targets: &[NodeId],
2091        inputs: StorageCache,
2092        optimized: &OptimizedGraph,
2093        selector: Option<Arc<dyn RuntimeSelector>>,
2094        lookup: Option<BackendRuntimeLookup>,
2095        sym_env: SymEnv,
2096        devices: DeviceRegistry,
2097    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2098        let order_source = match Self::streaming_pick_for(&graph, selector, lookup)? {
2099            Some(pick) => {
2100                return Self::realize_many_inner_with(
2101                    graph,
2102                    targets,
2103                    inputs,
2104                    OrderSource::Streaming {
2105                        optimized,
2106                        pick: &pick,
2107                    },
2108                    sym_env,
2109                    devices,
2110                );
2111            }
2112            None => OrderSource::Optimized {
2113                optimized,
2114                route: None,
2115            },
2116        };
2117        Self::realize_many_inner_with(graph, targets, inputs, order_source, sym_env, devices)
2118    }
2119
2120    /// Multi-target PR-A3b-1 entry — the `realize_many` sibling of
2121    /// [`Self::realize_with_optimized`]. Drives the executor from the
2122    /// `OptimizedGraph`'s run lowering via the binding-table-lookup
2123    /// path, with the optimize-time `generation` keying the
2124    /// `TopologyChanged` chunk-boundary check.
2125    pub fn realize_many_with_optimized(
2126        graph: Arc<RwLock<Graph>>,
2127        targets: &[NodeId],
2128        inputs: StorageCache,
2129        optimized: &OptimizedGraph,
2130    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2131        Self::realize_many_inner(
2132            graph,
2133            targets,
2134            inputs,
2135            OrderSource::Optimized {
2136                optimized,
2137                route: None,
2138            },
2139            SymEnv::default(),
2140        )
2141    }
2142
2143    /// Env-carrying sibling of [`Self::realize_many_with_optimized`] (Phase D
2144    /// symbolic extents). An empty env is byte-identical to it.
2145    pub fn realize_many_with_optimized_env(
2146        graph: Arc<RwLock<Graph>>,
2147        targets: &[NodeId],
2148        inputs: StorageCache,
2149        optimized: &OptimizedGraph,
2150        sym_env: SymEnv,
2151    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2152        Self::realize_many_inner(
2153            graph,
2154            targets,
2155            inputs,
2156            OrderSource::Optimized {
2157                optimized,
2158                route: None,
2159            },
2160            sym_env,
2161        )
2162    }
2163
2164    /// Multi-target PR-C1 entry — the `realize_many` sibling of
2165    /// [`Self::realize_with_optimized_route`]. Lowers each target's runs
2166    /// following the picker's chosen arms via
2167    /// [`fuel_graph::lower_picked_route`].
2168    pub fn realize_many_with_optimized_route(
2169        graph: Arc<RwLock<Graph>>,
2170        targets: &[NodeId],
2171        inputs: StorageCache,
2172        optimized: &OptimizedGraph,
2173        route: &PickedRoute,
2174    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2175        Self::realize_many_inner(
2176            graph,
2177            targets,
2178            inputs,
2179            OrderSource::Optimized {
2180                optimized,
2181                route: Some(route),
2182            },
2183            SymEnv::default(),
2184        )
2185    }
2186
2187    /// Env-carrying sibling of [`Self::realize_many_with_optimized_route`]
2188    /// (Phase D symbolic extents). An empty env is byte-identical to it.
2189    pub fn realize_many_with_optimized_route_env(
2190        graph: Arc<RwLock<Graph>>,
2191        targets: &[NodeId],
2192        inputs: StorageCache,
2193        optimized: &OptimizedGraph,
2194        route: &PickedRoute,
2195        sym_env: SymEnv,
2196    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2197        Self::realize_many_inner(
2198            graph,
2199            targets,
2200            inputs,
2201            OrderSource::Optimized {
2202                optimized,
2203                route: Some(route),
2204            },
2205            sym_env,
2206        )
2207    }
2208
2209    /// Multi-target sibling of [`Self::realize_with_optimized_picking_env`] —
2210    /// the executor resolves one arm per `Op::Branch` (cleanup Step C/D) over
2211    /// the effective targets. PR C1: a branched graph routes to the
2212    /// `OrderSource::Streaming` walk (lazy per-branch resolution at the
2213    /// frontier); branchless / no-selector falls to the untouched arm-0 path.
2214    pub fn realize_many_with_optimized_picking_env(
2215        graph: Arc<RwLock<Graph>>,
2216        targets: &[NodeId],
2217        inputs: StorageCache,
2218        optimized: &OptimizedGraph,
2219        selector: Option<Arc<dyn RuntimeSelector>>,
2220        lookup: Option<BackendRuntimeLookup>,
2221        sym_env: SymEnv,
2222    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2223        match Self::streaming_pick_for(&graph, selector, lookup)? {
2224            Some(pick) => Self::realize_many_inner(
2225                graph,
2226                targets,
2227                inputs,
2228                OrderSource::Streaming {
2229                    optimized,
2230                    pick: &pick,
2231                },
2232                sym_env,
2233            ),
2234            None => {
2235                Self::realize_many_with_optimized_env(graph, targets, inputs, optimized, sym_env)
2236            }
2237        }
2238    }
2239
2240    fn realize_many_inner(
2241        graph: Arc<RwLock<Graph>>,
2242        targets: &[NodeId],
2243        inputs: StorageCache,
2244        order_source: OrderSource<'_>,
2245        sym_env: SymEnv,
2246    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2247        Self::realize_many_inner_with(
2248            graph,
2249            targets,
2250            inputs,
2251            order_source,
2252            sym_env,
2253            DeviceRegistry::new(),
2254        )
2255    }
2256
2257    /// [`Self::realize_many_inner`] with the device handles the caller already holds.
2258    fn realize_many_inner_with(
2259        graph: Arc<RwLock<Graph>>,
2260        targets: &[NodeId],
2261        inputs: StorageCache,
2262        order_source: OrderSource<'_>,
2263        sym_env: SymEnv,
2264        device_handles: DeviceRegistry,
2265    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2266        if targets.is_empty() {
2267            return Ok(Vec::new());
2268        }
2269
2270        // Auto-insert safety copies for in-place ops whose target
2271        // has additional readers in this realize set (residual-
2272        // connection cycle break). No-op when no destructive ops
2273        // are present.
2274        {
2275            let mut g = graph.write().map_err(|_| poisoned("graph lock"))?;
2276            let effective_roots = extend_with_side_effect_roots(&g, targets);
2277            insert_safety_copies(&mut g, &effective_roots);
2278        }
2279
2280        // Execution plan covering every target's dependency set +
2281        // initial layouts for the input cache entries. Side-effect
2282        // roots merge in so their effects fire even when not
2283        // reachable from any target. `execution_plan` integrates
2284        // `derive_ordering`'s view-aware pinning so destructive ops
2285        // run AFTER non-destructive readers of their targets.
2286        let (compiler_work, wait_set, mut layout_cache): (
2287            CompilerWork,
2288            WaitSet,
2289            HashMap<NodeId, Layout>,
2290        ) = {
2291            let g = graph.read().map_err(|_| poisoned("graph lock"))?;
2292            let effective_roots = extend_with_side_effect_roots(&g, targets);
2293            // PR-A3b-1: derive from the OptimizedGraph's run lowering
2294            // when present (post-safety-copies); else the legacy
2295            // `execution_plan` walk. Identical on branchless graphs.
2296            //
2297            // PR-C1: a `Streaming` source is handed to the compiler thread
2298            // unflattened (resolves branches at the frontier).
2299            //
2300            // Step E A4b open question #4: also derives the `WaitSet`
2301            // ("event only where waited") from the same materialized order.
2302            let (work, wait_set) =
2303                compiler_work_and_wait_set_for(&g, &effective_roots, &order_source);
2304            let mut layouts = HashMap::with_capacity(inputs.len());
2305            for &id in inputs.keys() {
2306                layouts.insert(id, g.layout(id));
2307            }
2308            (work, wait_set, layouts)
2309        };
2310
2311        // Caller's target set — used to gate destructive-input
2312        // eviction so we don't drop a tensor the caller asked for.
2313        let target_set: std::collections::HashSet<NodeId> = targets.iter().copied().collect();
2314
2315        let (tx, rx) = channel::<Result<WorkItem>>();
2316        let graph_for_compiler = Arc::clone(&graph);
2317
2318        let compiler = thread::spawn(move || {
2319            compiler_thread_body(graph_for_compiler, compiler_work, sym_env, tx);
2320        });
2321
2322        // Phase 4.3: per-chunk SystemTopology generation check (see
2323        // realize_inner for the rationale). PR-A3b-1: the OptimizedGraph
2324        // path supplies its own optimize-time generation.
2325        let plan_generation: Option<u64> = generation_for(&order_source);
2326        let mut current_chunk_backend: Option<BackendId> = None;
2327        let mut cache: StorageCache = inputs;
2328        let mut devices = device_handles;
2329        // Data-dependent dynamic-shapes producer-bound symbols (see
2330        // `realize_inner`). `realize_many` does not expose them today; the
2331        // env is dropped at pass end (producers still publish, keeping the
2332        // seam uniform across both realize loops).
2333        let mut produced_syms = SymEnv::new();
2334        // Step E A4b-1/A4b-3: per-node async-completion handles (see realize_inner
2335        // for the full rationale). Map drained at realize-end; the cross-device
2336        // copy waits the SOURCE producer's handle (A4b-3).
2337        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
2338        // Step E A4b-4: eagerly-submitted in-flight Vulkan batches + the
2339        // multi-backend gate. See realize_inner for the full rationale — this is
2340        // the identical eager-submit / in-flight-lifetime machinery applied to the
2341        // multi-target walk. `multi_backend` arms on a genuine backend switch and
2342        // gates every eager submit, so a single-device realize_many is
2343        // byte-identical to A4b-2.
2344        let mut inflight_vulkan: Vec<InflightVulkan> = Vec::new();
2345        // ROADMAP row 158: the backlog this realize adds to the device queues; its `Drop` takes it back out on
2346        // the Ok path and when an error unwinds the walk.
2347        let mut backlog = crate::dispatch::BacklogLedger::new();
2348        let mut multi_backend = false;
2349        for item in rx {
2350            let item = item?;
2351            // Chunk-boundary hook: TopologyChanged check + (A4b-4) backend-switch
2352            // detection + eager-submit-on-leaving-a-Vulkan-chunk.
2353            if !is_backend_neutral(&item.kind) && current_chunk_backend != Some(item.target_backend)
2354            {
2355                if let Some(plan_gen) = plan_generation {
2356                    let live = crate::dispatch::topology_generation();
2357                    if live != plan_gen {
2358                        return Err(Error::TopologyChanged {
2359                            plan_generation: plan_gen,
2360                            current_generation: live,
2361                        }
2362                        .bt());
2363                    }
2364                }
2365                let leaving = current_chunk_backend;
2366                if let Some(prev) = leaving
2367                    && prev != item.target_backend
2368                {
2369                    multi_backend = true;
2370                    if prev == BackendId::Vulkan {
2371                        eager_submit_all_vulkan(&cache, &mut inflight_vulkan)?;
2372                    }
2373                }
2374                current_chunk_backend = Some(item.target_backend);
2375            }
2376            // Vulkan realizes run the async path (deferred eviction, size-based eager
2377            // submit) even on a single device: ordering between batches is structural
2378            // (inter-batch barrier + epoch-gated buffer reuse), not a host wait.
2379            if item.target_backend == BackendId::Vulkan && matches!(item.kind, WorkItemKind::Kernel)
2380            {
2381                multi_backend = true;
2382            }
2383            // Inter-batch Vulkan ordering is structural (see realize_inner): no host
2384            // wait before recording a new Vulkan op.
2385            // Step E A4b-3 + A4b-4: cross-device residency boundary. See
2386            // realize_inner for the full rationale.
2387            if matches!(
2388                item.kind,
2389                WorkItemKind::Copy { .. } | WorkItemKind::Move { .. }
2390            ) {
2391                // A4b-4: submit any open Vulkan chunk so the iGPU runs while the
2392                // host (possibly) waits on the CUDA producer.
2393                if multi_backend {
2394                    eager_submit_all_vulkan(&cache, &mut inflight_vulkan)?;
2395                }
2396                if let Some(&producer) = item.inputs.first() {
2397                    // A4b-4: wait in-flight Vulkan ONLY for a Vulkan-source D2H
2398                    // (reads completed data; download flushes only the OPEN batch).
2399                    // A CUDA/CPU source does NOT wait Vulkan (preserves overlap).
2400                    if multi_backend && copy_source_is_vulkan(&cache, producer)? {
2401                        drain_inflight_vulkan(&mut inflight_vulkan)?;
2402                    }
2403                    // Step E A4b-3: finer CUDA source-drain — wait ONLY the producer.
2404                    wait_producer_handle(&mut handles, producer)?;
2405                }
2406            }
2407            let handle = execute_work_item(
2408                &item,
2409                &mut cache,
2410                &mut devices,
2411                &mut layout_cache,
2412                &mut produced_syms,
2413                will_be_waited(&wait_set, item.node_id),
2414                // No persistent-output mode on the standard realize paths —
2415                // fresh alloc per node, byte-identical to pre-CapturedRun.
2416                None,
2417            )
2418            .map_err(|e| with_node_location(&graph, item.node_id, e))?;
2419            store_handle(&mut handles, item.node_id, handle);
2420            feed_backlog(&mut backlog, &cache, &item);
2421            if let Some(d_idx) = item.destructive_input
2422                && let Some(&destroyed) = item.inputs.get(d_idx)
2423                && !target_set.contains(&destroyed)
2424            {
2425                // Step E A2.1 (in-flight DATA-BUFFER lifetime — UAF guard,
2426                // now DEFERRED-DELETION instead of a drain): retain the
2427                // evicted buffer until the reader fences signal — eager-
2428                // submit the open batch (no wait) + move a refcount clone of
2429                // the buffer into every in-flight batch, freeing it post-
2430                // fence on each batch's `Drop` with NO host block. Replaces
2431                // the pre-A2.1 `drain_inflight_vulkan` + open-batch
2432                // `force_flush` (two host-blocking fence waits). See
2433                // `defer_evicted_vulkan_buffer` / realize_inner for the
2434                // UAF/leak argument. CUDA eviction is A3 stream-safe.
2435                // Single-device (multi_backend == false) keeps the pre-A2.1
2436                // blocking force_flush of the OPEN batch (the else branch) —
2437                // byte-identical + UAF-safe; the deferred path is unsafe there
2438                // (see force_flush_vulkan's doc).
2439                if multi_backend {
2440                    defer_evicted_vulkan_buffer(&cache, destroyed, &mut inflight_vulkan)?;
2441                } else if let Some(d_arc) = cache.get(&destroyed) {
2442                    force_flush_vulkan(d_arc)?;
2443                }
2444                cache.remove(&destroyed);
2445                layout_cache.remove(&destroyed);
2446                // CUDA eviction is stream-ordered-safe (A3); drop the
2447                // handle so the realize-end empty-map assert stays valid.
2448                handles.remove(&destroyed);
2449            }
2450        }
2451
2452        compiler
2453            .join()
2454            .map_err(|_| Error::Msg("compiler thread panicked".to_string()).bt())?;
2455
2456        // Step E A4b-1: drain every outstanding async handle (CUDA events) before
2457        // results are read / the cache drops.
2458        drain_handles(&mut handles)?;
2459        // Step E A4b open question #4: blanket per-device stream sync for the
2460        // elided nodes `drain_handles` never tracked — see `realize_inner`'s
2461        // identical comment / `sync_active_cuda_devices`'s doc for the argument.
2462        sync_active_cuda_devices(&cache)?;
2463        // Step E A4b-4: wait every eagerly-submitted in-flight Vulkan batch before
2464        // the cache drops. Empty on a single-device realize.
2465        drain_inflight_vulkan(&mut inflight_vulkan)?;
2466        // Step E A4b-2: drain all deferred Vulkan work — submit the open batch
2467        // then wait it via a `VulkanCompletion` handle (the A2 submit+wait, split;
2468        // byte-identical for pure-Vulkan — one submission at realize-end).
2469        drain_vulkan_pending(&cache)?;
2470        debug_assert!(
2471            inflight_vulkan.is_empty(),
2472            "A4b-4: in-flight Vulkan batch list must be empty after realize-end drain",
2473        );
2474
2475        // Verify every target was realized + collect outputs in
2476        // target order. We don't `remove` from the cache because the
2477        // same NodeId can appear twice in `targets` (caller wants the
2478        // same storage twice) — clone the Arc instead.
2479        let mut out = Vec::with_capacity(targets.len());
2480        for &target in targets {
2481            let storage = cache.get(&target).cloned().ok_or_else(|| {
2482                Error::Msg(format!(
2483                    "PipelinedExecutor::realize_many: target {:?} not populated after execution",
2484                    target
2485                ))
2486                .bt()
2487            })?;
2488            let layout = layout_cache.get(&target).cloned().ok_or_else(|| {
2489                Error::Msg(format!(
2490                    "PipelinedExecutor::realize_many: target layout {:?} not populated after execution",
2491                    target
2492                ))
2493                .bt()
2494            })?;
2495            out.push((storage, layout));
2496        }
2497        Ok(out)
2498    }
2499}
2500
2501/// Resolve the executor's dispatch order from the configured
2502/// [`OrderSource`]. PR-A3b-1: `Optimized` lowers the in-place
2503/// "plan IS the graph" form via `extract_runs`/`lower_run`; `Default`
2504/// keeps the pre-A3b-1 `execution_plan` walk. Both produce the same
2505/// `NodeId` sequence on a branchless graph (A3a equivalence gate),
2506/// computed here AFTER safety-copy insertion so either path covers
2507/// any freshly inserted copies.
2508fn order_for(
2509    graph: &Graph,
2510    effective_roots: &[NodeId],
2511    order_source: &OrderSource<'_>,
2512) -> Vec<NodeId> {
2513    match order_source {
2514        OrderSource::Default => execution_plan(graph, effective_roots),
2515        // The streaming walk is driven in the compiler thread (it
2516        // interleaves arm resolution with compilation), so `order_for`
2517        // never flattens it on the production path. This arm exists only
2518        // for match totality / non-pipelined callers: it collects the SAME
2519        // lazily-resolved order eagerly (the streaming walk with the same
2520        // `resolve_branch` over the threaded selector), which equals the
2521        // one-shot `lower_picked_route(pick_route(..))` order.
2522        OrderSource::Streaming {
2523            optimized: _optimized,
2524            pick,
2525        } => {
2526            let bindings = global_bindings();
2527            fuel_graph::lower_picked_route_streaming(graph, effective_roots, |branch| {
2528                resolve_branch(graph, branch, &bindings, pick.selector.as_ref())
2529            })
2530        }
2531        OrderSource::Optimized { optimized, route } => {
2532            // Lower the runs over the *effective* roots (user targets +
2533            // any spliced/side-effect roots) so the order matches the
2534            // walk's reachable set rather than only the optimize-time
2535            // roots. On a branchless graph this is the same concatenated
2536            // `lower_run` sequence the OptimizedGraph reports.
2537            //
2538            // PR-C1: when the picker supplied a route, follow the chosen
2539            // arms (`lower_picked_route`); otherwise the arm-0 lowering
2540            // (`OptimizedGraph::dispatch_order`). An empty route is
2541            // byte-identical to arm-0, so the two paths agree whenever
2542            // the picker chose arm-0 everywhere (the no-pressure case).
2543            match route {
2544                Some(route) => fuel_graph::lower_picked_route(graph, effective_roots, route),
2545                None => {
2546                    // A transient view built solely to call `dispatch_order`;
2547                    // it does no planning, so it carries no placements. The
2548                    // real optimization's map lives on `optimized`.
2549                    let view = OptimizedGraph {
2550                        roots: effective_roots.to_vec(),
2551                        generation: optimized.generation,
2552                        placements: None,
2553                        eviction: None,
2554                    };
2555                    view.dispatch_order(graph)
2556                }
2557            }
2558        }
2559        // Resolved by `compiler_work_and_wait_set_for` before delegating
2560        // here (the whole point of `Cached` is to skip this computation
2561        // on a hit) — never reached. Kept exhaustive rather than wildcarded
2562        // so a future `OrderSource` variant can't silently fall through.
2563        OrderSource::Cached { .. } => {
2564            unreachable!("OrderSource::Cached is resolved before order_for is called")
2565        }
2566    }
2567}
2568
2569/// Step E A4b open question #4 — "event only where waited". The producer
2570/// [`NodeId`]s that some later `Op::Copy`/`Op::Move` node in `order` will
2571/// `wait_producer_handle` on (the executor's cross-device residency
2572/// boundary — see `wait_producer_handle`, whose `item.inputs.first()` read
2573/// this mirrors exactly). A CUDA node whose id is absent from the returned
2574/// set has NO mid-walk reader: same-device consumers are correct via stream
2575/// ordering alone (they never `wait`), and nothing touches its handle before
2576/// the realize-end drain, so [`crate::compiled::execute_compiled_with_wait_hint`]
2577/// can skip recording an `Event` for it entirely.
2578///
2579/// Requires a materialized `order` (works for [`OrderSource::Default`] /
2580/// [`OrderSource::Optimized`], whose [`CompilerWork::Order`] is a frozen
2581/// `Vec<NodeId>` computed up front) — see
2582/// [`compiler_work_and_wait_set_for`] for the [`OrderSource::Streaming`]
2583/// fallback.
2584fn build_wait_set(graph: &Graph, order: &[NodeId]) -> HashSet<NodeId> {
2585    let mut set = HashSet::new();
2586    for &id in order {
2587        let node = graph.node(id);
2588        if matches!(node.op, Op::Copy { .. } | Op::Move { .. })
2589            && let Some(&producer) = node.inputs.first()
2590        {
2591            set.insert(producer);
2592        }
2593    }
2594    set
2595}
2596
2597/// Step E A4b open question #4: the executor's per-realize wait-set.
2598/// `None` is the CONSERVATIVE fallback — every CUDA node still gets an Event
2599/// (today's pre-elision behavior, byte-identical). `Some(set)` restricts
2600/// event production to `set`'s members ([`build_wait_set`]'s output);
2601/// everything else gets `CompletionHandle::Ready` with no Event recorded.
2602type WaitSet = Option<HashSet<NodeId>>;
2603
2604/// Whether `node_id`'s completion handle must be individually observable
2605/// (i.e. `execute_compiled_with_wait_hint`'s `will_be_waited`). `None` (the
2606/// [`OrderSource::Streaming`] fallback — never elides) is always `true`.
2607#[inline]
2608fn will_be_waited(wait_set: &WaitSet, node_id: NodeId) -> bool {
2609    match wait_set {
2610        None => true,
2611        Some(set) => set.contains(&node_id),
2612    }
2613}
2614
2615/// Build the [`CompilerWork`] the compiler thread walks for the configured
2616/// [`OrderSource`], plus the [`WaitSet`] "event only where waited" (open
2617/// question #4) consults. The non-streaming sources flatten up front via
2618/// [`order_for`] (unchanged) and the SAME materialized order feeds
2619/// [`build_wait_set`], so the pre-scan and the dispatch order never
2620/// disagree. [`OrderSource::Streaming`] is handed to the compiler thread as
2621/// a [`CompilerWork::Streaming`] spec — NOT flattened here — so the thread
2622/// resolves branches lazily at the frontier (Step E Phase C, PR C1); the lazy
2623/// order can't be pre-scanned without eagerly resolving it (which would
2624/// defeat the point of streaming), so it falls back to the conservative
2625/// `WaitSet::None` — event every node, unchanged behavior. Holds the graph
2626/// read-lock only for the flattening branches; the streaming branch defers
2627/// the lock to the compiler thread.
2628fn compiler_work_and_wait_set_for(
2629    graph: &Graph,
2630    effective_roots: &[NodeId],
2631    order_source: &OrderSource<'_>,
2632) -> (CompilerWork, WaitSet) {
2633    match order_source {
2634        OrderSource::Streaming { pick, .. } => (
2635            CompilerWork::Streaming {
2636                roots: effective_roots.to_vec(),
2637                pick: (*pick).clone(),
2638            },
2639            None,
2640        ),
2641        OrderSource::Cached {
2642            optimized,
2643            order_cache,
2644        } => {
2645            let order = order_cache.get_or_init(|| {
2646                order_for(
2647                    graph,
2648                    effective_roots,
2649                    &OrderSource::Optimized {
2650                        optimized,
2651                        route: None,
2652                    },
2653                )
2654            });
2655            let wait_set = build_wait_set(graph, order);
2656            (CompilerWork::Order(order.clone()), Some(wait_set))
2657        }
2658        other => {
2659            let order = order_for(graph, effective_roots, other);
2660            let wait_set = build_wait_set(graph, &order);
2661            (CompilerWork::Order(order), Some(wait_set))
2662        }
2663    }
2664}
2665
2666/// The topology generation that keys the executor's `TopologyChanged`
2667/// chunk-boundary check. Uses the `OptimizedGraph`'s optimize-time
2668/// generation (PR-A3b-1 path). `None` ⇒ no check (the plain
2669/// `realize`/`realize_many` entries).
2670fn generation_for(order_source: &OrderSource<'_>) -> Option<u64> {
2671    match order_source {
2672        OrderSource::Optimized { optimized, .. } => Some(optimized.generation),
2673        OrderSource::Streaming { optimized, .. } => Some(optimized.generation),
2674        OrderSource::Cached { optimized, .. } => Some(optimized.generation),
2675        OrderSource::Default => None,
2676    }
2677}
2678
2679/// What the compiler thread walks: either a pre-flattened dispatch
2680/// `Order` (the `Default` / `Optimized` paths — unchanged), or a
2681/// `Streaming` spec the thread resolves branch-by-branch at the frontier
2682/// (Step E Phase C, PR C1).
2683enum CompilerWork {
2684    /// A frozen topological order (computed up front by `order_for`). The
2685    /// compiler thread compiles each node and sends it in turn.
2686    Order(Vec<NodeId>),
2687    /// The streaming run-walk: the compiler thread drives
2688    /// [`fuel_graph::walk_picked_route_streaming`] over `roots`, resolving
2689    /// each `Op::Branch` lazily via [`resolve_branch`] as the frontier
2690    /// reaches its arm-entry, and compiling + sending only the chosen
2691    /// arm's runs. `roots` are the effective roots (same set `order_for`
2692    /// lowers over). Byte-identical to `Order(lower_picked_route(
2693    /// pick_route(..)))` in C1 (same VRAM-only selector).
2694    Streaming {
2695        roots: Vec<NodeId>,
2696        pick: StreamingPick,
2697    },
2698}
2699
2700/// Compiler thread body. Holds the graph read-lock + a thread-local
2701/// layout cache and emits `WorkItem`s in topological order. For
2702/// [`CompilerWork::Order`] it walks the frozen order; for
2703/// [`CompilerWork::Streaming`] it resolves each branch at the frontier and
2704/// emits only the chosen arm's runs (Step E Phase C, PR C1). Sends
2705/// `Err(...)` and stops on the first failure.
2706fn compiler_thread_body(
2707    graph: Arc<RwLock<Graph>>,
2708    work: CompilerWork,
2709    sym_env: SymEnv,
2710    tx: Sender<Result<WorkItem>>,
2711) {
2712    let bindings = global_bindings();
2713
2714    let g = match graph.read() {
2715        Ok(g) => g,
2716        Err(_) => {
2717            let _ = tx.send(Err(poisoned("graph lock in compiler")));
2718            return;
2719        }
2720    };
2721
2722    // Compiler-thread-local layout cache. Populated as compile_one
2723    // walks topologically; downstream nodes look up their inputs'
2724    // layouts here (rather than from the graph side-table) to honor
2725    // the strided layouts emitted by metadata-only view ops earlier
2726    // in the same realize call.
2727    let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
2728    // `compile_one` for one node + send; returns `false` to stop the walk
2729    // (channel closed or compile error). Shared by both work modes so the
2730    // streamed and frozen-order paths compile identically.
2731    // Arm exits of live branches. The reconverge node reads ARM 0's exit (the runnability invariant),
2732    // so when the picker chooses an arm k >= 1 its exit is the value the reconverge must see: right
2733    // after compiling that exit, alias arm 0's exit id to it (a zero-copy `ViewOf`). Non-chosen arms
2734    // are never compiled, so an exit that is compiled here is the chosen one.
2735    let alias_exits: HashMap<NodeId, NodeId> = {
2736        let mut m = HashMap::new();
2737        for i in 0..g.len() {
2738            let id = NodeId(i);
2739            if matches!(g.node(id).op, Op::Branch { .. }) {
2740                let arms = &g.node(id).inputs;
2741                for &exit in arms.iter().skip(1) {
2742                    m.insert(exit, arms[0]);
2743                }
2744            }
2745        }
2746        m
2747    };
2748    // Diagnostic (`FUEL_PRINT_BRANCH_COUNT`): every node the compiler thread sends, in order, so a failed
2749    // realize can be read against the order it was fed.
2750    let print_order = std::env::var_os("FUEL_PRINT_BRANCH_COUNT").is_some();
2751    let compile_and_send = |id: NodeId, layout_cache: &mut HashMap<NodeId, Layout>| -> bool {
2752        if print_order {
2753            let n = g.node(id);
2754            eprintln!(
2755                "fuel: send Node#{} {} inputs={:?} backend={:?} placement={:?}",
2756                id.0,
2757                format!("{:?}", n.op).chars().take(40).collect::<String>(),
2758                n.inputs.iter().map(|i| i.0).collect::<Vec<_>>(),
2759                g.target_backend(id),
2760                g.placement(id),
2761            );
2762        }
2763        let item = compile_one(&g, id, layout_cache, &bindings, &sym_env);
2764        let stop_on_err = item.is_err();
2765        if tx.send(item).is_err() {
2766            return false;
2767        }
2768        if stop_on_err {
2769            return false;
2770        }
2771        if let Some(&arm0_exit) = alias_exits.get(&id)
2772            && tx
2773                .send(Ok(arm_exit_alias_item(&g, arm0_exit, id, layout_cache)))
2774                .is_err()
2775        {
2776            return false;
2777        }
2778        true
2779    };
2780
2781    match work {
2782        CompilerWork::Order(order) => {
2783            for id in order {
2784                if !compile_and_send(id, &mut layout_cache) {
2785                    return;
2786                }
2787            }
2788        }
2789        CompilerWork::Streaming { roots, pick } => {
2790            // Resolve each branch lazily at its arm-entry. C1 built the
2791            // streaming frontier; C2 made `pick.selector` load-aware (the
2792            // production `ChainedSelector` now reads each arm's live device
2793            // load — `pending_work_count / slot_capacity` via the
2794            // `BackendStreams` seam — as a key leg under the VRAM guard),
2795            // so this resolution reads live device load at THIS moment: the
2796            // executor has been submitting/draining (and updating the B1
2797            // counter) while the compiler ran ahead. Emit only the chosen
2798            // arm's runs, compiling + sending each node as the walk reaches
2799            // it — genuine streaming (resolution interleaved with
2800            // dispatch), not a pre-flattened order.
2801            let mut stopped = false;
2802            fuel_graph::walk_picked_route_streaming(
2803                &g,
2804                &roots,
2805                |branch| resolve_branch(&g, branch, &bindings, pick.selector.as_ref()),
2806                |members| {
2807                    if stopped {
2808                        return;
2809                    }
2810                    for &id in members {
2811                        if !compile_and_send(id, &mut layout_cache) {
2812                            stopped = true;
2813                            return;
2814                        }
2815                    }
2816                },
2817            );
2818        }
2819    }
2820}
2821
2822/// The work item that makes arm 0's exit id carry the value of the chosen arm's exit: a zero-copy
2823/// `ViewOf` (the executor clones the source's storage into `alias_id`'s cache slot). Emitted right
2824/// after the chosen exit, before the reconverge node that reads `alias_id`. The two exits agree on
2825/// shape and dtype by the branch's cast-to-uniform rule, so the layout is the source's.
2826fn arm_exit_alias_item(
2827    graph: &Graph,
2828    alias_id: NodeId,
2829    source: NodeId,
2830    layout_cache: &mut HashMap<NodeId, Layout>,
2831) -> WorkItem {
2832    let node = graph.node(alias_id);
2833    let layout = layout_cache
2834        .get(&source)
2835        .cloned()
2836        .unwrap_or_else(|| Layout::contiguous(graph.node(source).shape.clone()));
2837    layout_cache.insert(alias_id, layout.clone());
2838    WorkItem {
2839        node_id: alias_id,
2840        inputs: vec![source],
2841        elem_count: node.shape.elem_count(),
2842        dtype: node.dtype,
2843        target_backend: graph
2844            .target_backend(source)
2845            .or_else(|| graph.target_backend(alias_id))
2846            .unwrap_or(BackendId::Cpu),
2847        kind: WorkItemKind::ViewOf { input: source },
2848        compiled: None,
2849        output_layout: layout,
2850        destructive_input: None,
2851        output_bundle: None,
2852    }
2853}
2854
2855/// Resolve the [`CompiledNode`] for a kernel-bearing graph node via
2856/// the first-registered [`compile_node`] binding-table lookup.
2857///
2858/// `op_params` always comes from the executor's
2859/// `op_to_op_params(graph, node, id, layout_cache, sym_env)` — the live
2860/// OpParams shape (reduce dims, conv geometry, the per-pass
2861/// `SymEnv`-resolved `WriteSlice` offset, etc.) derives from the graph
2862/// node + its resolved input layouts at execute time.
2863fn resolve_compiled(
2864    graph: &Graph,
2865    node: &fuel_graph::Node,
2866    op_kind: OpKind,
2867    dtypes: &[DType],
2868    target_backend: BackendId,
2869    op_params: OpParams,
2870    bindings: &KernelBindingTable,
2871) -> Result<CompiledNode> {
2872    let mut compiled = compile_node(op_kind, dtypes, target_backend, op_params, bindings)?;
2873    // ROADMAP row 158: price the launch ONCE here so the executor's per-op feed of the device backlog is a
2874    // field read, not a cost-model query (see `compiled::estimate_static_ns`).
2875    if target_backend != BackendId::Cpu {
2876        let shapes: Vec<fuel_ir::Shape> = node
2877            .inputs
2878            .iter()
2879            .map(|&i| graph.node(i).shape.clone())
2880            .collect();
2881        compiled.est_ns = crate::compiled::estimate_static_ns(
2882            op_kind,
2883            dtypes,
2884            &shapes,
2885            target_backend,
2886            &compiled.op_params,
2887            bindings,
2888        );
2889    }
2890    Ok(compiled)
2891}
2892
2893/// Resolve one node into a `WorkItem` and update `layout_cache`
2894/// with the node's output layout. Three op shapes:
2895///
2896/// - `Op::Const` — adopts the entry from the input cache; layout is
2897///   read from the graph's side-table (or its contiguous fallback).
2898///
2899/// - Metadata-only view op — output layout is read from the graph's
2900///   side-table (populated by `Graph::push` at construction time);
2901///   the executor adopts the input's Storage Arc (no allocation, no
2902///   kernel).
2903///
2904/// - Computational op — output layout is `Layout::contiguous(node.shape)`
2905///   because today's kernels write contiguous output. The compiler
2906///   resolves the kernel ref and emits a Kernel work item.
2907fn compile_one(
2908    graph: &Graph,
2909    id: NodeId,
2910    layout_cache: &mut HashMap<NodeId, Layout>,
2911    bindings: &KernelBindingTable,
2912    sym_env: &SymEnv,
2913) -> Result<WorkItem> {
2914    let node = graph.node(id);
2915    let elem_count = node.shape.elem_count();
2916    let inputs = node.inputs.clone();
2917    // Snapshot destructive-input metadata from the graph at compile
2918    // time so the executor can evict the destroyed input from its
2919    // cache after the op runs (Op::Release / Op::Move semantics).
2920    let destructive_input = node.op.destructive_input();
2921
2922    if matches!(node.op, Op::Const) {
2923        let output_layout = graph.layout(id);
2924        layout_cache.insert(id, output_layout.clone());
2925        return Ok(WorkItem {
2926            node_id: id,
2927            inputs,
2928            elem_count,
2929            dtype: node.dtype,
2930            target_backend: BackendId::Cpu,
2931            kind: WorkItemKind::ConstAdopt,
2932            compiled: None,
2933            output_layout,
2934            destructive_input,
2935            output_bundle: None,
2936        });
2937    }
2938
2939    if node.op.is_view_op() {
2940        if inputs.len() != 1 {
2941            return Err(Error::Msg(format!(
2942                "view op {:?} expects 1 input, got {}",
2943                node.op,
2944                inputs.len(),
2945            ))
2946            .bt());
2947        }
2948        // Layout is read from the graph's side-table — populated by
2949        // `Graph::push` at construction time for view ops, and by
2950        // graph-rewriting opt passes that emit view nodes. The
2951        // compiler does not re-derive: graph.layout(id) is the single
2952        // source of truth.
2953        let output_layout = graph.layout(id);
2954        layout_cache.insert(id, output_layout.clone());
2955        // Inherit the upstream's target_backend (or default CPU) —
2956        // metadata-only adoption doesn't actually run on a backend,
2957        // but downstream consumers look at target_backend so it
2958        // needs to be set sensibly. Any device works.
2959        let target_backend = graph
2960            .target_backend(id)
2961            .or_else(|| graph.target_backend(inputs[0]))
2962            .unwrap_or(BackendId::Cpu);
2963        return Ok(WorkItem {
2964            node_id: id,
2965            inputs,
2966            elem_count,
2967            dtype: node.dtype,
2968            target_backend,
2969            kind: WorkItemKind::ViewOf {
2970                input: node.inputs[0],
2971            },
2972            compiled: None,
2973            output_layout,
2974            destructive_input,
2975            output_bundle: None,
2976        });
2977    }
2978
2979    // Op::View — multi-output projection (Option C, Session 4).
2980    // Structurally identical to a metadata-only view op at realize
2981    // time: clone the producer's Storage Arc into the View's cache
2982    // slot. The graph's layout side-table, populated by
2983    // `Tensor::view`, already carries the slot's effective layout
2984    // (slot.byte_offset baked into start_offset in slot-dtype-element
2985    // units).
2986    if let Op::View { .. } = node.op {
2987        if inputs.len() != 1 {
2988            return Err(Error::Msg(format!(
2989                "Op::View expects 1 input (the producer), got {}",
2990                inputs.len(),
2991            ))
2992            .bt());
2993        }
2994        let output_layout = graph.layout(id);
2995        layout_cache.insert(id, output_layout.clone());
2996        let target_backend = graph
2997            .target_backend(id)
2998            .or_else(|| graph.target_backend(inputs[0]))
2999            .unwrap_or(BackendId::Cpu);
3000        return Ok(WorkItem {
3001            node_id: id,
3002            inputs: inputs.clone(),
3003            elem_count,
3004            dtype: node.dtype,
3005            target_backend,
3006            kind: WorkItemKind::SlotView {
3007                producer: inputs[0],
3008            },
3009            compiled: None,
3010            output_layout,
3011            destructive_input,
3012            output_bundle: None,
3013        });
3014    }
3015
3016    // Op::ViewOwned — copies the slot's bytes into a fresh
3017    // contiguous Storage at realize time. Output layout is
3018    // contiguous starting at offset 0 (the memcpy produced an
3019    // independent buffer).
3020    if let Op::ViewOwned { slot } = node.op {
3021        if inputs.len() != 1 {
3022            return Err(Error::Msg(format!(
3023                "Op::ViewOwned expects 1 input (the producer), got {}",
3024                inputs.len(),
3025            ))
3026            .bt());
3027        }
3028        let output_layout = Layout::contiguous(node.shape.clone());
3029        layout_cache.insert(id, output_layout.clone());
3030        let target_backend = graph
3031            .target_backend(id)
3032            .or_else(|| graph.target_backend(inputs[0]))
3033            .unwrap_or(BackendId::Cpu);
3034        return Ok(WorkItem {
3035            node_id: id,
3036            inputs: inputs.clone(),
3037            elem_count,
3038            dtype: node.dtype,
3039            target_backend,
3040            kind: WorkItemKind::SlotOwn {
3041                producer: inputs[0],
3042                slot,
3043            },
3044            compiled: None,
3045            output_layout,
3046            destructive_input,
3047            output_bundle: None,
3048        });
3049    }
3050
3051    if matches!(node.op, Op::Release) {
3052        // Op::Release produces a zero-element marker output. The
3053        // marker storage is CPU + 0 bytes — nothing reads it; it
3054        // exists so cache lookups on the Release NodeId resolve.
3055        // The actual deallocation of `inputs[0]` happens in the
3056        // realize loop via `destructive_input` cleanup.
3057        if inputs.len() != 1 {
3058            return Err(
3059                Error::Msg(format!("Op::Release expects 1 input, got {}", inputs.len(),)).bt(),
3060            );
3061        }
3062        let output_layout = Layout::contiguous(node.shape.clone());
3063        layout_cache.insert(id, output_layout.clone());
3064        // Inherit the source's target_backend so any downstream
3065        // backend-aware logic (telemetry, scheduling) sees a sensible
3066        // value. The marker doesn't actually run on any backend.
3067        let target_backend = graph
3068            .target_backend(id)
3069            .or_else(|| graph.target_backend(inputs[0]))
3070            .unwrap_or(BackendId::Cpu);
3071        return Ok(WorkItem {
3072            node_id: id,
3073            inputs,
3074            elem_count,
3075            dtype: node.dtype,
3076            target_backend,
3077            kind: WorkItemKind::ReleaseMarker,
3078            compiled: None,
3079            output_layout,
3080            destructive_input,
3081            output_bundle: None,
3082        });
3083    }
3084
3085    // In-place ops (Phase 3 of in-place ops infrastructure): kernel
3086    // lookup goes through the standard binding-table path, but the
3087    // executor adopts the target's Arc as the output instead of
3088    // allocating fresh bytes. The compile-time predicate is exactly
3089    // `op.destructive_input().is_some()` AND NOT one of the
3090    // structural ops (WriteSlice / ZeroFill / Release / Move) which
3091    // have their own dedicated WorkItemKind arms in this function.
3092    if !matches!(
3093        node.op,
3094        Op::WriteSlice { .. }
3095            | Op::WriteSliceRotating { .. }
3096            | Op::WriteSliceDoff { .. }
3097            | Op::ZeroFill
3098            | Op::Release
3099            | Op::Move { .. },
3100    ) && let Some(target_idx) = node.op.destructive_input()
3101    {
3102        if inputs.len() <= target_idx {
3103            return Err(Error::Msg(format!(
3104                "in-place op {:?} declares destructive_input={target_idx} \
3105                     but has only {} input(s)",
3106                node.op,
3107                inputs.len(),
3108            ))
3109            .bt());
3110        }
3111        let target_backend = graph.target_backend(id).ok_or_else(|| {
3112            Error::Msg(format!(
3113                "PipelinedExecutor: in-place op node {id:?} has no target_backend set",
3114            ))
3115            .bt()
3116        })?;
3117        let op_kind = op_to_op_kind(&node.op).ok_or_else(|| {
3118            Error::Msg(format!(
3119                "PipelinedExecutor: in-place op {:?} has no op_to_op_kind mapping",
3120                node.op,
3121            ))
3122            .bt()
3123        })?;
3124        let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3125        let dtypes = build_lookup_dtypes(graph, node);
3126        let compiled = resolve_compiled(
3127            graph,
3128            node,
3129            op_kind,
3130            &dtypes,
3131            target_backend,
3132            op_params,
3133            bindings,
3134        )?;
3135        // Output adopts target's Layout (same Storage Arc, same shape).
3136        let output_layout = graph.layout(inputs[target_idx]);
3137        layout_cache.insert(id, output_layout.clone());
3138        return Ok(WorkItem {
3139            node_id: id,
3140            inputs: inputs.clone(),
3141            elem_count,
3142            dtype: node.dtype,
3143            target_backend,
3144            kind: WorkItemKind::InplaceKernel { target_idx },
3145            compiled: Some(compiled),
3146            output_layout,
3147            destructive_input,
3148            output_bundle: None,
3149        });
3150    }
3151
3152    if matches!(node.op, Op::WriteSlice { .. }) {
3153        // WriteSlice: kernel lookup happens like a normal kernel, but
3154        // the work item carries a dedicated kind so the executor
3155        // knows to adopt the destination's Arc as the output rather
3156        // than allocating a fresh buffer. The destination's NodeId is
3157        // captured here so the executor doesn't have to re-derive it.
3158        if inputs.len() != 2 {
3159            return Err(Error::Msg(format!(
3160                "Op::WriteSlice expects 2 inputs (destination, source), got {}",
3161                inputs.len(),
3162            ))
3163            .bt());
3164        }
3165        let target_backend = graph.target_backend(id).ok_or_else(|| {
3166            Error::Msg(format!(
3167                "PipelinedExecutor: WriteSlice node {:?} has no target_backend set",
3168                id
3169            ))
3170            .bt()
3171        })?;
3172        let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3173        let dtypes = build_lookup_dtypes(graph, node);
3174        let compiled = resolve_compiled(
3175            graph,
3176            node,
3177            OpKind::WriteSlice,
3178            &dtypes,
3179            target_backend,
3180            op_params,
3181            bindings,
3182        )?;
3183        // Output adopts the destination's Layout — same Storage Arc,
3184        // same shape. Downstream consumers that want a post-write
3185        // sub-extent compose an explicit Op::Slice (WriteSlice does
3186        // not encode partial extents).
3187        let output_layout = graph.layout(inputs[0]);
3188        layout_cache.insert(id, output_layout.clone());
3189        return Ok(WorkItem {
3190            node_id: id,
3191            inputs: inputs.clone(),
3192            elem_count,
3193            dtype: node.dtype,
3194            target_backend,
3195            kind: WorkItemKind::WriteSlice {
3196                dest: inputs[0],
3197                source: inputs[1],
3198            },
3199            compiled: Some(compiled),
3200            output_layout,
3201            destructive_input,
3202            output_bundle: None,
3203        });
3204    }
3205
3206    if matches!(node.op, Op::WriteSliceRotating { .. }) {
3207        // WriteSliceRotating: same shape as WriteSlice but with a
3208        // third input (position scalar). Dispatch through the
3209        // binding table at `OpKind::WriteSliceRotating`; the
3210        // executor's arm reads the position from `position`'s
3211        // storage and the kernel splits across the ring boundary.
3212        if inputs.len() != 3 {
3213            return Err(Error::Msg(format!(
3214                "Op::WriteSliceRotating expects 3 inputs (destination, source, position), got {}",
3215                inputs.len(),
3216            ))
3217            .bt());
3218        }
3219        let target_backend = graph.target_backend(id).ok_or_else(|| {
3220            Error::Msg(format!(
3221                "PipelinedExecutor: WriteSliceRotating node {:?} has no target_backend set",
3222                id
3223            ))
3224            .bt()
3225        })?;
3226        let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3227        let dtypes = build_lookup_dtypes(graph, node);
3228        let compiled = resolve_compiled(
3229            graph,
3230            node,
3231            OpKind::WriteSliceRotating,
3232            &dtypes,
3233            target_backend,
3234            op_params,
3235            bindings,
3236        )?;
3237        let output_layout = graph.layout(inputs[0]);
3238        layout_cache.insert(id, output_layout.clone());
3239        return Ok(WorkItem {
3240            node_id: id,
3241            inputs: inputs.clone(),
3242            elem_count,
3243            dtype: node.dtype,
3244            target_backend,
3245            kind: WorkItemKind::WriteSliceRotating {
3246                dest: inputs[0],
3247                source: inputs[1],
3248                position: inputs[2],
3249            },
3250            compiled: Some(compiled),
3251            output_layout,
3252            destructive_input,
3253            output_bundle: None,
3254        });
3255    }
3256
3257    if matches!(node.op, Op::WriteSliceDoff { .. }) {
3258        // WriteSliceDoff: same shape as WriteSlice but with a third
3259        // input (device-resident I64 offset). Dispatch through the
3260        // binding table at `OpKind::WriteSliceDoff`; the executor's arm
3261        // threads the offset's device pointer straight to the kernel
3262        // (no D2H, capture-safe).
3263        if inputs.len() != 3 {
3264            return Err(Error::Msg(format!(
3265                "Op::WriteSliceDoff expects 3 inputs (destination, source, offset), got {}",
3266                inputs.len(),
3267            ))
3268            .bt());
3269        }
3270        let target_backend = graph.target_backend(id).ok_or_else(|| {
3271            Error::Msg(format!(
3272                "PipelinedExecutor: WriteSliceDoff node {:?} has no target_backend set",
3273                id
3274            ))
3275            .bt()
3276        })?;
3277        let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3278        let dtypes = build_lookup_dtypes(graph, node);
3279        let compiled = resolve_compiled(
3280            graph,
3281            node,
3282            OpKind::WriteSliceDoff,
3283            &dtypes,
3284            target_backend,
3285            op_params,
3286            bindings,
3287        )?;
3288        let output_layout = graph.layout(inputs[0]);
3289        layout_cache.insert(id, output_layout.clone());
3290        return Ok(WorkItem {
3291            node_id: id,
3292            inputs: inputs.clone(),
3293            elem_count,
3294            dtype: node.dtype,
3295            target_backend,
3296            kind: WorkItemKind::WriteSliceDoff {
3297                dest: inputs[0],
3298                source: inputs[1],
3299                offset: inputs[2],
3300            },
3301            compiled: Some(compiled),
3302            output_layout,
3303            destructive_input,
3304            output_bundle: None,
3305        });
3306    }
3307
3308    if let Op::Alloc { target } = node.op {
3309        // Op::Alloc { target }: produce a fresh zero-init Storage on
3310        // `target` with node.shape * node.dtype. Zero inputs.
3311        // Direct executor dispatch via WorkItemKind::Alloc — no
3312        // binding-table lookup (the device handle threading isn't
3313        // expressible through the binding table's current key shape).
3314        if !inputs.is_empty() {
3315            return Err(
3316                Error::Msg(format!("Op::Alloc expects 0 inputs, got {}", inputs.len(),)).bt(),
3317            );
3318        }
3319        let output_layout = Layout::contiguous(node.shape.clone());
3320        layout_cache.insert(id, output_layout.clone());
3321        // target_backend is informational here (the executor's Alloc
3322        // arm consults target_location for allocation routing); set
3323        // it to target's backend for consistency with how downstream
3324        // nodes inherit/read it.
3325        let target_backend = target.backend();
3326        return Ok(WorkItem {
3327            node_id: id,
3328            inputs,
3329            elem_count,
3330            dtype: node.dtype,
3331            target_backend,
3332            kind: WorkItemKind::Alloc {
3333                target_location: target,
3334            },
3335            compiled: None,
3336            output_layout,
3337            destructive_input,
3338            output_bundle: None,
3339        });
3340    }
3341
3342    if let Op::Iota { len } = node.op {
3343        // Op::Iota { len }: 0-input F32 position generator
3344        // [0.0, 1.0, …, (len-1)]. Direct executor dispatch via
3345        // WorkItemKind::Iota — no binding-table lookup (a leaf has no
3346        // inputs[0] to inherit a backend from). Modeled on Op::Alloc.
3347        if !inputs.is_empty() {
3348            return Err(
3349                Error::Msg(format!("Op::Iota expects 0 inputs, got {}", inputs.len(),)).bt(),
3350            );
3351        }
3352        let output_layout = Layout::contiguous(node.shape.clone());
3353        layout_cache.insert(id, output_layout.clone());
3354        // Leaf: the planner may not place a 0-input node, so fall back to
3355        // CPU. Iota is a tiny host-side generator; its only consumer today
3356        // is the CPU flash-attn decomposition's alibi bias.
3357        let target_backend = graph.target_backend(id).unwrap_or(BackendId::Cpu);
3358        return Ok(WorkItem {
3359            node_id: id,
3360            inputs,
3361            elem_count,
3362            dtype: node.dtype,
3363            target_backend,
3364            kind: WorkItemKind::Iota {
3365                len,
3366                target_location: graph.placement(id),
3367            },
3368            compiled: None,
3369            output_layout,
3370            destructive_input,
3371            output_bundle: None,
3372        });
3373    }
3374
3375    if matches!(node.op, Op::ZeroFill) {
3376        // Op::ZeroFill: 1 input (the buffer to zero); output aliases
3377        // input's Storage Arc (destructive in-place). No binding-
3378        // table lookup — per-backend dispatch in execute_work_item.
3379        if inputs.len() != 1 {
3380            return Err(Error::Msg(format!(
3381                "Op::ZeroFill expects 1 input, got {}",
3382                inputs.len(),
3383            ))
3384            .bt());
3385        }
3386        // Output layout: contiguous in the node's shape. We don't
3387        // require the input to be contiguous (auto_contiguize in the
3388        // executor handles strided inputs), but the destructive
3389        // semantic means callers should only ZeroFill an Op::Alloc
3390        // output today.
3391        let output_layout = Layout::contiguous(node.shape.clone());
3392        layout_cache.insert(id, output_layout.clone());
3393        let target_backend = graph
3394            .target_backend(id)
3395            .or_else(|| graph.target_backend(inputs[0]))
3396            .unwrap_or(BackendId::Cpu);
3397        return Ok(WorkItem {
3398            node_id: id,
3399            inputs,
3400            elem_count,
3401            dtype: node.dtype,
3402            target_backend,
3403            kind: WorkItemKind::ZeroFill,
3404            compiled: None,
3405            output_layout,
3406            destructive_input,
3407            output_bundle: None,
3408        });
3409    }
3410
3411    if let Op::Copy { target } = node.op {
3412        // Op::Copy { target }: download bytes from the source residency
3413        // to a fresh Storage allocated on `target`. Kernel lookup uses
3414        // `target_backend` = source backend (set by `prepare()` on the
3415        // realize device the source is on); the wrapper does the actual
3416        // transfer (e.g. Vulkan::download_bytes → memcpy into a CPU
3417        // CpuStorageBytes). The output Storage's variant is determined
3418        // by `target_location` and allocated in `execute_work_item`'s
3419        // WorkItemKind::Copy arm.
3420        if inputs.len() != 1 {
3421            return Err(
3422                Error::Msg(format!("Op::Copy expects 1 input, got {}", inputs.len(),)).bt(),
3423            );
3424        }
3425        let target_backend = graph.target_backend(id).ok_or_else(|| {
3426            Error::Msg(format!(
3427                "PipelinedExecutor: Op::Copy node {:?} has no target_backend \
3428                 set (= source backend, the one whose kernel runs the \
3429                 download)",
3430                id
3431            ))
3432            .bt()
3433        })?;
3434        let op_params = OpParams::None;
3435        let dtypes = build_lookup_dtypes(graph, node);
3436        let compiled = resolve_compiled(
3437            graph,
3438            node,
3439            OpKind::Copy,
3440            &dtypes,
3441            target_backend,
3442            op_params,
3443            bindings,
3444        )?;
3445        // Output layout: contiguous in the node's shape (mirrors the
3446        // source's logical shape). Auto-contiguize on the input side
3447        // (in execute_work_item) handles strided source views by
3448        // materializing them into a contiguous source buffer before
3449        // the kernel runs.
3450        let output_layout = Layout::contiguous(node.shape.clone());
3451        layout_cache.insert(id, output_layout.clone());
3452        return Ok(WorkItem {
3453            node_id: id,
3454            inputs,
3455            elem_count,
3456            dtype: node.dtype,
3457            target_backend,
3458            kind: WorkItemKind::Copy {
3459                target_location: target,
3460            },
3461            compiled: Some(compiled),
3462            output_layout,
3463            destructive_input,
3464            output_bundle: None,
3465        });
3466    }
3467
3468    if let Op::Move { target } = node.op {
3469        // Op::Move { target }: identical data-movement half to
3470        // Op::Copy — kernel lookup at (OpKind::Copy, [dt, dt],
3471        // source_backend); output allocated on `target` by the
3472        // executor's Copy/Move arm. The destructive half (release
3473        // the source) rides the realize loop's `destructive_input`
3474        // cleanup via the snapshot taken at the top of this function
3475        // (`Op::Move::destructive_input() == Some(0)`). Ordering
3476        // safety (a Move must not strand a sibling consumer of its
3477        // source) is `execution_plan`/`derive_ordering`'s job — the
3478        // Move is pinned after every non-destructive reader of the
3479        // source's alias set before any work item is emitted.
3480        if inputs.len() != 1 {
3481            return Err(
3482                Error::Msg(format!("Op::Move expects 1 input, got {}", inputs.len(),)).bt(),
3483            );
3484        }
3485        let target_backend = graph.target_backend(id).ok_or_else(|| {
3486            Error::Msg(format!(
3487                "PipelinedExecutor: Op::Move node {:?} has no target_backend \
3488                 set (= source backend, the one whose kernel runs the \
3489                 transfer)",
3490                id
3491            ))
3492            .bt()
3493        })?;
3494        let op_params = OpParams::None;
3495        let dtypes = build_lookup_dtypes(graph, node);
3496        let compiled = resolve_compiled(
3497            graph,
3498            node,
3499            OpKind::Copy,
3500            &dtypes,
3501            target_backend,
3502            op_params,
3503            bindings,
3504        )?;
3505        // Output layout: contiguous in the node's shape, same as
3506        // Op::Copy (the transfer materializes strided sources via
3507        // auto-contiguize on the input side).
3508        let output_layout = Layout::contiguous(node.shape.clone());
3509        layout_cache.insert(id, output_layout.clone());
3510        return Ok(WorkItem {
3511            node_id: id,
3512            inputs,
3513            elem_count,
3514            dtype: node.dtype,
3515            target_backend,
3516            kind: WorkItemKind::Move {
3517                target_location: target,
3518            },
3519            compiled: Some(compiled),
3520            output_layout,
3521            destructive_input,
3522            output_bundle: None,
3523        });
3524    }
3525
3526    if matches!(node.op, Op::Reshape(_)) {
3527        if inputs.len() != 1 {
3528            return Err(
3529                Error::Msg(format!("Op::Reshape expects 1 input, got {}", inputs.len(),)).bt(),
3530            );
3531        }
3532        let input_layout = graph.layout(inputs[0]);
3533        // Output is contiguous in the new shape — bytes per element
3534        // are unchanged, so a contiguous input flows through with
3535        // zero copy. A non-contiguous input is auto-contiguized at
3536        // execute time and the result is naturally contiguous.
3537        let output_layout = Layout::contiguous(node.shape.clone());
3538        layout_cache.insert(id, output_layout.clone());
3539        let target_backend = graph
3540            .target_backend(id)
3541            .or_else(|| graph.target_backend(inputs[0]))
3542            .unwrap_or(BackendId::Cpu);
3543        // Sanity: same total element count.
3544        let in_elem_count = input_layout.shape().elem_count();
3545        if in_elem_count != elem_count {
3546            return Err(Error::Msg(format!(
3547                "Op::Reshape changes element count: input {} → output {}",
3548                in_elem_count, elem_count,
3549            ))
3550            .bt());
3551        }
3552        return Ok(WorkItem {
3553            node_id: id,
3554            inputs,
3555            elem_count,
3556            dtype: node.dtype,
3557            target_backend,
3558            kind: WorkItemKind::ContiguizeOf {
3559                input: node.inputs[0],
3560            },
3561            compiled: None,
3562            output_layout,
3563            destructive_input,
3564            output_bundle: None,
3565        });
3566    }
3567
3568    if matches!(node.op, Op::Contiguize) {
3569        // Op::Contiguize: same execute-time path as Reshape, but
3570        // output shape == input shape so there's no element-count
3571        // check. Zero-copy when input is already contiguous +
3572        // zero-offset (the ContiguizeOf arm in execute_work_item
3573        // adopts the input Arc); otherwise auto_contiguize allocates
3574        // a fresh contiguous Storage on the input's backend.
3575        if inputs.len() != 1 {
3576            return Err(Error::Msg(format!(
3577                "Op::Contiguize expects 1 input, got {}",
3578                inputs.len(),
3579            ))
3580            .bt());
3581        }
3582        let output_layout = Layout::contiguous(node.shape.clone());
3583        layout_cache.insert(id, output_layout.clone());
3584        let target_backend = graph
3585            .target_backend(id)
3586            .or_else(|| graph.target_backend(inputs[0]))
3587            .unwrap_or(BackendId::Cpu);
3588        return Ok(WorkItem {
3589            node_id: id,
3590            inputs,
3591            elem_count,
3592            dtype: node.dtype,
3593            target_backend,
3594            kind: WorkItemKind::ContiguizeOf {
3595                input: node.inputs[0],
3596            },
3597            compiled: None,
3598            output_layout,
3599            destructive_input,
3600            output_bundle: None,
3601        });
3602    }
3603
3604    // Runtime fused op — a JIT-adopted (Tier-2) kernel. `Op::Fused(fid, _)`
3605    // with `fid.is_runtime()` has no `OpKind` (the op was synthesized after
3606    // startup): its kernel resolves from the SAME binding table as every
3607    // static kernel, under `BindingKey::RuntimeFused(fid)` — the dtype tuple
3608    // is the key, so an absent kernel AND a dtype mismatch are one honest
3609    // `NoBackendForOp` miss. A deterministic *lookup*, not a decision: the
3610    // optimizer's gate emitted the arm only when this kernel was bound, and
3611    // pinned `target_backend` (`runtime-fused-op-registration.md` §6). The
3612    // guards are invariant checks, never live fallbacks.
3613    if let Op::Fused(fid, _) = &node.op
3614        && fid.is_runtime()
3615    {
3616        let target_backend = graph.target_backend(id).ok_or_else(|| {
3617            Error::Msg(format!(
3618                "PipelinedExecutor: runtime fused op {:?} (node {:?}) has no \
3619                     target_backend — the arm emitter pins it at emission",
3620                fid, id,
3621            ))
3622            .bt()
3623        })?;
3624        // v1: single-output only. Reject a multi-output bundle explicitly
3625        // rather than silently dropping it.
3626        if graph.output_views_arc(id).is_some() {
3627            return Err(Error::Msg(format!(
3628                "PipelinedExecutor: runtime fused op {:?} (node {:?}) carries a \
3629                     multi-output bundle — synthesized kernels are single-output in v1",
3630                fid, id,
3631            ))
3632            .bt());
3633        }
3634        let dtypes = build_lookup_dtypes(graph, node);
3635        let (kernel, caps) = bindings.lookup_with_caps(
3636            crate::kernel::BindingKey::RuntimeFused(*fid),
3637            &dtypes,
3638            target_backend,
3639        )?;
3640        let output_layout = Layout::contiguous(node.shape.clone());
3641        layout_cache.insert(id, output_layout.clone());
3642        // Deliberate, not a fallthrough to `op_to_op_params` (which doesn't
3643        // know runtime ops): the node's `Runtime { scalars }` — the live
3644        // `extract:` values, pattern pre-order — becomes `JitScalars` (the
3645        // launch appends them as the kernel's trailing `p{i}` args); a
3646        // param-free op carries `None` (its launch is layout-driven:
3647        // pointers + element count).
3648        let op_params = match &node.op {
3649            Op::Fused(_, FusedOpParams::Runtime { scalars }) if !scalars.is_empty() => {
3650                OpParams::JitScalars {
3651                    scalars: scalars.clone(),
3652                }
3653            }
3654            _ => OpParams::None,
3655        };
3656        let compiled = CompiledNode {
3657            op: OpKind::RuntimeFused,
3658            dtypes: KernelDTypes::from_slice(&dtypes),
3659            backend: target_backend,
3660            kernel,
3661            caps,
3662            op_params,
3663            est_ns: 0,
3664        };
3665        return Ok(WorkItem {
3666            node_id: id,
3667            inputs,
3668            elem_count,
3669            dtype: node.dtype,
3670            target_backend,
3671            kind: WorkItemKind::Kernel,
3672            compiled: Some(compiled),
3673            output_layout,
3674            destructive_input,
3675            output_bundle: None,
3676        });
3677    }
3678
3679    let target_backend = graph.target_backend(id).ok_or_else(|| {
3680        Error::Msg(format!(
3681            "PipelinedExecutor: node {:?} ({:?}) has no target_backend set",
3682            id, node.op
3683        ))
3684        .bt()
3685    })?;
3686
3687    let op_kind = op_to_op_kind(&node.op).ok_or_else(|| {
3688        Error::Msg(format!(
3689            "PipelinedExecutor: op {:?} not yet mapped to an OpKind \
3690             (Phase C migrates more ops as they're registered)",
3691            node.op,
3692        ))
3693        .bt()
3694    })?;
3695
3696    let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3697    // Build the per-operand dtype list for the binding-table lookup —
3698    // inputs in order, then outputs. Variadic uniform-dtype ops
3699    // (Concat) collapse to the canonical `[T_in, T_out]` shorthand to
3700    // match how registrations index them.
3701    let dtypes = build_lookup_dtypes(graph, node);
3702    let compiled = resolve_compiled(
3703        graph,
3704        node,
3705        op_kind,
3706        &dtypes,
3707        target_backend,
3708        op_params,
3709        bindings,
3710    )?;
3711    let output_layout = Layout::contiguous(node.shape.clone());
3712    layout_cache.insert(id, output_layout.clone());
3713    // Multi-output: snapshot the producer's bundle metadata. When
3714    // `Some(_)`, the Kernel arm allocates a single Storage sized to
3715    // fit every slot and attaches the bundle via
3716    // `Storage::with_bundle` so downstream Op::View/Op::ViewOwned
3717    // resolve correctly.
3718    let output_bundle = graph.output_views_arc(id);
3719    Ok(WorkItem {
3720        node_id: id,
3721        inputs,
3722        elem_count,
3723        dtype: node.dtype,
3724        target_backend,
3725        kind: WorkItemKind::Kernel,
3726        compiled: Some(compiled),
3727        output_layout,
3728        destructive_input,
3729        output_bundle,
3730    })
3731}
3732
3733/// Build the per-operand dtype list used as the binding-table lookup
3734/// key. Inputs in order, then the output. Variadic-uniform ops
3735/// (Concat) collapse to the canonical `[T_in, T_out]` shorthand to
3736/// match how those wrappers are registered (otherwise an N-way concat
3737/// would need N+1 distinct registrations per dtype).
3738///
3739/// `pub(crate)` — `crate::plan::compile_plan` (step 9b) reuses this
3740/// to key the route picker's binding-table lookup the same way the
3741/// pipelined path does.
3742pub(crate) fn build_lookup_dtypes(graph: &Graph, node: &Node) -> Vec<DType> {
3743    if matches!(node.op, Op::Concat { .. }) {
3744        // Concat: all inputs share node.dtype by construction.
3745        let in_dt = node
3746            .inputs
3747            .first()
3748            .map(|&id| graph.node(id).dtype)
3749            .unwrap_or(node.dtype);
3750        return vec![in_dt, node.dtype];
3751    }
3752    if matches!(node.op, Op::WriteSlice { .. }) {
3753        // WriteSlice: the destination (inputs[0]) is exposed to the
3754        // executor as the OUTPUT slot (in-place adoption), not as an
3755        // input the kernel reads. Canonicalize the binding-table key
3756        // to `[T_source, T_out]` so registrations match the kernel's
3757        // actual surface (one input slab + one output buffer).
3758        let src_dt = node
3759            .inputs
3760            .get(1)
3761            .map(|&id| graph.node(id).dtype)
3762            .unwrap_or(node.dtype);
3763        return vec![src_dt, node.dtype];
3764    }
3765    if matches!(node.op, Op::WriteSliceRotating { .. }) {
3766        // Same canonicalization as WriteSlice: dest = output slot;
3767        // position (inputs[2]) is read by the kernel via the
3768        // position-input parameter, not the binding-table key.
3769        let src_dt = node
3770            .inputs
3771            .get(1)
3772            .map(|&id| graph.node(id).dtype)
3773            .unwrap_or(node.dtype);
3774        return vec![src_dt, node.dtype];
3775    }
3776    if matches!(node.op, Op::WriteSliceDoff { .. }) {
3777        // Same canonicalization as WriteSlice: dest = output slot;
3778        // offset (inputs[2], I64) is a non-key runtime operand read by
3779        // the kernel via its device pointer, not the binding-table key.
3780        let src_dt = node
3781            .inputs
3782            .get(1)
3783            .map(|&id| graph.node(id).dtype)
3784            .unwrap_or(node.dtype);
3785        return vec![src_dt, node.dtype];
3786    }
3787    let mut dts: Vec<DType> = node.inputs.iter().map(|&id| graph.node(id).dtype).collect();
3788    dts.push(node.dtype);
3789    dts
3790}
3791
3792/// SoftmaxLastDim is reachable only through `Op::Fused(FusedOps::
3793/// SOFTMAX_LAST_DIM, _)` post-step-5 (the legacy `Op::SoftmaxLastDim`
3794/// primitive variant was retired). This helper collapses the
3795/// op-to-OpKind/OpParams shapes for callers that want a single-arm
3796/// match.
3797fn op_is_softmax_last_dim(op: &Op) -> bool {
3798    matches!(op, Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM)
3799}
3800
3801/// FusedLinear is reachable only through `Op::Fused(FusedOps::
3802/// FUSED_LINEAR, _)` post-step-5.
3803fn op_is_fused_linear(op: &Op) -> bool {
3804    matches!(op, Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::FUSED_LINEAR)
3805}
3806
3807/// RowScaledMatMul (row 172 item 1): `(a @ b) * row_scale`, reached only through
3808/// `Op::Fused(FusedOps::ROW_SCALED_MATMUL, _)`. Shares FusedLinear's
3809/// `OpParams::Matmul` params; its third input is the `[..., M, 1]` row scale.
3810fn op_is_row_scaled_matmul(op: &Op) -> bool {
3811    matches!(op, Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::ROW_SCALED_MATMUL)
3812}
3813
3814/// Does the executor have an arm that runs `op` on `backend`? Only for ops it dispatches DIRECTLY
3815/// (no binding-table kernel, so the planner cannot reject them for lack of a binding). `None` means
3816/// the op is not direct-dispatched and this answer does not apply (the binding table decides).
3817///
3818/// Source of truth for [`check_direct_arms_wired`]; keep in step with the `execute_work_item` arms.
3819pub(crate) fn direct_arm_wired(op: &Op, backend: BackendId) -> Option<bool> {
3820    match op {
3821        // CPU generates it; CUDA generates on the host and uploads (GAP-380 a2). The cuda arm is
3822        // compiled only with the `cuda` feature, and a CUDA stamp cannot arise without it.
3823        Op::Iota { .. } => Some(
3824            backend == BackendId::Cpu || (cfg!(feature = "cuda") && backend == BackendId::Cuda),
3825        ),
3826        _ => None,
3827    }
3828}
3829
3830/// Plan-time guard (PM, 2026-11-12): a node stamped for a backend whose executor has no arm for its
3831/// op fails HERE, with the node and op named, instead of as an `Err` inside the executor mid-run.
3832/// Run after the backend stamp. A graph with every arm wired is a no-op.
3833pub(crate) fn check_direct_arms_wired(graph: &Graph, roots: &[NodeId]) -> Result<()> {
3834    for id in fuel_graph::topo_order_multi(graph, roots) {
3835        let node = graph.node(id);
3836        let backend = graph.target_backend(id).unwrap_or(BackendId::Cpu);
3837        if direct_arm_wired(&node.op, backend) == Some(false) {
3838            return Err(Error::Msg(format!(
3839                "plan: Node#{} ({:?}, out shape={:?} dtype={:?}) is placed on {backend:?} but the executor                  has no {backend:?} arm for this op (wired arms: see pipelined::direct_arm_wired)",
3840                id.0,
3841                node.op,
3842                node.shape,
3843                node.dtype,
3844            ))
3845            .bt());
3846        }
3847    }
3848    Ok(())
3849}
3850
3851/// Map a `fuel_graph::Op` to a `fuel_ir::dispatch::OpKind`.
3852/// Returns `None` for ops that haven't been wired into the new
3853/// dispatch path yet — Phase C extends this as op families migrate.
3854///
3855/// `pub(crate)` — `crate::plan::compile_plan` (step 9b) reuses this
3856/// to skip nodes the binding-table doesn't index (view ops,
3857/// `Op::Const`, not-yet-migrated ops) when building bindings.
3858pub(crate) fn op_to_op_kind(op: &Op) -> Option<OpKind> {
3859    match op {
3860        Op::Add => Some(OpKind::AddElementwise),
3861        Op::Sub => Some(OpKind::SubElementwise),
3862        Op::Mul => Some(OpKind::MulElementwise),
3863        Op::Div => Some(OpKind::DivElementwise),
3864        Op::Relu => Some(OpKind::ReluElementwise),
3865        Op::Neg => Some(OpKind::NegElementwise),
3866        Op::Sqr => Some(OpKind::SqrElementwise),
3867        Op::Sqrt => Some(OpKind::SqrtElementwise),
3868        Op::Tanh => Some(OpKind::TanhElementwise),
3869        Op::Exp => Some(OpKind::ExpElementwise),
3870        Op::Log => Some(OpKind::LogElementwise),
3871        Op::Sin => Some(OpKind::SinElementwise),
3872        Op::Cos => Some(OpKind::CosElementwise),
3873        Op::Sigmoid => Some(OpKind::SigmoidElementwise),
3874        Op::Silu => Some(OpKind::SiluElementwise),
3875        Op::GeluTanh => Some(OpKind::GeluTanhElementwise),
3876        Op::Step => Some(OpKind::StepElementwise),
3877        Op::Recip => Some(OpKind::RecipElementwise),
3878        Op::Abs => Some(OpKind::AbsElementwise),
3879        Op::Equal => Some(OpKind::EqualElementwise),
3880        Op::Ne => Some(OpKind::NotEqualElementwise),
3881        Op::Lt => Some(OpKind::LessElementwise),
3882        Op::Le => Some(OpKind::LessEqualElementwise),
3883        Op::Gt => Some(OpKind::GreaterElementwise),
3884        Op::Ge => Some(OpKind::GreaterEqualElementwise),
3885        Op::Where => Some(OpKind::Where),
3886        Op::Floor => Some(OpKind::FloorElementwise),
3887        Op::Ceil => Some(OpKind::CeilElementwise),
3888        Op::Round => Some(OpKind::RoundElementwise),
3889        Op::Sign => Some(OpKind::SignElementwise),
3890        Op::Erf => Some(OpKind::ErfElementwise),
3891        Op::Gelu => Some(OpKind::GeluElementwise),
3892        Op::Pow => Some(OpKind::PowElementwise),
3893        Op::Rsqrt => Some(OpKind::RsqrtElementwise),
3894        Op::Rem => Some(OpKind::RemElementwise),
3895        Op::Flip { .. } => Some(OpKind::Flip),
3896        Op::Roll { .. } => Some(OpKind::Roll),
3897        Op::CumSum { .. } => Some(OpKind::CumSum),
3898        Op::Triu { .. } => Some(OpKind::Triu),
3899        Op::Tril { .. } => Some(OpKind::Tril),
3900        Op::LogSoftmaxLastDim => Some(OpKind::LogSoftmaxLastDim),
3901        Op::LogSoftmaxLastDimBackward => Some(OpKind::LogSoftmaxLastDimBackward),
3902        Op::MaskedFill { .. } => Some(OpKind::MaskedFill),
3903        Op::Pad { .. } => Some(OpKind::Pad),
3904        Op::PadBackward { .. } => Some(OpKind::PadBackward),
3905        Op::SumDim(_) => Some(OpKind::SumReduce),
3906        Op::MaxDim(_) => Some(OpKind::MaxReduce),
3907        Op::MinDim(_) => Some(OpKind::MinReduce),
3908        Op::MeanDim(_) => Some(OpKind::MeanReduce),
3909        Op::SumAll => Some(OpKind::SumReduce),
3910        Op::MaxAll => Some(OpKind::MaxReduce),
3911        Op::MinAll => Some(OpKind::MinReduce),
3912        Op::MeanAll => Some(OpKind::MeanReduce),
3913        Op::MatMul => Some(OpKind::MatMul),
3914        Op::Cast(_) => Some(OpKind::Cast),
3915        // Phase 7.6 step 5: fused-op dispatch routes through
3916        // `Op::Fused(fid, _)`; the legacy `Op::Conv2D` /
3917        // `Op::FusedLinear` / `Op::SoftmaxLastDim` /
3918        // `Op::RmsNormLastDim` / `Op::LayerNormLastDim` / `Op::Rope`
3919        // arms were dropped together with the variants.
3920        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::CONV2D => Some(OpKind::Conv2D),
3921        // Phase 7.6 step 5 (final): legacy `Op::ConvTranspose2D` /
3922        // `Op::FlashAttn` / `Op::PagedAttn` arms dropped with the
3923        // variants; dispatch flows only through `Op::Fused`.
3924        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D => {
3925            Some(OpKind::ConvTranspose2D)
3926        }
3927        Op::ReduceSumTo(_) => Some(OpKind::ReduceSumTo),
3928        Op::ReduceMaxTo(_) => Some(OpKind::ReduceMaxTo),
3929        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::FLASH_ATTN => {
3930            Some(OpKind::FlashAttn)
3931        }
3932        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::PAGED_ATTN => {
3933            Some(OpKind::PagedAttn)
3934        }
3935        Op::AddScalar(_) => Some(OpKind::Affine),
3936        Op::MulScalar(_) => Some(OpKind::Affine),
3937        Op::Clamp { .. } => Some(OpKind::ClampElementwise),
3938        Op::PowI(_) => Some(OpKind::PowIElementwise),
3939        Op::Maximum => Some(OpKind::MaximumElementwise),
3940        Op::Minimum => Some(OpKind::MinimumElementwise),
3941        Op::Concat { .. } => Some(OpKind::Concat),
3942        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM => {
3943            Some(OpKind::SoftmaxLastDim)
3944        }
3945        // Phase 7.6 step 6 follow-up: backward helpers now route
3946        // through the byte-level binding table too.
3947        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM_BACKWARD => {
3948            Some(OpKind::SoftmaxLastDimBackward)
3949        }
3950        Op::Fused(fid, _)
3951            if *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM_BACKWARD =>
3952        {
3953            Some(OpKind::LayerNormLastDimBackward)
3954        }
3955        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM_BACKWARD => {
3956            Some(OpKind::RmsNormLastDimBackward)
3957        }
3958        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::REDUCE_MAX_TO_BACKWARD => {
3959            Some(OpKind::ReduceMaxToBackward)
3960        }
3961        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::POWI_BACKWARD => {
3962            Some(OpKind::PowIElementwiseBackward)
3963        }
3964        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::FUSED_LINEAR => {
3965            Some(OpKind::FusedLinear)
3966        }
3967        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::ROW_SCALED_MATMUL => {
3968            Some(OpKind::RowScaledMatMul)
3969        }
3970        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::TOP_K_LAST_DIM => {
3971            Some(OpKind::TopKLastDim)
3972        }
3973        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::MATMUL_TOP_K => {
3974            Some(OpKind::MatMulTopK)
3975        }
3976        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM => {
3977            Some(OpKind::RmsNormLastDim)
3978        }
3979        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM => {
3980            Some(OpKind::LayerNormLastDim)
3981        }
3982        Op::IndexSelect { .. } => Some(OpKind::IndexSelect),
3983        Op::Gather { .. } => Some(OpKind::Gather),
3984        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::ROPE => Some(OpKind::Rope),
3985        Op::IndexAdd { .. } => Some(OpKind::IndexAdd),
3986        Op::ScatterAdd { .. } => Some(OpKind::ScatterAdd),
3987        Op::NonZeroIndices { .. } => Some(OpKind::NonZeroIndices),
3988        Op::ArgMaxDim(_) => Some(OpKind::ArgMaxDim),
3989        Op::ArgMinDim(_) => Some(OpKind::ArgMinDim),
3990        // Phase 7.6 step 5 (final): legacy `Op::QMatMul` arm dropped.
3991        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::QMATMUL => {
3992            Some(OpKind::QMatMul)
3993        }
3994        Op::WriteSlice { .. } => Some(OpKind::WriteSlice),
3995        Op::WriteSliceRotating { .. } => Some(OpKind::WriteSliceRotating),
3996        Op::WriteSliceDoff { .. } => Some(OpKind::WriteSliceDoff),
3997        // Phase 2 of bridge-retirement (post-9c): Op::Copy dispatches
3998        // through the binding table at OpKind::Copy. The BackendId
3999        // axis encodes the source backend (the kernel runs there —
4000        // download from local memory). The executor handles output
4001        // allocation on the target via a dedicated WorkItemKind::Copy
4002        // arm, since target_location differs from target_backend for
4003        // this op (the only one with that property today).
4004        Op::Copy { .. } => Some(OpKind::Copy),
4005        // Op::Move dispatches the same data-movement kernel as
4006        // Op::Copy — the destructive release of the source is
4007        // realize-loop bookkeeping (`destructive_input` cleanup), not
4008        // a kernel. Same OpKind, same source-backend key convention.
4009        // `compile_plan` skips both (residency-determined, not a
4010        // picker decision).
4011        Op::Move { .. } => Some(OpKind::Copy),
4012        // Phase 3 of the in-place ops infrastructure: each in-place Op
4013        // variant maps to its OpKind so the binding-table dispatch can
4014        // resolve a kernel. The executor's dedicated WorkItemKind
4015        // arms (added alongside) handle the storage-Arc adoption.
4016        Op::ReluInplace => Some(OpKind::ReluInplace),
4017        Op::SiluInplace => Some(OpKind::SiluInplace),
4018        Op::GeluTanhInplace => Some(OpKind::GeluTanhInplace),
4019        Op::TanhInplace => Some(OpKind::TanhInplace),
4020        Op::SigmoidInplace => Some(OpKind::SigmoidInplace),
4021        Op::NegInplace => Some(OpKind::NegInplace),
4022        Op::AbsInplace => Some(OpKind::AbsInplace),
4023        Op::SqrInplace => Some(OpKind::SqrInplace),
4024        Op::SqrtInplace => Some(OpKind::SqrtInplace),
4025        Op::RsqrtInplace => Some(OpKind::RsqrtInplace),
4026        Op::RecipInplace => Some(OpKind::RecipInplace),
4027        Op::ExpInplace => Some(OpKind::ExpInplace),
4028        Op::LogInplace => Some(OpKind::LogInplace),
4029        Op::SinInplace => Some(OpKind::SinInplace),
4030        Op::CosInplace => Some(OpKind::CosInplace),
4031        Op::SignInplace => Some(OpKind::SignInplace),
4032        Op::FloorInplace => Some(OpKind::FloorInplace),
4033        Op::CeilInplace => Some(OpKind::CeilInplace),
4034        Op::RoundInplace => Some(OpKind::RoundInplace),
4035        Op::ErfInplace => Some(OpKind::ErfInplace),
4036        Op::GeluInplace => Some(OpKind::GeluInplace),
4037        Op::ClampInplace { .. } => Some(OpKind::ClampInplace),
4038        Op::PowIInplace(_) => Some(OpKind::PowIInplace),
4039        // In-place binary variants (Add/Sub/Mul/Div/MaskedFill) and
4040        // their OpKind siblings are tracked by a parallel session and
4041        // toggle in and out of the Op enum as that work progresses.
4042        // No multi-output arm references them; nothing to map here in
4043        // the current HEAD.
4044        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::INPLACE_AFFINE => {
4045            Some(OpKind::InplaceAffine)
4046        }
4047        Op::Fused(fid, _)
4048            if *fid == fuel_graph::registry::FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY =>
4049        {
4050            Some(OpKind::FusedSoftmaxCrossEntropy)
4051        }
4052        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::CAUSAL_CONV1D => {
4053            Some(OpKind::CausalConv1d)
4054        }
4055        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SELECTIVE_SCAN => {
4056            Some(OpKind::SelectiveScan)
4057        }
4058        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SSD_CHUNK_SCAN => {
4059            Some(OpKind::SsdChunkScan)
4060        }
4061        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::NF4_MATMUL => {
4062            Some(OpKind::Nf4Matmul)
4063        }
4064        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::AWQ_MATMUL => {
4065            Some(OpKind::AwqMatmul)
4066        }
4067        // Phase 3a (post-9c): Op::Alloc + Op::ZeroFill are structural
4068        // ops dispatched directly via `WorkItemKind::Alloc` /
4069        // `WorkItemKind::ZeroFill` (no binding-table lookup).
4070        // `compile_plan` skips these.
4071        Op::Alloc { .. } | Op::ZeroFill => None,
4072        _ => None,
4073    }
4074}
4075
4076/// Build the [`OpParams`] for `node`'s op. Most ops use
4077/// `OpParams::None`; reductions / matmul / conv / slice carry their
4078/// op-specific extras here. The graph is consulted to read input
4079/// shapes (e.g. reductions need the input shape to walk the
4080/// multi-index — Storage only carries bytes + dtype).
4081///
4082/// Phase C — extends as op families migrate. Returns Err if a
4083/// graph-shape lookup fails (currently can't, but the signature is
4084/// `Result` so future cases needing validation slot in cleanly).
4085/// Encode an `f64` value into the byte pattern of `dtype`. Used by
4086/// `Op::Pad` (Constant mode) to pre-convert the fill value once at
4087/// op_params time, so the kernel itself stays dtype-agnostic.
4088fn encode_value_to_bytes(dtype: DType, value: f64) -> Result<Vec<u8>> {
4089    match dtype {
4090        DType::F32 => Ok((value as f32).to_le_bytes().to_vec()),
4091        DType::F64 => Ok(value.to_le_bytes().to_vec()),
4092        DType::BF16 => Ok(half::bf16::from_f32(value as f32).to_le_bytes().to_vec()),
4093        DType::F16 => Ok(half::f16::from_f32(value as f32).to_le_bytes().to_vec()),
4094        DType::U8 => Ok(vec![value as u8]),
4095        DType::U32 => Ok((value as u32).to_le_bytes().to_vec()),
4096        other => Err(Error::Msg(format!(
4097            "encode_value_to_bytes: dtype {other:?} not yet supported for Pad fill",
4098        ))
4099        .bt()),
4100    }
4101}
4102
4103/// Encode a typed `Scalar` to its little-endian byte representation.
4104/// Used by Op::MaskedFill so the kernel only sees bytes — never has
4105/// to know the value's dtype.
4106fn scalar_to_bytes(s: fuel_ir::Scalar) -> Vec<u8> {
4107    use fuel_ir::Scalar;
4108    match s {
4109        Scalar::U8(v) => vec![v],
4110        Scalar::I8(v) => vec![v as u8],
4111        Scalar::U32(v) => v.to_le_bytes().to_vec(),
4112        Scalar::I16(v) => v.to_le_bytes().to_vec(),
4113        Scalar::I32(v) => v.to_le_bytes().to_vec(),
4114        Scalar::I64(v) => v.to_le_bytes().to_vec(),
4115        Scalar::BF16(v) => v.to_le_bytes().to_vec(),
4116        Scalar::F16(v) => v.to_le_bytes().to_vec(),
4117        Scalar::F32(v) => v.to_le_bytes().to_vec(),
4118        Scalar::F64(v) => v.to_le_bytes().to_vec(),
4119        Scalar::Bool(b) => vec![b as u8],
4120        Scalar::F8E4M3(v) => vec![v.to_bits()],
4121        Scalar::F8E5M2(v) => vec![v.to_bits()],
4122        // OCP-MX E8M0 block scale is a raw byte on the wire (`2^(X-127)`,
4123        // decoded kernel-side); a single byte is its own LE encoding.
4124        Scalar::F8E8M0(v) => vec![v],
4125    }
4126}
4127
4128fn op_to_op_params(
4129    graph: &Graph,
4130    node: &Node,
4131    node_id: NodeId,
4132    layout_cache: &HashMap<NodeId, Layout>,
4133    sym_env: &SymEnv,
4134) -> Result<OpParams> {
4135    // Helper: read an input's layout from the compiler-thread-local
4136    // cache (which is current within the realize call), falling back
4137    // to the graph's side-table if the input wasn't visited (which
4138    // shouldn't happen in topo order, but the fallback keeps the
4139    // path safe).
4140    let input_layout = |input_id: NodeId| -> Layout {
4141        layout_cache
4142            .get(&input_id)
4143            .cloned()
4144            .unwrap_or_else(|| graph.layout(input_id))
4145    };
4146    Ok(match &node.op {
4147        // Phase 7.6 step 5 (final): legacy `Op::QMatMul` arm dropped.
4148        Op::Fused(_, fuel_graph::registry::FusedOpParams::QMatMul { quant_type, k, n }) => {
4149            // Inputs: (activations f32 [..., m, k], weight_bytes
4150            // u32-typed). Output shape (this Node's shape) is
4151            // [..., m, n]. Flatten leading dims into batch_count.
4152            if node.inputs.len() != 2 {
4153                return Err(Error::Msg(format!(
4154                    "Op::QMatMul expects 2 inputs (activations, weight_bytes), got {}",
4155                    node.inputs.len(),
4156                ))
4157                .bt());
4158            }
4159            let act_layout = input_layout(node.inputs[0]);
4160            let act_dims = act_layout.shape().dims();
4161            if act_dims.len() < 2 {
4162                return Err(Error::Msg(format!(
4163                    "Op::QMatMul: activations must be rank ≥ 2, got {act_dims:?}",
4164                ))
4165                .bt());
4166            }
4167            let m = act_dims[act_dims.len() - 2];
4168            let k_act = act_dims[act_dims.len() - 1];
4169            if k_act != *k {
4170                return Err(Error::Msg(format!(
4171                    "Op::QMatMul: activation last dim ({k_act}) must equal Op's k ({k})",
4172                ))
4173                .bt());
4174            }
4175            let batch_count: usize = act_dims[..act_dims.len() - 2].iter().product();
4176            OpParams::QMatMul {
4177                quant_type: *quant_type,
4178                batch_count,
4179                m,
4180                n: *n,
4181                k: *k,
4182            }
4183        }
4184        Op::ArgMaxDim(d) | Op::ArgMinDim(d) => {
4185            // Reuse OpParams::Reduce — same shape contract; the
4186            // single reduce dim is the argmax/argmin axis. Input
4187            // layout flows through KernelRef's `layouts[0]`.
4188            OpParams::Reduce {
4189                dims: vec![*d],
4190                keepdim: false,
4191            }
4192        }
4193        Op::SumDim(d) | Op::MaxDim(d) | Op::MinDim(d) | Op::MeanDim(d) => OpParams::Reduce {
4194            dims: vec![*d],
4195            keepdim: false,
4196        },
4197        Op::SumAll | Op::MaxAll | Op::MinAll | Op::MeanAll => {
4198            let il = input_layout(node.inputs[0]);
4199            let rank = il.shape().rank();
4200            OpParams::Reduce {
4201                dims: (0..rank).collect(),
4202                keepdim: false,
4203            }
4204        }
4205        Op::MatMul => {
4206            // Batched matmul: lhs `[..lhs_batch.., m, k]` @
4207            // rhs `[..rhs_batch.., k, n]` → out `[..lhs_batch.., m, n]`.
4208            // Per-axis the batch dims either match or follow GQA-style
4209            // divisibility (lhs_dim > rhs_dim && lhs_dim % rhs_dim == 0);
4210            // the kernel honors the latter via `rhs_idx = lhs_idx / n_rep`.
4211            if node.inputs.len() != 2 {
4212                return Err(Error::Msg(format!(
4213                    "Op::MatMul expects 2 inputs, got {}",
4214                    node.inputs.len(),
4215                ))
4216                .bt());
4217            }
4218            let lhs = input_layout(node.inputs[0]);
4219            let rhs = input_layout(node.inputs[1]);
4220            let lhs_dims = lhs.shape().dims();
4221            let rhs_dims = rhs.shape().dims();
4222            if lhs_dims.len() < 2 || rhs_dims.len() < 2 {
4223                return Err(Error::Msg(format!(
4224                    "Op::MatMul requires both inputs rank ≥ 2; got lhs={:?} rhs={:?}",
4225                    lhs_dims, rhs_dims,
4226                ))
4227                .bt());
4228            }
4229            if lhs_dims.len() != rhs_dims.len() {
4230                return Err(Error::Msg(format!(
4231                    "Op::MatMul: ranks must match (auto-broadcast happens at \
4232                     graph construction time); got lhs rank {} vs rhs rank {}",
4233                    lhs_dims.len(),
4234                    rhs_dims.len(),
4235                ))
4236                .bt());
4237            }
4238            let rank = lhs_dims.len();
4239            let batch_rank = rank - 2;
4240            // Per-axis validation: equal or GQA-divisible.
4241            for i in 0..batch_rank {
4242                let la = lhs_dims[i];
4243                let ra = rhs_dims[i];
4244                let ok = la == ra || (ra > 0 && la > ra && la % ra == 0);
4245                if !ok {
4246                    return Err(Error::Msg(format!(
4247                        "Op::MatMul: batch dim {i} disallowed combination \
4248                         (lhs={la}, rhs={ra}); must be equal or \
4249                         GQA-divisible (lhs > rhs && lhs % rhs == 0)",
4250                    ))
4251                    .bt());
4252                }
4253            }
4254            let lhs_batch_dims: Vec<usize> = lhs_dims[..batch_rank].to_vec();
4255            let rhs_batch_dims: Vec<usize> = rhs_dims[..batch_rank].to_vec();
4256            let (m, k_lhs) = (lhs_dims[rank - 2], lhs_dims[rank - 1]);
4257            let (k_rhs, n) = (rhs_dims[rank - 2], rhs_dims[rank - 1]);
4258            if k_lhs != k_rhs {
4259                return Err(Error::Msg(format!(
4260                    "Op::MatMul: contracting dims disagree — lhs trailing is \
4261                     [{m}, {k_lhs}], rhs trailing is [{k_rhs}, {n}]",
4262                ))
4263                .bt());
4264            }
4265            // Data-determined-M (sparse-MoE): a side-table row count makes
4266            // `m` the capacity and this the compute count. Dual-path,
4267            // mirroring WriteSlice: resolve in the compile-time SymEnv
4268            // (static / input-determined) now; else DEFER a producer-bound
4269            // sym to execute; else it is a genuine caller error.
4270            let m_compute = match graph.matmul_row_count(node_id) {
4271                None => MatmulM::All,
4272                Some(dyn_m) => match dyn_m.resolve(sym_env) {
4273                    Some(c) => {
4274                        if c > m {
4275                            return Err(Error::Msg(format!(
4276                                "Op::MatMul: resolved row count {c} exceeds capacity {m}",
4277                            ))
4278                            .bt());
4279                        }
4280                        MatmulM::Rows(c)
4281                    }
4282                    None => match dyn_m {
4283                        fuel_ir::DynScalar::Sym(s) if graph.binds_data_determined_sym(s) => {
4284                            MatmulM::Deferred(dyn_m)
4285                        }
4286                        _ => {
4287                            return Err(Error::Msg(format!(
4288                                "Op::MatMul: dynamic row count {dyn_m:?} is unbound in the \
4289                                 SymEnv at compile and no producer binds it (not \
4290                                 data-determined)",
4291                            ))
4292                            .bt());
4293                        }
4294                    },
4295                },
4296            };
4297            OpParams::Matmul {
4298                lhs_batch_dims,
4299                rhs_batch_dims,
4300                m,
4301                n,
4302                k: k_lhs,
4303                m_compute,
4304            }
4305        }
4306        // Phase 7.6 step 4: legacy `Op::FusedLinear` and registry-extended
4307        // `Op::Fused(FUSED_LINEAR, _)` share the same shape contract and
4308        // params encoding (reuses OpParams::Matmul). One body covers both.
4309        op if op_is_fused_linear(op) || op_is_row_scaled_matmul(op) => {
4310            // Inputs: [a, b, bias]. Same shape semantics as MatMul on
4311            // a/b; bias is rank-1 [N] and broadcasts along all leading
4312            // dims. We reuse OpParams::Matmul (kernel reads bias from
4313            // inputs[2] directly).
4314            if node.inputs.len() != 3 {
4315                return Err(Error::Msg(format!(
4316                    "Op::FusedLinear expects 3 inputs (a, b, bias), got {}",
4317                    node.inputs.len(),
4318                ))
4319                .bt());
4320            }
4321            let lhs = input_layout(node.inputs[0]);
4322            let rhs = input_layout(node.inputs[1]);
4323            let bias = input_layout(node.inputs[2]);
4324            let lhs_dims = lhs.shape().dims();
4325            let rhs_dims = rhs.shape().dims();
4326            let bias_dims = bias.shape().dims();
4327            if lhs_dims.len() < 2 || rhs_dims.len() < 2 {
4328                return Err(Error::Msg(format!(
4329                    "Op::FusedLinear requires both a, b rank ≥ 2; got a={:?} b={:?}",
4330                    lhs_dims, rhs_dims,
4331                ))
4332                .bt());
4333            }
4334            if lhs_dims.len() != rhs_dims.len() {
4335                return Err(Error::Msg(format!(
4336                    "Op::FusedLinear: ranks must match (auto-broadcast happens at \
4337                     graph construction time); got a rank {} vs b rank {}",
4338                    lhs_dims.len(),
4339                    rhs_dims.len(),
4340                ))
4341                .bt());
4342            }
4343            let rank = lhs_dims.len();
4344            let batch_rank = rank - 2;
4345            for i in 0..batch_rank {
4346                let la = lhs_dims[i];
4347                let ra = rhs_dims[i];
4348                let ok = la == ra || (ra > 0 && la > ra && la % ra == 0);
4349                if !ok {
4350                    return Err(Error::Msg(format!(
4351                        "Op::FusedLinear: batch dim {i} disallowed (a={la}, b={ra})",
4352                    ))
4353                    .bt());
4354                }
4355            }
4356            let lhs_batch_dims: Vec<usize> = lhs_dims[..batch_rank].to_vec();
4357            let rhs_batch_dims: Vec<usize> = rhs_dims[..batch_rank].to_vec();
4358            let (m, k_lhs) = (lhs_dims[rank - 2], lhs_dims[rank - 1]);
4359            let (k_rhs, n) = (rhs_dims[rank - 2], rhs_dims[rank - 1]);
4360            if k_lhs != k_rhs {
4361                return Err(Error::Msg(format!(
4362                    "Op::FusedLinear: contracting dims disagree — a trailing is \
4363                     [{m}, {k_lhs}], b trailing is [{k_rhs}, {n}]",
4364                ))
4365                .bt());
4366            }
4367            if op_is_row_scaled_matmul(&node.op) {
4368                // The row scale is `[..lhs batch, M, 1]`.
4369                let mut want = lhs_batch_dims.clone();
4370                want.push(m);
4371                want.push(1);
4372                if bias_dims != want.as_slice() {
4373                    return Err(Error::Msg(format!(
4374                        "Op::RowScaledMatMul: row_scale must be {want:?}, got {bias_dims:?}",
4375                    ))
4376                    .bt());
4377                }
4378            } else if bias_dims.len() != 1 || bias_dims[0] != n {
4379                return Err(Error::Msg(format!(
4380                    "Op::FusedLinear: bias must be rank-1 [{n}], got {bias_dims:?}",
4381                ))
4382                .bt());
4383            }
4384            OpParams::Matmul {
4385                lhs_batch_dims,
4386                rhs_batch_dims,
4387                m,
4388                n,
4389                k: k_lhs,
4390                // FusedLinear is always static-M (dense linear layer).
4391                m_compute: MatmulM::All,
4392            }
4393        }
4394        // FusedSoftmaxCrossEntropy: flatten logits `[..., V]` to
4395        // `[n_rows, V]` for the kernel. n_rows is the product of all
4396        // leading dims (≥1 even for rank-1 logits, where targets are
4397        // a scalar). The kernel walks rows internally.
4398        Op::Fused(
4399            _,
4400            fuel_graph::registry::FusedOpParams::FusedSoftmaxCrossEntropy {
4401                reduction,
4402                ignore_index,
4403            },
4404        ) => {
4405            if node.inputs.len() != 2 {
4406                return Err(Error::Msg(format!(
4407                    "FusedSoftmaxCrossEntropy expects 2 inputs (logits, targets), got {}",
4408                    node.inputs.len(),
4409                ))
4410                .bt());
4411            }
4412            let logits_layout = input_layout(node.inputs[0]);
4413            let logits_dims = logits_layout.shape().dims();
4414            if logits_dims.is_empty() {
4415                return Err(Error::Msg(
4416                    "FusedSoftmaxCrossEntropy: logits must have rank ≥ 1".to_string(),
4417                )
4418                .bt());
4419            }
4420            let vocab = *logits_dims.last().unwrap();
4421            let n_rows: usize = logits_dims[..logits_dims.len() - 1]
4422                .iter()
4423                .product::<usize>()
4424                .max(1);
4425            let targets_layout = input_layout(node.inputs[1]);
4426            let target_count: usize = targets_layout
4427                .shape()
4428                .dims()
4429                .iter()
4430                .product::<usize>()
4431                .max(1);
4432            if target_count != n_rows {
4433                return Err(Error::Msg(format!(
4434                    "FusedSoftmaxCrossEntropy: targets element count {target_count} must \
4435                     equal logits row count {n_rows} (logits {logits_dims:?}, targets {:?})",
4436                    targets_layout.shape().dims(),
4437                ))
4438                .bt());
4439            }
4440            OpParams::FusedSoftmaxCrossEntropy {
4441                n_rows,
4442                vocab,
4443                reduction: *reduction,
4444                ignore_index: *ignore_index,
4445            }
4446        }
4447        // CausalConv1d: derive (batch, channels, seq_in, seq_out, kernel)
4448        // from the input layouts. x is `[batch, channels, seq_in]`
4449        // (caller pre-pads with kernel-1 zeros), weight is
4450        // `[channels, 1, kernel]`. seq_out = seq_in - (kernel - 1).
4451        Op::Fused(_, fuel_graph::registry::FusedOpParams::CausalConv1d { use_silu }) => {
4452            if node.inputs.len() != 3 {
4453                return Err(Error::Msg(format!(
4454                    "CausalConv1d expects 3 inputs (x, weight, bias), got {}",
4455                    node.inputs.len(),
4456                ))
4457                .bt());
4458            }
4459            let x_layout = input_layout(node.inputs[0]);
4460            let w_layout = input_layout(node.inputs[1]);
4461            let x_dims = x_layout.shape().dims();
4462            let w_dims = w_layout.shape().dims();
4463            if x_dims.len() != 3 {
4464                return Err(Error::Msg(format!(
4465                    "CausalConv1d: x must be rank 3 [batch, channels, seq+pad], got {x_dims:?}",
4466                ))
4467                .bt());
4468            }
4469            if w_dims.len() != 3 {
4470                return Err(Error::Msg(format!(
4471                    "CausalConv1d: weight must be rank 3 [channels, 1, kernel], got {w_dims:?}",
4472                ))
4473                .bt());
4474            }
4475            let batch = x_dims[0];
4476            let channels = x_dims[1];
4477            let seq_in = x_dims[2];
4478            let kernel = w_dims[2];
4479            if seq_in < kernel - 1 {
4480                return Err(Error::Msg(format!(
4481                    "CausalConv1d: x time dim {seq_in} must be ≥ kernel-1 = {} \
4482                     (caller must pre-pad with kernel-1 zeros)",
4483                    kernel - 1,
4484                ))
4485                .bt());
4486            }
4487            let seq_out = seq_in - (kernel - 1);
4488            OpParams::CausalConv1d {
4489                batch,
4490                channels,
4491                seq_in,
4492                seq_out,
4493                kernel,
4494                use_silu: *use_silu,
4495            }
4496        }
4497        // SelectiveScan: derive (batch, seqlen, dim, dstate) from the
4498        // input layouts. u: [batch, seqlen, dim]; a: [dim, dstate].
4499        Op::Fused(_, fuel_graph::registry::FusedOpParams::SelectiveScan { delta_softplus }) => {
4500            if node.inputs.len() != 5 {
4501                return Err(Error::Msg(format!(
4502                    "SelectiveScan expects 5 inputs (u, delta, a, b, c), got {}",
4503                    node.inputs.len(),
4504                ))
4505                .bt());
4506            }
4507            let u_layout = input_layout(node.inputs[0]);
4508            let a_layout = input_layout(node.inputs[2]);
4509            let u_dims = u_layout.shape().dims();
4510            let a_dims = a_layout.shape().dims();
4511            if u_dims.len() != 3 {
4512                return Err(Error::Msg(format!(
4513                    "SelectiveScan: u must be rank 3 [batch, seqlen, dim], got {u_dims:?}",
4514                ))
4515                .bt());
4516            }
4517            if a_dims.len() != 2 {
4518                return Err(Error::Msg(format!(
4519                    "SelectiveScan: a must be rank 2 [dim, dstate], got {a_dims:?}",
4520                ))
4521                .bt());
4522            }
4523            let batch = u_dims[0];
4524            let seqlen = u_dims[1];
4525            let dim = u_dims[2];
4526            let dstate = a_dims[1];
4527            if a_dims[0] != dim {
4528                return Err(Error::Msg(format!(
4529                    "SelectiveScan: a's first dim {} must equal dim {dim}",
4530                    a_dims[0],
4531                ))
4532                .bt());
4533            }
4534            OpParams::SelectiveScan {
4535                batch,
4536                seqlen,
4537                dim,
4538                dstate,
4539                delta_softplus: *delta_softplus,
4540            }
4541        }
4542        // SsdChunkScan: derive (batch, seqlen, heads, head_dim,
4543        // state_dim) from x and b layouts. x: [batch, seqlen, heads,
4544        // head_dim]; b: [batch, seqlen, heads, state_dim].
4545        Op::Fused(_, fuel_graph::registry::FusedOpParams::SsdChunkScan { chunk_size }) => {
4546            if node.inputs.len() != 5 {
4547                return Err(Error::Msg(format!(
4548                    "SsdChunkScan expects 5 inputs (x, dt, a, b, c), got {}",
4549                    node.inputs.len(),
4550                ))
4551                .bt());
4552            }
4553            let x_layout = input_layout(node.inputs[0]);
4554            let b_layout = input_layout(node.inputs[3]);
4555            let x_dims = x_layout.shape().dims();
4556            let b_dims = b_layout.shape().dims();
4557            if x_dims.len() != 4 {
4558                return Err(Error::Msg(format!(
4559                    "SsdChunkScan: x must be rank 4 [batch, seqlen, heads, head_dim], got {x_dims:?}",
4560                ))
4561                .bt());
4562            }
4563            if b_dims.len() != 4 {
4564                return Err(Error::Msg(format!(
4565                    "SsdChunkScan: b must be rank 4 [batch, seqlen, heads, state_dim], got {b_dims:?}",
4566                ))
4567                .bt());
4568            }
4569            let batch = x_dims[0];
4570            let seqlen = x_dims[1];
4571            let heads = x_dims[2];
4572            let head_dim = x_dims[3];
4573            let state_dim = b_dims[3];
4574            OpParams::SsdChunkScan {
4575                batch,
4576                seqlen,
4577                heads,
4578                head_dim,
4579                state_dim,
4580                chunk_size: *chunk_size,
4581            }
4582        }
4583        // Nf4Matmul: derive (batch, m, n, k) from activations + w_packed
4584        // layouts. activations: [..., m, k] (leading dims flatten into
4585        // batch); w_packed: [n, k/2] U8.
4586        Op::Fused(_, fuel_graph::registry::FusedOpParams::Nf4Matmul { block_size }) => {
4587            if node.inputs.len() != 3 {
4588                return Err(Error::Msg(format!(
4589                    "Nf4Matmul expects 3 inputs (activations, w_packed, absmax), got {}",
4590                    node.inputs.len(),
4591                ))
4592                .bt());
4593            }
4594            let a_layout = input_layout(node.inputs[0]);
4595            let w_layout = input_layout(node.inputs[1]);
4596            let a_dims = a_layout.shape().dims();
4597            let w_dims = w_layout.shape().dims();
4598            if a_dims.len() < 2 {
4599                return Err(Error::Msg(format!(
4600                    "Nf4Matmul: activations must be rank ≥ 2, got {a_dims:?}",
4601                ))
4602                .bt());
4603            }
4604            if w_dims.len() != 2 {
4605                return Err(Error::Msg(format!(
4606                    "Nf4Matmul: w_packed must be rank 2 [n, k/2], got {w_dims:?}",
4607                ))
4608                .bt());
4609            }
4610            let m = a_dims[a_dims.len() - 2];
4611            let k = a_dims[a_dims.len() - 1];
4612            let n = w_dims[0];
4613            let batch: usize = a_dims[..a_dims.len() - 2].iter().product::<usize>().max(1);
4614            if k % 2 != 0 {
4615                return Err(Error::Msg(format!(
4616                    "Nf4Matmul: k={k} must be even (w_packed holds 2 nibbles per byte along k)",
4617                ))
4618                .bt());
4619            }
4620            if k % *block_size != 0 {
4621                return Err(Error::Msg(format!(
4622                    "Nf4Matmul: k={k} must be a multiple of block_size={block_size}",
4623                ))
4624                .bt());
4625            }
4626            if w_dims[1] != k / 2 {
4627                return Err(Error::Msg(format!(
4628                    "Nf4Matmul: w_packed second dim {} must equal k/2 = {}",
4629                    w_dims[1],
4630                    k / 2,
4631                ))
4632                .bt());
4633            }
4634            OpParams::Nf4Matmul {
4635                batch,
4636                m,
4637                n,
4638                k,
4639                block_size: *block_size,
4640            }
4641        }
4642        // TopKLastDim (row 172 item 2): `rows` = product of the leading dims,
4643        // `n` = the last axis, `k` from the node's params (validated at build time).
4644        Op::Fused(fid, fp) if *fid == fuel_graph::registry::FusedOps::TOP_K_LAST_DIM => {
4645            let fuel_graph::registry::FusedOpParams::TopKLastDim { k } = fp else {
4646                return Err(Error::Msg(format!(
4647                    "TopKLastDim: expected FusedOpParams::TopKLastDim, got {fp:?}"
4648                ))
4649                .bt());
4650            };
4651            if node.inputs.len() != 1 {
4652                return Err(Error::Msg(format!(
4653                    "TopKLastDim expects 1 input, got {}",
4654                    node.inputs.len()
4655                ))
4656                .bt());
4657            }
4658            let x = input_layout(node.inputs[0]);
4659            let dims = x.shape().dims();
4660            let Some((&n, lead)) = dims.split_last() else {
4661                return Err(Error::Msg("TopKLastDim: input must be rank >= 1".to_string()).bt());
4662            };
4663            if *k == 0 || *k > n {
4664                return Err(Error::Msg(format!("TopKLastDim: k = {k} must be in 1..={n}")).bt());
4665            }
4666            OpParams::TopKLastDim {
4667                rows: lead.iter().product::<usize>().max(1),
4668                n,
4669                k: *k,
4670            }
4671        }
4672        // MatMulTopK (row 172 item 2 step B): a [.., m, k] @ b [.., k, n], equal
4673        // batch dims, then top_k over n.
4674        Op::Fused(fid, fp) if *fid == fuel_graph::registry::FusedOps::MATMUL_TOP_K => {
4675            let fuel_graph::registry::FusedOpParams::MatMulTopK { k: top_k } = fp else {
4676                return Err(Error::Msg(format!(
4677                    "MatMulTopK: expected FusedOpParams::MatMulTopK, got {fp:?}"
4678                ))
4679                .bt());
4680            };
4681            if node.inputs.len() != 2 {
4682                return Err(Error::Msg(format!(
4683                    "MatMulTopK expects 2 inputs (a, b), got {}",
4684                    node.inputs.len()
4685                ))
4686                .bt());
4687            }
4688            let a = input_layout(node.inputs[0]);
4689            let b = input_layout(node.inputs[1]);
4690            let (ad, bd) = (a.shape().dims(), b.shape().dims());
4691            if ad.len() < 2 || ad.len() != bd.len() || ad[..ad.len() - 2] != bd[..bd.len() - 2] {
4692                return Err(Error::Msg(format!(
4693                    "MatMulTopK: a {ad:?} and b {bd:?} need equal rank >= 2 and equal batch dims"
4694                ))
4695                .bt());
4696            }
4697            let r = ad.len();
4698            let (m, k) = (ad[r - 2], ad[r - 1]);
4699            let (k2, n) = (bd[r - 2], bd[r - 1]);
4700            if k != k2 {
4701                return Err(Error::Msg(format!(
4702                    "MatMulTopK: contracting dims disagree (a trailing [{m}, {k}], b trailing [{k2}, {n}])"
4703                ))
4704                .bt());
4705            }
4706            if *top_k == 0 || *top_k > n {
4707                return Err(Error::Msg(format!("MatMulTopK: k = {top_k} must be in 1..={n}")).bt());
4708            }
4709            OpParams::MatMulTopK {
4710                batch: ad[..r - 2].iter().product::<usize>().max(1),
4711                m,
4712                n,
4713                k,
4714                top_k: *top_k,
4715            }
4716        }
4717        // AwqMatmul: (batch, m, n, k) from activations [..., m, k] and the
4718        // kernel-layout weight [n, k/8]; the padded zeros/scales widths are the
4719        // op's own build-time invariant (checked by `awq_matmul`).
4720        Op::Fused(
4721            _,
4722            fuel_graph::registry::FusedOpParams::AwqMatmul {
4723                group_size,
4724                split_k_iters,
4725            },
4726        ) => {
4727            if node.inputs.len() != 4 {
4728                return Err(Error::Msg(format!(
4729                    "AwqMatmul expects 4 inputs (activations, weight, zeros, scales), got {}",
4730                    node.inputs.len(),
4731                ))
4732                .bt());
4733            }
4734            let a_layout = input_layout(node.inputs[0]);
4735            let w_layout = input_layout(node.inputs[1]);
4736            let a_dims = a_layout.shape().dims();
4737            let w_dims = w_layout.shape().dims();
4738            if a_dims.len() < 2 {
4739                return Err(Error::Msg(format!(
4740                    "AwqMatmul: activations must be rank ≥ 2, got {a_dims:?}",
4741                ))
4742                .bt());
4743            }
4744            if w_dims.len() != 2 {
4745                return Err(Error::Msg(format!(
4746                    "AwqMatmul: weight must be rank 2 [n, k/8], got {w_dims:?}",
4747                ))
4748                .bt());
4749            }
4750            let m = a_dims[a_dims.len() - 2];
4751            let k = a_dims[a_dims.len() - 1];
4752            let n = w_dims[0];
4753            let batch: usize = a_dims[..a_dims.len() - 2].iter().product::<usize>().max(1);
4754            if k % 8 != 0 || w_dims[1] != k / 8 {
4755                return Err(Error::Msg(format!(
4756                    "AwqMatmul: weight second dim {} must equal k/8 for k={k} (a multiple of 8)",
4757                    w_dims[1],
4758                ))
4759                .bt());
4760            }
4761            OpParams::AwqMatmul {
4762                batch,
4763                m,
4764                n,
4765                k,
4766                group_size: *group_size,
4767                split_k_iters: *split_k_iters,
4768            }
4769        }
4770        // Phase 7.6 step 3: SoftmaxLastDim flows through
4771        // `Op::Fused(FusedOps::SOFTMAX_LAST_DIM, _)`. The
4772        // SOFTMAX_LAST_DIM_BACKWARD variant added in step 6
4773        // follow-up shares the same `outer × last_dim` shape
4774        // contract (input 0 is `y` for forward / forward-output
4775        // for backward; both rank-≥1 with last-dim as the
4776        // reduction axis).
4777        op if op_is_softmax_last_dim(op)
4778            || matches!(op, Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM_BACKWARD) =>
4779        {
4780            let il = input_layout(node.inputs[0]);
4781            let dims = il.shape().dims();
4782            if dims.is_empty() {
4783                return Err(Error::Msg("Op::SoftmaxLastDim requires rank ≥ 1".to_string()).bt());
4784            }
4785            let last_dim = *dims.last().unwrap();
4786            let outer_count: usize = dims[..dims.len() - 1].iter().product();
4787            OpParams::SoftmaxLastDim {
4788                outer_count,
4789                last_dim,
4790            }
4791        }
4792        Op::Flip { dim } => {
4793            // Single input. Precompute the flat-3-axis split
4794            // (outer × dim × inner) from the input shape.
4795            if node.inputs.len() != 1 {
4796                return Err(Error::Msg(format!(
4797                    "Op::Flip expects 1 input, got {}",
4798                    node.inputs.len(),
4799                ))
4800                .bt());
4801            }
4802            let in_layout = input_layout(node.inputs[0]);
4803            let in_dims = in_layout.shape().dims();
4804            if *dim >= in_dims.len() {
4805                return Err(Error::Msg(format!(
4806                    "Op::Flip: dim {dim} out of range for rank {}",
4807                    in_dims.len(),
4808                ))
4809                .bt());
4810            }
4811            let outer_count: usize = in_dims[..*dim].iter().product();
4812            let dim_size = in_dims[*dim];
4813            let inner_count: usize = in_dims[*dim + 1..].iter().product();
4814            OpParams::Flip {
4815                outer_count,
4816                dim_size,
4817                inner_count,
4818                axis: *dim,
4819            }
4820        }
4821        Op::Roll { dim, shift } => {
4822            if node.inputs.len() != 1 {
4823                return Err(Error::Msg(format!(
4824                    "Op::Roll expects 1 input, got {}",
4825                    node.inputs.len(),
4826                ))
4827                .bt());
4828            }
4829            let in_layout = input_layout(node.inputs[0]);
4830            let in_dims = in_layout.shape().dims();
4831            if *dim >= in_dims.len() {
4832                return Err(Error::Msg(format!(
4833                    "Op::Roll: dim {dim} out of range for rank {}",
4834                    in_dims.len(),
4835                ))
4836                .bt());
4837            }
4838            let outer_count: usize = in_dims[..*dim].iter().product();
4839            let dim_size = in_dims[*dim];
4840            let inner_count: usize = in_dims[*dim + 1..].iter().product();
4841            OpParams::Roll {
4842                outer_count,
4843                dim_size,
4844                inner_count,
4845                shift: *shift,
4846                axis: *dim,
4847            }
4848        }
4849        Op::CumSum { dim } => {
4850            if node.inputs.len() != 1 {
4851                return Err(Error::Msg(format!(
4852                    "Op::CumSum expects 1 input, got {}",
4853                    node.inputs.len(),
4854                ))
4855                .bt());
4856            }
4857            let in_layout = input_layout(node.inputs[0]);
4858            let in_dims = in_layout.shape().dims();
4859            if *dim >= in_dims.len() {
4860                return Err(Error::Msg(format!(
4861                    "Op::CumSum: dim {dim} out of range for rank {}",
4862                    in_dims.len(),
4863                ))
4864                .bt());
4865            }
4866            let outer_count: usize = in_dims[..*dim].iter().product();
4867            let dim_size = in_dims[*dim];
4868            let inner_count: usize = in_dims[*dim + 1..].iter().product();
4869            OpParams::CumSum {
4870                outer_count,
4871                dim_size,
4872                inner_count,
4873                axis: *dim,
4874            }
4875        }
4876        Op::Triu { diagonal } | Op::Tril { diagonal } => {
4877            if node.inputs.len() != 1 {
4878                return Err(Error::Msg(format!(
4879                    "Op::Triu/Tril expects 1 input, got {}",
4880                    node.inputs.len(),
4881                ))
4882                .bt());
4883            }
4884            let in_layout = input_layout(node.inputs[0]);
4885            let in_dims = in_layout.shape().dims();
4886            if in_dims.len() < 2 {
4887                return Err(Error::Msg(format!(
4888                    "Op::Triu/Tril requires rank >= 2, got {}",
4889                    in_dims.len(),
4890                ))
4891                .bt());
4892            }
4893            let rows = in_dims[in_dims.len() - 2];
4894            let cols = in_dims[in_dims.len() - 1];
4895            let batch_count: usize = in_dims[..in_dims.len() - 2]
4896                .iter()
4897                .product::<usize>()
4898                .max(1);
4899            OpParams::Triangular {
4900                batch_count,
4901                rows,
4902                cols,
4903                diagonal: *diagonal,
4904            }
4905        }
4906        Op::LogSoftmaxLastDim => {
4907            if node.inputs.len() != 1 {
4908                return Err(Error::Msg(format!(
4909                    "Op::LogSoftmaxLastDim expects 1 input, got {}",
4910                    node.inputs.len(),
4911                ))
4912                .bt());
4913            }
4914            let in_layout = input_layout(node.inputs[0]);
4915            let in_dims = in_layout.shape().dims();
4916            if in_dims.is_empty() {
4917                return Err(Error::Msg("Op::LogSoftmaxLastDim requires rank ≥ 1".to_string()).bt());
4918            }
4919            let last_dim = *in_dims.last().unwrap();
4920            let outer_count: usize = in_dims[..in_dims.len() - 1].iter().product();
4921            OpParams::LogSoftmaxLastDim {
4922                outer_count,
4923                last_dim,
4924            }
4925        }
4926        Op::LogSoftmaxLastDimBackward => {
4927            // Inputs: (forward_output_y, upstream_grad). Same shape contract
4928            // as SoftmaxLastDimBackward — last-dim row-wise dispatch.
4929            if node.inputs.len() != 2 {
4930                return Err(Error::Msg(format!(
4931                    "Op::LogSoftmaxLastDimBackward expects 2 inputs, got {}",
4932                    node.inputs.len(),
4933                ))
4934                .bt());
4935            }
4936            let in_layout = input_layout(node.inputs[0]);
4937            let in_dims = in_layout.shape().dims();
4938            if in_dims.is_empty() {
4939                return Err(Error::Msg(
4940                    "Op::LogSoftmaxLastDimBackward requires rank ≥ 1".to_string(),
4941                )
4942                .bt());
4943            }
4944            let last_dim = *in_dims.last().unwrap();
4945            let outer_count: usize = in_dims[..in_dims.len() - 1].iter().product();
4946            OpParams::LogSoftmaxLastDim {
4947                outer_count,
4948                last_dim,
4949            }
4950        }
4951        Op::MaskedFill { value } => {
4952            if node.inputs.len() != 2 {
4953                return Err(Error::Msg(format!(
4954                    "Op::MaskedFill expects 2 inputs (x, mask), got {}",
4955                    node.inputs.len(),
4956                ))
4957                .bt());
4958            }
4959            let fill_bytes = scalar_to_bytes(*value);
4960            OpParams::MaskedFill { fill_bytes }
4961        }
4962        // Op::MaskedFillInplace tracked by the parallel in-place
4963        // binary family session — not in HEAD's Op enum right now.
4964        Op::PadBackward {
4965            in_shape,
4966            padding,
4967            mode,
4968        } => {
4969            // Single input is the upstream gradient; output is the
4970            // input gradient (shape == `in_shape`).
4971            if node.inputs.len() != 1 {
4972                return Err(Error::Msg(format!(
4973                    "Op::PadBackward expects 1 input, got {}",
4974                    node.inputs.len(),
4975                ))
4976                .bt());
4977            }
4978            let in_dims: Vec<usize> = in_shape.dims().to_vec();
4979            // Output of the original forward Pad is the input shape
4980            // of the backward (== upstream's shape).
4981            let out_dims: Vec<usize> = in_dims
4982                .iter()
4983                .zip(padding.iter())
4984                .map(|(&d, &(b, a))| d + b + a)
4985                .collect();
4986            let mode_tag: u8 = match mode {
4987                fuel_graph::PadMode::Constant => 0,
4988                fuel_graph::PadMode::Reflect => 1,
4989                fuel_graph::PadMode::Replicate => 2,
4990            };
4991            OpParams::PadBackward {
4992                in_shape: in_dims,
4993                out_shape: out_dims,
4994                padding: padding.clone(),
4995                mode_tag,
4996            }
4997        }
4998        Op::Pad {
4999            padding,
5000            mode,
5001            value,
5002        } => {
5003            if node.inputs.len() != 1 {
5004                return Err(Error::Msg(format!(
5005                    "Op::Pad expects 1 input, got {}",
5006                    node.inputs.len(),
5007                ))
5008                .bt());
5009            }
5010            let in_layout = input_layout(node.inputs[0]);
5011            let in_dims: Vec<usize> = in_layout.shape().dims().to_vec();
5012            if padding.len() != in_dims.len() {
5013                return Err(Error::Msg(format!(
5014                    "Op::Pad: padding.len() ({}) != input rank ({})",
5015                    padding.len(),
5016                    in_dims.len(),
5017                ))
5018                .bt());
5019            }
5020            let out_dims: Vec<usize> = in_dims
5021                .iter()
5022                .zip(padding.iter())
5023                .map(|(&d, &(b, a))| d + b + a)
5024                .collect();
5025            let mode_tag: u8 = match mode {
5026                fuel_graph::PadMode::Constant => 0,
5027                fuel_graph::PadMode::Reflect => 1,
5028                fuel_graph::PadMode::Replicate => 2,
5029            };
5030            // Encode fill value as bytes for the output dtype. The
5031            // kernel is dtype-agnostic — it just memcopies the
5032            // pattern. Conversion happens once here per node, not
5033            // per element in the kernel.
5034            let fill_bytes = encode_value_to_bytes(node.dtype, *value)?;
5035            OpParams::Pad {
5036                in_shape: in_dims,
5037                out_shape: out_dims,
5038                padding: padding.clone(),
5039                mode_tag,
5040                fill_bytes,
5041            }
5042        }
5043        Op::IndexAdd { dim } => {
5044            // Inputs: (base, indices, src). All same dtype except
5045            // indices is U32. Output shape == base shape.
5046            if node.inputs.len() != 3 {
5047                return Err(Error::Msg(format!(
5048                    "Op::IndexAdd expects 3 inputs (base, indices, src), got {}",
5049                    node.inputs.len(),
5050                ))
5051                .bt());
5052            }
5053            let base_layout = input_layout(node.inputs[0]);
5054            let idx_layout = input_layout(node.inputs[1]);
5055            let src_layout = input_layout(node.inputs[2]);
5056            let base_dims = base_layout.shape().dims();
5057            let idx_dims = idx_layout.shape().dims();
5058            let src_dims = src_layout.shape().dims();
5059            if *dim >= base_dims.len() {
5060                return Err(Error::Msg(format!(
5061                    "Op::IndexAdd: dim {dim} out of range for base rank {}",
5062                    base_dims.len(),
5063                ))
5064                .bt());
5065            }
5066            if idx_dims.len() != 1 {
5067                return Err(Error::Msg(format!(
5068                    "Op::IndexAdd: indices must be rank 1, got {idx_dims:?}",
5069                ))
5070                .bt());
5071            }
5072            if base_dims.len() != src_dims.len() {
5073                return Err(Error::Msg(format!(
5074                    "Op::IndexAdd: base rank ({}) != src rank ({})",
5075                    base_dims.len(),
5076                    src_dims.len(),
5077                ))
5078                .bt());
5079            }
5080            let outer_count: usize = base_dims[..*dim].iter().product();
5081            let base_dim_size = base_dims[*dim];
5082            let inner_count: usize = base_dims[*dim + 1..].iter().product();
5083            let n_indices = idx_dims[0];
5084            OpParams::IndexAdd {
5085                outer_count,
5086                base_dim_size,
5087                n_indices,
5088                inner_count,
5089            }
5090        }
5091        Op::ScatterAdd { dim } => {
5092            if node.inputs.len() != 3 {
5093                return Err(Error::Msg(format!(
5094                    "Op::ScatterAdd expects 3 inputs (base, indices, src), got {}",
5095                    node.inputs.len(),
5096                ))
5097                .bt());
5098            }
5099            let base_layout = input_layout(node.inputs[0]);
5100            let src_layout = input_layout(node.inputs[2]);
5101            let base_shape: Vec<usize> = base_layout.shape().dims().to_vec();
5102            let src_shape: Vec<usize> = src_layout.shape().dims().to_vec();
5103            if base_shape.len() != src_shape.len() {
5104                return Err(Error::Msg(format!(
5105                    "Op::ScatterAdd: base rank ({}) != src rank ({})",
5106                    base_shape.len(),
5107                    src_shape.len(),
5108                ))
5109                .bt());
5110            }
5111            if *dim >= base_shape.len() {
5112                return Err(Error::Msg(format!(
5113                    "Op::ScatterAdd: dim {dim} out of range for rank {}",
5114                    base_shape.len(),
5115                ))
5116                .bt());
5117            }
5118            OpParams::ScatterAdd {
5119                base_shape,
5120                src_shape,
5121                dim: *dim,
5122            }
5123        }
5124        // Phase 7.6 step 5: Rope routes through the registry; the
5125        // legacy `Op::Rope` arm was retired with the variant.
5126        Op::Fused(_, fuel_graph::registry::FusedOpParams::Rope) => {
5127            // Inputs: (x, cos, sin). x is [..., seq, head_dim];
5128            // cos/sin are [seq, head_dim] (validated at graph build).
5129            if node.inputs.len() != 3 {
5130                return Err(Error::Msg(format!(
5131                    "Op::Rope expects 3 inputs (x, cos, sin), got {}",
5132                    node.inputs.len(),
5133                ))
5134                .bt());
5135            }
5136            let x_layout = input_layout(node.inputs[0]);
5137            let x_dims = x_layout.shape().dims();
5138            if x_dims.len() < 2 {
5139                return Err(
5140                    Error::Msg(format!("Op::Rope: x must have rank ≥ 2, got {x_dims:?}",)).bt(),
5141                );
5142            }
5143            let head_dim = *x_dims.last().unwrap();
5144            let seq = x_dims[x_dims.len() - 2];
5145            let outer_count: usize = x_dims[..x_dims.len() - 2].iter().product();
5146            OpParams::Rope {
5147                outer_count,
5148                seq,
5149                head_dim,
5150            }
5151        }
5152        Op::Gather { dim } => {
5153            // inputs[0] = source, inputs[1] = U32 indices (same rank).
5154            if node.inputs.len() != 2 {
5155                return Err(Error::Msg(format!(
5156                    "Op::Gather expects 2 inputs (source, indices), got {}",
5157                    node.inputs.len(),
5158                ))
5159                .bt());
5160            }
5161            let src_layout = input_layout(node.inputs[0]);
5162            let idx_layout = input_layout(node.inputs[1]);
5163            let source_shape: Vec<usize> = src_layout.shape().dims().to_vec();
5164            let output_shape: Vec<usize> = idx_layout.shape().dims().to_vec();
5165            if source_shape.len() != output_shape.len() {
5166                return Err(Error::Msg(format!(
5167                    "Op::Gather: source rank ({}) != indices rank ({})",
5168                    source_shape.len(),
5169                    output_shape.len(),
5170                ))
5171                .bt());
5172            }
5173            if *dim >= source_shape.len() {
5174                return Err(Error::Msg(format!(
5175                    "Op::Gather: dim {dim} out of range for rank {}",
5176                    source_shape.len(),
5177                ))
5178                .bt());
5179            }
5180            OpParams::Gather {
5181                source_shape,
5182                output_shape,
5183                dim: *dim,
5184            }
5185        }
5186        Op::NonZeroIndices { count_sym } => {
5187            // inputs[0] = x (the value tensor). capacity == x.elem_count();
5188            // the bundled output is [indices [capacity] U32 ; count [1] U32].
5189            if node.inputs.len() != 1 {
5190                return Err(Error::Msg(format!(
5191                    "Op::NonZeroIndices expects 1 input, got {}",
5192                    node.inputs.len(),
5193                ))
5194                .bt());
5195            }
5196            let x_layout = input_layout(node.inputs[0]);
5197            let capacity = x_layout.shape().elem_count();
5198            OpParams::NonZeroIndices {
5199                capacity,
5200                count_sym: *count_sym,
5201            }
5202        }
5203        Op::IndexSelect { dim } => {
5204            // inputs[0] = source, inputs[1] = U32 indices (rank 1).
5205            if node.inputs.len() != 2 {
5206                return Err(Error::Msg(format!(
5207                    "Op::IndexSelect expects 2 inputs (source, indices), got {}",
5208                    node.inputs.len(),
5209                ))
5210                .bt());
5211            }
5212            let src_layout = input_layout(node.inputs[0]);
5213            let idx_layout = input_layout(node.inputs[1]);
5214            let src_dims = src_layout.shape().dims();
5215            let idx_dims = idx_layout.shape().dims();
5216            if *dim >= src_dims.len() {
5217                return Err(Error::Msg(format!(
5218                    "Op::IndexSelect: dim {dim} out of range for source rank {}",
5219                    src_dims.len(),
5220                ))
5221                .bt());
5222            }
5223            if idx_dims.len() != 1 {
5224                return Err(Error::Msg(format!(
5225                    "Op::IndexSelect: indices must be rank 1, got shape {idx_dims:?}",
5226                ))
5227                .bt());
5228            }
5229            let outer_count: usize = src_dims[..*dim].iter().product();
5230            let source_dim_size = src_dims[*dim];
5231            let inner_count: usize = src_dims[*dim + 1..].iter().product();
5232            let n_indices = idx_dims[0];
5233            OpParams::IndexSelect {
5234                outer_count,
5235                source_dim_size,
5236                n_indices,
5237                inner_count,
5238            }
5239        }
5240        // Phase 7.6 step 5: legacy `Op::RmsNormLastDim` /
5241        // `Op::LayerNormLastDim` arms retired with the variants;
5242        // both now route through `Op::Fused(NORM_LAST_DIM, _)`.
5243        // Step 6 follow-up extends this arm to also cover the
5244        // backward variants (same outer × last_dim + eps geometry).
5245        Op::Fused(fid, params)
5246            if *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM
5247                || *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM
5248                || *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM_BACKWARD
5249                || *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM_BACKWARD =>
5250        {
5251            let eps = match params {
5252                fuel_graph::registry::FusedOpParams::RmsNormLastDim { eps } => *eps,
5253                fuel_graph::registry::FusedOpParams::LayerNormLastDim { eps } => *eps,
5254                fuel_graph::registry::FusedOpParams::RmsNormLastDimBackward { eps } => *eps,
5255                fuel_graph::registry::FusedOpParams::LayerNormLastDimBackward { eps } => *eps,
5256                _ => {
5257                    return Err(Error::Msg(format!(
5258                        "Op::Fused(NORM_LAST_DIM[_BACKWARD], _) expected \
5259                     RmsNormLastDim[Backward] or LayerNormLastDim[Backward] params, got {params:?}",
5260                    ))
5261                    .bt());
5262                }
5263            };
5264            let il = input_layout(node.inputs[0]);
5265            let dims = il.shape().dims();
5266            if dims.is_empty() {
5267                return Err(Error::Msg(
5268                    "Op::Fused(NORM_LAST_DIM[_BACKWARD], _) requires rank ≥ 1".to_string(),
5269                )
5270                .bt());
5271            }
5272            let last_dim = *dims.last().unwrap();
5273            let outer_count: usize = dims[..dims.len() - 1].iter().product();
5274            OpParams::NormLastDim {
5275                outer_count,
5276                last_dim,
5277                eps,
5278            }
5279        }
5280        // ReduceMaxToBackward: shape pair via the new
5281        // OpParams::ReduceMaxToBackward variant. x's shape is
5282        // `input_shape`; upstream's shape is `output_shape`.
5283        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::REDUCE_MAX_TO_BACKWARD => {
5284            if node.inputs.len() != 2 {
5285                return Err(Error::Msg(format!(
5286                    "Op::Fused(REDUCE_MAX_TO_BACKWARD) expects 2 inputs, got {}",
5287                    node.inputs.len(),
5288                ))
5289                .bt());
5290            }
5291            let x_layout = input_layout(node.inputs[0]);
5292            let up_layout = input_layout(node.inputs[1]);
5293            let input_shape: Vec<usize> = x_layout.shape().dims().to_vec();
5294            let output_shape: Vec<usize> = up_layout.shape().dims().to_vec();
5295            OpParams::ReduceMaxToBackward {
5296                input_shape,
5297                output_shape,
5298            }
5299        }
5300        Op::Concat { dim } => {
5301            // Output's shape: [..., total_dim, ...]. Compute outer
5302            // and inner counts from output_shape[..dim] and
5303            // [dim+1..]; per-input dim sizes from each input's
5304            // layout shape at index `dim`.
5305            if node.inputs.is_empty() {
5306                return Err(Error::Msg("Op::Concat requires at least 1 input".to_string()).bt());
5307            }
5308            let out_dims = node.shape.dims();
5309            if *dim >= out_dims.len() {
5310                return Err(Error::Msg(format!(
5311                    "Op::Concat: dim {dim} out of range for output rank {}",
5312                    out_dims.len(),
5313                ))
5314                .bt());
5315            }
5316            let outer_count: usize = out_dims[..*dim].iter().product();
5317            let inner_count: usize = out_dims[*dim + 1..].iter().product();
5318            let mut input_dim_sizes: Vec<usize> = Vec::with_capacity(node.inputs.len());
5319            for in_id in &node.inputs {
5320                let il = input_layout(*in_id);
5321                let il_dims = il.shape().dims();
5322                if *dim >= il_dims.len() {
5323                    return Err(Error::Msg(format!(
5324                        "Op::Concat: input {in_id:?} has rank {} but concat dim is {dim}",
5325                        il_dims.len(),
5326                    ))
5327                    .bt());
5328                }
5329                input_dim_sizes.push(il_dims[*dim]);
5330            }
5331            OpParams::Concat {
5332                outer_count,
5333                input_dim_sizes,
5334                inner_count,
5335                axis: *dim,
5336            }
5337        }
5338        Op::AddScalar(c) => OpParams::Affine { mul: 1.0, add: *c },
5339        Op::MulScalar(c) => OpParams::Affine { mul: *c, add: 0.0 },
5340        Op::Clamp { min, max } => OpParams::Clamp {
5341            min: *min,
5342            max: *max,
5343        },
5344        Op::PowI(exp) => OpParams::PowI { exp: *exp },
5345        Op::ClampInplace { min, max } => OpParams::Clamp {
5346            min: *min,
5347            max: *max,
5348        },
5349        Op::PowIInplace(exp) => OpParams::PowI { exp: *exp },
5350        // PowI backward — `(x, upstream) → grad_x = exp · x^(exp-1) ·
5351        // upstream`. Pulls the same `exp` as the forward through
5352        // FusedOpParams::PowIBackward (autograd carries it across).
5353        Op::Fused(_, fuel_graph::registry::FusedOpParams::PowIBackward { exp }) => {
5354            OpParams::PowI { exp: *exp }
5355        }
5356        // In-place affine (Phase 3 of the in-place ops infrastructure):
5357        // reuse the existing `OpParams::Affine` payload — the kernel
5358        // side doesn't care whether the destination is fresh or aliases
5359        // the input; the structural decision lives in the executor's
5360        // dedicated `WorkItemKind::InplaceKernel` arm.
5361        Op::Fused(_, fuel_graph::registry::FusedOpParams::InplaceAffine { mul, add }) => {
5362            OpParams::Affine {
5363                mul: *mul,
5364                add: *add,
5365            }
5366        }
5367        // Phase 7.6 step 5: legacy `Op::Conv2D` arm retired with the
5368        // variant; Conv2D routes through `Op::Fused(CONV2D, _)`.
5369        Op::Fused(
5370            _,
5371            fuel_graph::registry::FusedOpParams::Conv2D {
5372                stride,
5373                padding,
5374                groups,
5375            },
5376        ) => {
5377            // Inputs[0] = x [N, Cin, Hin, Win]; inputs[1] = weight
5378            // [Cout, Cin/groups, Kh, Kw]; inputs[2] (optional) = bias [Cout].
5379            // Output (this Node's shape) = [N, Cout, Hout, Wout].
5380            if node.inputs.len() != 2 && node.inputs.len() != 3 {
5381                return Err(Error::Msg(format!(
5382                    "Op::Conv2D expects 2 or 3 inputs, got {}",
5383                    node.inputs.len(),
5384                ))
5385                .bt());
5386            }
5387            let x_layout = input_layout(node.inputs[0]);
5388            let w_layout = input_layout(node.inputs[1]);
5389            let x_dims = x_layout.shape().dims();
5390            let w_dims = w_layout.shape().dims();
5391            if x_dims.len() != 4 || w_dims.len() != 4 {
5392                return Err(Error::Msg(format!(
5393                    "Op::Conv2D requires rank-4 x and weight; got x={x_dims:?} w={w_dims:?}",
5394                ))
5395                .bt());
5396            }
5397            let out_dims = node.shape.dims();
5398            if out_dims.len() != 4 {
5399                return Err(Error::Msg(format!(
5400                    "Op::Conv2D output must be rank 4, got {out_dims:?}",
5401                ))
5402                .bt());
5403            }
5404            let x_shape = [x_dims[0], x_dims[1], x_dims[2], x_dims[3]];
5405            let w_shape = [w_dims[0], w_dims[1], w_dims[2], w_dims[3]];
5406            let out_shape = [out_dims[0], out_dims[1], out_dims[2], out_dims[3]];
5407            OpParams::Conv2D {
5408                x_shape,
5409                w_shape,
5410                out_shape,
5411                stride: *stride,
5412                padding: *padding,
5413                dilation: (1, 1),
5414                groups: *groups,
5415            }
5416        }
5417        // Phase 7.6 step 5 (final): legacy `Op::PagedAttn` arm dropped.
5418        Op::Fused(
5419            _,
5420            fuel_graph::registry::FusedOpParams::PagedAttn {
5421                softmax_scale,
5422                block_size,
5423                softcap,
5424            },
5425        ) => {
5426            // Inputs[0]=q [B,Hq,Sq,D], inputs[1]=k_cache [num_blocks,
5427            // block_size, Hkv, D], inputs[2]=v_cache same shape,
5428            // inputs[3]=block_table [B, max_blocks_per_seq] U32,
5429            // inputs[4]=context_lens [B] U32, inputs[5]=alibi [Hq] (optional).
5430            if node.inputs.len() != 5 && node.inputs.len() != 6 {
5431                return Err(Error::Msg(format!(
5432                    "Op::PagedAttn expects 5 or 6 inputs, got {}",
5433                    node.inputs.len(),
5434                ))
5435                .bt());
5436            }
5437            let q_layout = input_layout(node.inputs[0]);
5438            let kc_layout = input_layout(node.inputs[1]);
5439            let vc_layout = input_layout(node.inputs[2]);
5440            let bt_layout = input_layout(node.inputs[3]);
5441            let q_dims = q_layout.shape().dims();
5442            let kc_dims = kc_layout.shape().dims();
5443            let vc_dims = vc_layout.shape().dims();
5444            let bt_dims = bt_layout.shape().dims();
5445            if q_dims.len() != 4 || kc_dims.len() != 4 || vc_dims.len() != 4 {
5446                return Err(Error::Msg(format!(
5447                    "Op::PagedAttn requires rank-4 q/k_cache/v_cache; \
5448                     got q={q_dims:?} k_cache={kc_dims:?} v_cache={vc_dims:?}",
5449                ))
5450                .bt());
5451            }
5452            if kc_dims != vc_dims {
5453                return Err(Error::Msg(format!(
5454                    "Op::PagedAttn: k_cache {kc_dims:?} and v_cache {vc_dims:?} must match",
5455                ))
5456                .bt());
5457            }
5458            if bt_dims.len() != 2 {
5459                return Err(Error::Msg(format!(
5460                    "Op::PagedAttn: block_table must be rank 2 [B, max_blocks_per_seq], got {bt_dims:?}",
5461                ))
5462                .bt());
5463            }
5464            if kc_dims[1] != *block_size {
5465                return Err(Error::Msg(format!(
5466                    "Op::PagedAttn: k_cache block_size dim ({}) must equal Op's block_size ({})",
5467                    kc_dims[1], block_size,
5468                ))
5469                .bt());
5470            }
5471            OpParams::PagedAttn {
5472                b: q_dims[0],
5473                hq: q_dims[1],
5474                hkv: kc_dims[2],
5475                sq: q_dims[2],
5476                d: q_dims[3],
5477                block_size: *block_size,
5478                max_blocks_per_seq: bt_dims[1],
5479                num_blocks: kc_dims[0],
5480                softmax_scale: *softmax_scale,
5481                softcap: *softcap,
5482            }
5483        }
5484        // Phase 7.6 step 5 (final): legacy `Op::FlashAttn` arm dropped.
5485        Op::Fused(
5486            _,
5487            fuel_graph::registry::FusedOpParams::FlashAttn {
5488                softmax_scale,
5489                causal,
5490                window_size_left,
5491                window_size_right,
5492                softcap,
5493                k_len,
5494            },
5495        ) => {
5496            // Inputs[0]=q [B,Hq,Sq,D], inputs[1]=k [B,Hkv,Sk,D],
5497            // inputs[2]=v [B,Hkv,Sk,D], inputs[3]=alibi_slopes [Hq] (optional).
5498            // `sk` is the PHYSICAL K extent (capacity, for strides/bytes);
5499            // `k_len` (resolved below) is the LOGICAL attended length.
5500            if node.inputs.len() != 3 && node.inputs.len() != 4 {
5501                return Err(Error::Msg(format!(
5502                    "Op::FlashAttn expects 3 or 4 inputs, got {}",
5503                    node.inputs.len(),
5504                ))
5505                .bt());
5506            }
5507            let q_layout = input_layout(node.inputs[0]);
5508            let k_layout = input_layout(node.inputs[1]);
5509            let v_layout = input_layout(node.inputs[2]);
5510            let q_dims = q_layout.shape().dims();
5511            let k_dims = k_layout.shape().dims();
5512            let v_dims = v_layout.shape().dims();
5513            if q_dims.len() != 4 || k_dims.len() != 4 || v_dims.len() != 4 {
5514                return Err(Error::Msg(format!(
5515                    "Op::FlashAttn requires rank-4 q/k/v; got q={q_dims:?} k={k_dims:?} v={v_dims:?}",
5516                ))
5517                .bt());
5518            }
5519            if k_dims != v_dims {
5520                return Err(Error::Msg(format!(
5521                    "Op::FlashAttn: k {k_dims:?} and v {v_dims:?} must share shape",
5522                ))
5523                .bt());
5524            }
5525            if q_dims[0] != k_dims[0] || q_dims[3] != k_dims[3] {
5526                return Err(Error::Msg(format!(
5527                    "Op::FlashAttn: q {q_dims:?} and k {k_dims:?} must share B and D",
5528                ))
5529                .bt());
5530            }
5531            let sk = k_dims[2];
5532            // Resolve the logical attended length. `None` ⇒ attend the
5533            // full K extent (today's behavior). `Some(dyn)` ⇒ resolve
5534            // against the per-pass SymEnv; the resolved length must fit
5535            // the capacity and cover Sq (a valid causal prefix).
5536            let attended_k_len = match k_len {
5537                None => sk,
5538                Some(dyn_k) => {
5539                    let kl = dyn_k.resolve(sym_env).ok_or_else(|| {
5540                        Error::Msg(format!(
5541                            "Op::FlashAttn: dynamic k_len {dyn_k:?} is unbound in the SymEnv at realize",
5542                        ))
5543                        .bt()
5544                    })?;
5545                    if kl > sk {
5546                        return Err(Error::Msg(format!(
5547                            "Op::FlashAttn: resolved k_len ({kl}) exceeds K capacity ({sk})",
5548                        ))
5549                        .bt());
5550                    }
5551                    if kl < q_dims[2] {
5552                        return Err(Error::Msg(format!(
5553                            "Op::FlashAttn: resolved k_len ({kl}) < Sq ({}) — not a valid causal prefix",
5554                            q_dims[2],
5555                        ))
5556                        .bt());
5557                    }
5558                    kl
5559                }
5560            };
5561            OpParams::FlashAttn {
5562                b: q_dims[0],
5563                hq: q_dims[1],
5564                hkv: k_dims[1],
5565                sq: q_dims[2],
5566                sk,
5567                d: q_dims[3],
5568                k_len: attended_k_len,
5569                softmax_scale: *softmax_scale,
5570                causal: *causal,
5571                window_size_left: *window_size_left,
5572                window_size_right: *window_size_right,
5573                softcap: *softcap,
5574            }
5575        }
5576        Op::ReduceSumTo(target_shape) => {
5577            if node.inputs.len() != 1 {
5578                return Err(Error::Msg(format!(
5579                    "Op::ReduceSumTo expects 1 input, got {}",
5580                    node.inputs.len(),
5581                ))
5582                .bt());
5583            }
5584            let in_layout = input_layout(node.inputs[0]);
5585            let input_shape: Vec<usize> = in_layout.shape().dims().to_vec();
5586            let output_shape: Vec<usize> = target_shape.dims().to_vec();
5587            OpParams::ReduceSumTo {
5588                input_shape,
5589                output_shape,
5590            }
5591        }
5592        Op::ReduceMaxTo(target_shape) => {
5593            if node.inputs.len() != 1 {
5594                return Err(Error::Msg(format!(
5595                    "Op::ReduceMaxTo expects 1 input, got {}",
5596                    node.inputs.len(),
5597                ))
5598                .bt());
5599            }
5600            let in_layout = input_layout(node.inputs[0]);
5601            let input_shape: Vec<usize> = in_layout.shape().dims().to_vec();
5602            let output_shape: Vec<usize> = target_shape.dims().to_vec();
5603            OpParams::ReduceMaxTo {
5604                input_shape,
5605                output_shape,
5606            }
5607        }
5608        // Phase 7.6 step 5 (final): legacy `Op::ConvTranspose2D` arm dropped.
5609        Op::Fused(
5610            _,
5611            fuel_graph::registry::FusedOpParams::ConvTranspose2D {
5612                stride,
5613                padding,
5614                output_padding,
5615                dilation,
5616                groups,
5617            },
5618        ) => {
5619            // Inputs[0] = x [N, Cin, Hin, Win]; inputs[1] = weight
5620            // [Cin, Cout/groups, Kh, Kw]; inputs[2] (optional) = bias [Cout].
5621            // Output (this Node's shape) = [N, Cout, Hout, Wout].
5622            if node.inputs.len() != 2 && node.inputs.len() != 3 {
5623                return Err(Error::Msg(format!(
5624                    "Op::ConvTranspose2D expects 2 or 3 inputs, got {}",
5625                    node.inputs.len(),
5626                ))
5627                .bt());
5628            }
5629            let x_layout = input_layout(node.inputs[0]);
5630            let w_layout = input_layout(node.inputs[1]);
5631            let x_dims = x_layout.shape().dims();
5632            let w_dims = w_layout.shape().dims();
5633            if x_dims.len() != 4 || w_dims.len() != 4 {
5634                return Err(Error::Msg(format!(
5635                    "Op::ConvTranspose2D requires rank-4 x and weight; got x={x_dims:?} w={w_dims:?}",
5636                ))
5637                .bt());
5638            }
5639            let out_dims = node.shape.dims();
5640            if out_dims.len() != 4 {
5641                return Err(Error::Msg(format!(
5642                    "Op::ConvTranspose2D output must be rank 4, got {out_dims:?}",
5643                ))
5644                .bt());
5645            }
5646            let x_shape = [x_dims[0], x_dims[1], x_dims[2], x_dims[3]];
5647            let w_shape = [w_dims[0], w_dims[1], w_dims[2], w_dims[3]];
5648            let out_shape = [out_dims[0], out_dims[1], out_dims[2], out_dims[3]];
5649            OpParams::ConvTranspose2D {
5650                x_shape,
5651                w_shape,
5652                out_shape,
5653                stride: *stride,
5654                padding: *padding,
5655                output_padding: *output_padding,
5656                dilation: *dilation,
5657                groups: *groups,
5658            }
5659        }
5660        Op::WriteSlice { ranges, dyn_offset } => {
5661            // inputs[0] = destination (its shape == this node's shape
5662            // since WriteSlice's output adopts the destination's
5663            // Layout). inputs[1] = source slab; its shape is implied
5664            // by `ranges`. The kernel needs the destination shape to
5665            // compute strides for the slab walk.
5666            if node.inputs.len() != 2 {
5667                return Err(Error::Msg(format!(
5668                    "Op::WriteSlice expects 2 inputs (destination, source), got {}",
5669                    node.inputs.len(),
5670                ))
5671                .bt());
5672            }
5673            let dest_dims = node.shape.dims().to_vec();
5674            if ranges.len() != dest_dims.len() {
5675                return Err(Error::Msg(format!(
5676                    "Op::WriteSlice: ranges.len() ({}) must equal destination rank ({})",
5677                    ranges.len(),
5678                    dest_dims.len(),
5679                ))
5680                .bt());
5681            }
5682            // Phase D symbolic extents: when present, resolve the runtime
5683            // start offset against the per-pass SymEnv, overriding
5684            // `ranges[axis].0`. The slab WIDTH on that axis stays
5685            // `ranges[axis].1 - ranges[axis].0`, so the effective range
5686            // becomes `(base, base + width)`. `None` ⇒ fully static, and
5687            // the SymEnv is never consulted (empty-env realize unchanged).
5688            //
5689            // DUAL-PATH (increment 2b — data-determined dynamic shapes):
5690            //  - The offset resolves in the compile-time `sym_env` (static,
5691            //    or an INPUT-determined `cached_len`): bake it into `ranges`
5692            //    now, exactly as before.
5693            //  - It is UNBOUND at compile AND a producer in this graph binds
5694            //    it (`Op::NonZeroIndices`'s count, etc.): it is
5695            //    DATA-DETERMINED — leave `ranges[axis]` as the static
5696            //    placeholder and DEFER, carrying the `DynScalar` in
5697            //    `deferred_dyn_offset`. The `WorkItemKind::WriteSlice`
5698            //    executor arm resolves it from `produced_syms` (after the
5699            //    producer runs) and bounds-checks the resolved range there.
5700            //  - It is unbound AND no producer binds it: a genuine caller
5701            //    error → surface it here (preserves the unbound-error path).
5702            let mut ranges = ranges.clone();
5703            let mut deferred_dyn_offset: Option<(usize, fuel_ir::DynScalar)> = None;
5704            if let Some((axis, off)) = dyn_offset {
5705                if *axis >= ranges.len() {
5706                    return Err(Error::Msg(format!(
5707                        "Op::WriteSlice: dyn_offset axis ({axis}) out of bounds for rank {}",
5708                        ranges.len(),
5709                    ))
5710                    .bt());
5711                }
5712                match off.resolve(sym_env) {
5713                    Some(base) => {
5714                        let (start, end) = ranges[*axis];
5715                        let width = end - start;
5716                        ranges[*axis] = (base, base + width);
5717                    }
5718                    None => {
5719                        let is_data_determined = matches!(off, fuel_ir::DynScalar::Sym(s)
5720                            if graph.binds_data_determined_sym(*s));
5721                        if is_data_determined {
5722                            deferred_dyn_offset = Some((*axis, *off));
5723                        } else {
5724                            return Err(Error::Msg(format!(
5725                                "Op::WriteSlice: dynamic offset {off:?} on axis {axis} is \
5726                                 unbound in the SymEnv at realize (and no producer in the \
5727                                 graph binds it, so it is not data-determined)",
5728                            ))
5729                            .bt());
5730                        }
5731                    }
5732                }
5733            }
5734            for (i, &(start, end)) in ranges.iter().enumerate() {
5735                // The deferred axis still holds its static placeholder; the
5736                // executor bounds-checks the resolved range after producing
5737                // the count. Every other axis is fully known now.
5738                if deferred_dyn_offset.is_some_and(|(a, _)| a == i) {
5739                    continue;
5740                }
5741                if end < start || end > dest_dims[i] {
5742                    return Err(Error::Msg(format!(
5743                        "Op::WriteSlice: ranges[{i}] = ({start}, {end}) invalid \
5744                         for destination dim {i} = {}",
5745                        dest_dims[i],
5746                    ))
5747                    .bt());
5748                }
5749            }
5750            OpParams::WriteSlice {
5751                dest_shape: dest_dims,
5752                ranges,
5753                deferred_dyn_offset,
5754            }
5755        }
5756        Op::WriteSliceRotating {
5757            axis,
5758            modulus,
5759            ranges,
5760        } => {
5761            // inputs[0] = destination, inputs[1] = source slab,
5762            // inputs[2] = dynamic position scalar (U32). The builder
5763            // already validated rank / dtype / shape parity; the
5764            // exec-time check below mirrors WriteSlice for the
5765            // structural invariants the executor depends on.
5766            if node.inputs.len() != 3 {
5767                return Err(Error::Msg(format!(
5768                    "Op::WriteSliceRotating expects 3 inputs (destination, source, position), got {}",
5769                    node.inputs.len(),
5770                ))
5771                .bt());
5772            }
5773            let dest_dims = node.shape.dims().to_vec();
5774            if ranges.len() != dest_dims.len() {
5775                return Err(Error::Msg(format!(
5776                    "Op::WriteSliceRotating: ranges.len() ({}) must equal destination rank ({})",
5777                    ranges.len(),
5778                    dest_dims.len(),
5779                ))
5780                .bt());
5781            }
5782            if *axis >= dest_dims.len() {
5783                return Err(Error::Msg(format!(
5784                    "Op::WriteSliceRotating: axis {axis} out of bounds for rank {}",
5785                    dest_dims.len(),
5786                ))
5787                .bt());
5788            }
5789            if *modulus == 0 || *modulus > dest_dims[*axis] {
5790                return Err(Error::Msg(format!(
5791                    "Op::WriteSliceRotating: modulus {modulus} invalid for dest_shape[{axis}] = {}",
5792                    dest_dims[*axis],
5793                ))
5794                .bt());
5795            }
5796            OpParams::WriteSliceRotating {
5797                dest_shape: dest_dims,
5798                axis: *axis,
5799                modulus: *modulus,
5800                ranges: ranges.clone(),
5801            }
5802        }
5803        Op::WriteSliceDoff { axis, ranges } => {
5804            // inputs[0] = destination, inputs[1] = source slab,
5805            // inputs[2] = device-resident I64 offset scalar. The
5806            // builder validated rank / dtype / static-width parity; the
5807            // exec-time check below mirrors WriteSliceRotating minus the
5808            // modulus (no wrap). Bounds on the *dynamic* offset are the
5809            // caller's contract (device-only, un-checkable here).
5810            if node.inputs.len() != 3 {
5811                return Err(Error::Msg(format!(
5812                    "Op::WriteSliceDoff expects 3 inputs (destination, source, offset), got {}",
5813                    node.inputs.len(),
5814                ))
5815                .bt());
5816            }
5817            let dest_dims = node.shape.dims().to_vec();
5818            if ranges.len() != dest_dims.len() {
5819                return Err(Error::Msg(format!(
5820                    "Op::WriteSliceDoff: ranges.len() ({}) must equal destination rank ({})",
5821                    ranges.len(),
5822                    dest_dims.len(),
5823                ))
5824                .bt());
5825            }
5826            if *axis >= dest_dims.len() {
5827                return Err(Error::Msg(format!(
5828                    "Op::WriteSliceDoff: axis {axis} out of bounds for rank {}",
5829                    dest_dims.len(),
5830                ))
5831                .bt());
5832            }
5833            OpParams::WriteSliceDoff {
5834                dest_shape: dest_dims,
5835                axis: *axis,
5836                ranges: ranges.clone(),
5837            }
5838        }
5839        _ => OpParams::None,
5840    })
5841}
5842
5843/// Execute one work item. Three branches by `WorkItemKind`:
5844///
5845/// - `ConstAdopt` — verify cache has an entry pre-seeded by the
5846///   caller; record the layout from the WorkItem.
5847/// - `ViewOf { input }` — clone the input's Storage Arc into the
5848///   output slot (bytes are shared); record the strided layout
5849///   from the WorkItem.
5850/// - `Kernel` — gather input Arcs, allocate the output, run the
5851///   compiled kernel, store the result; record the contiguous
5852///   layout from the WorkItem.
5853///
5854/// Best-effort: prefix a realize-time node error with the failing node's graph
5855/// location — `Graph::describe_node` renders `Node#N (op, out shape, dtype,
5856/// inputs=[...])`, enough to grep-locate the offending op in a large graph. The
5857/// legacy per-node executors (`fuel-graph-executor`, the retired
5858/// `fuel-reference-backend`) wrapped panics this way; the PipelinedExecutor
5859/// surfaces the raw kernel error, so a dtype/shape/OOB failure deep in a model
5860/// arrived with no graph coordinate. On a graph read-lock failure the original
5861/// error passes through unchanged — the location is a navigation aid, never
5862/// worth masking the real error with a lock issue. Zero happy-path cost: only
5863/// the error branch touches the graph.
5864fn with_node_location(graph: &Arc<RwLock<Graph>>, node_id: NodeId, err: Error) -> Error {
5865    match graph.read() {
5866        Ok(g) => err.context(g.describe_node(node_id)),
5867        Err(_) => err,
5868    }
5869}
5870
5871/// Execute one [`WorkItem`] against the cache, returning the node's
5872/// [`CompletionHandle`].
5873///
5874/// Step E A4b-1: the producing arms (Kernel / WriteSlice / WriteSliceRotating /
5875/// in-place / cross-device Copy alloc) return the handle from `execute_compiled`
5876/// *without* waiting it inline — the realize loop stores it in its per-node
5877/// handle map and drains at realize-end. Non-producing arms (const adopt, view,
5878/// slot projection, release marker, contiguize) are pure Arc-clones / host
5879/// allocs whose work is already complete → [`CompletionHandle::Ready`].
5880/// Read a data-determined runtime count from bundle slot 1 of a
5881/// just-realized producer and bind it into the per-pass `SymEnv` under
5882/// `count_sym` — the data-dependent dynamic-shapes seam (increment 2a).
5883/// The producer's bundle is `[indices [capacity] U32 ; count [1] U32]`;
5884/// slot 1's single U32 starts at byte `capacity * 4` (after the
5885/// `capacity`-element U32 primary slot). CPU only for now — device
5886/// backends need a D2H after the completion handle is waited (a documented
5887/// follow-up; the whole data-dependent path is CPU-first). Called AFTER
5888/// `execute_compiled`, whose CPU path returns a `Ready` handle, so the
5889/// bytes are already valid.
5890fn bind_data_determined_count(
5891    arc: &Arc<RwLock<Storage>>,
5892    capacity: usize,
5893    count_sym: fuel_ir::SymId,
5894    produced_syms: &mut SymEnv,
5895) -> Result<()> {
5896    let guard = arc
5897        .read()
5898        .map_err(|_| poisoned("NonZeroIndices output storage"))?;
5899    let count_byte_off = capacity * std::mem::size_of::<u32>();
5900    let end = count_byte_off + std::mem::size_of::<u32>();
5901    // The non-CPU `BackendStorage` variants are cfg-gated; with GPU
5902    // features off, `Cpu` is the only variant and the fallback arm is
5903    // unreachable (a documented CPU-first limitation, not dead logic).
5904    #[allow(unreachable_patterns)]
5905    let count = match &guard.inner {
5906        fuel_memory::BackendStorage::Cpu(cpu_bytes) => {
5907            let bytes = cpu_bytes.bytes();
5908            if end > bytes.len() {
5909                return Err(Error::Msg(format!(
5910                    "NonZeroIndices: count slot byte range [{count_byte_off}..{end}) \
5911                     exceeds bundle byte length {}",
5912                    bytes.len(),
5913                ))
5914                .bt());
5915            }
5916            u32::from_le_bytes(
5917                bytes[count_byte_off..end]
5918                    .try_into()
5919                    .expect("4 bytes → u32"),
5920            )
5921        }
5922        other => {
5923            return Err(Error::Msg(format!(
5924                "NonZeroIndices: data-determined count read is CPU-only today; got \
5925                 BackendStorage::{:?} (device backends need a D2H after the completion \
5926                 handle is waited — a documented follow-up)",
5927                other.backend_id(),
5928            ))
5929            .bt());
5930        }
5931    };
5932    produced_syms.bind(count_sym, count as usize)?;
5933    Ok(())
5934}
5935
5936/// Increment 2b — the consumer half of data-dependent dynamic shapes. When
5937/// a `WriteSlice`'s offset is DATA-DETERMINED (its `SymId` is produced
5938/// mid-pass, so `op_to_op_params` deferred it into
5939/// `OpParams::WriteSlice::deferred_dyn_offset` instead of baking it at
5940/// compile), resolve it HERE from `produced_syms` — populated by the
5941/// producer's execute step (single-threaded topological order guarantees
5942/// the producer already ran). Returns a patched clone of the `CompiledNode`
5943/// with the resolved `ranges` (and `deferred_dyn_offset` cleared) for the
5944/// kernel; `None` when there is nothing to defer (the common path — no
5945/// clone). Bounds-checks the resolved range (deferred past compile).
5946fn resolve_deferred_write_slice(
5947    compiled: &CompiledNode,
5948    produced_syms: &SymEnv,
5949    node_id: NodeId,
5950) -> Result<Option<CompiledNode>> {
5951    let OpParams::WriteSlice {
5952        dest_shape,
5953        ranges,
5954        deferred_dyn_offset,
5955    } = &compiled.op_params
5956    else {
5957        return Ok(None);
5958    };
5959    let Some((axis, off)) = deferred_dyn_offset else {
5960        return Ok(None);
5961    };
5962    let base = off.resolve(produced_syms).ok_or_else(|| {
5963        Error::Msg(format!(
5964            "Op::WriteSlice {node_id:?}: data-determined offset {off:?} on axis {axis} is \
5965             unbound in produced_syms at execute (its producer did not run / bind it)",
5966        ))
5967        .bt()
5968    })?;
5969    let mut ranges = ranges.clone();
5970    let (start, end) = ranges[*axis];
5971    let width = end - start;
5972    let resolved = (base, base + width);
5973    if resolved.1 > dest_shape[*axis] {
5974        return Err(Error::Msg(format!(
5975            "Op::WriteSlice {node_id:?}: resolved data-determined range {resolved:?} on axis \
5976             {axis} exceeds destination dim = {}",
5977            dest_shape[*axis],
5978        ))
5979        .bt());
5980    }
5981    ranges[*axis] = resolved;
5982    let mut patched = compiled.clone();
5983    patched.op_params = OpParams::WriteSlice {
5984        dest_shape: dest_shape.clone(),
5985        ranges,
5986        deferred_dyn_offset: None,
5987    };
5988    Ok(Some(patched))
5989}
5990
5991/// Dynamic-M matmul: when a matmul's row count is DATA-DETERMINED
5992/// (`MatmulM::Deferred`, deferred by `op_to_op_params` because a producer
5993/// binds its `SymId` mid-pass), resolve it HERE from `produced_syms` and
5994/// run the kernel against a patched clone whose `m_compute` is
5995/// `MatmulM::Rows(count)`. Mirrors `resolve_deferred_write_slice`. `None`
5996/// when nothing is deferred (the common path — no clone). The kernel then
5997/// computes exactly `count` rows of the `m`-row capacity buffer.
5998fn resolve_deferred_matmul(
5999    compiled: &CompiledNode,
6000    produced_syms: &SymEnv,
6001    node_id: NodeId,
6002) -> Result<Option<CompiledNode>> {
6003    let OpParams::Matmul {
6004        lhs_batch_dims,
6005        rhs_batch_dims,
6006        m,
6007        n,
6008        k,
6009        m_compute,
6010    } = &compiled.op_params
6011    else {
6012        return Ok(None);
6013    };
6014    let MatmulM::Deferred(dyn_m) = m_compute else {
6015        return Ok(None);
6016    };
6017    let rows = dyn_m.resolve(produced_syms).ok_or_else(|| {
6018        Error::Msg(format!(
6019            "Op::MatMul {node_id:?}: data-determined row count {dyn_m:?} is unbound in \
6020             produced_syms at execute (its producer did not run / bind it)",
6021        ))
6022        .bt()
6023    })?;
6024    if rows > *m {
6025        return Err(Error::Msg(format!(
6026            "Op::MatMul {node_id:?}: resolved row count {rows} exceeds capacity {m}",
6027        ))
6028        .bt());
6029    }
6030    let mut patched = compiled.clone();
6031    patched.op_params = OpParams::Matmul {
6032        lhs_batch_dims: lhs_batch_dims.clone(),
6033        rhs_batch_dims: rhs_batch_dims.clone(),
6034        m: *m,
6035        n: *n,
6036        k: *k,
6037        m_compute: MatmulM::Rows(rows),
6038    };
6039    Ok(Some(patched))
6040}
6041
6042fn execute_work_item(
6043    item: &WorkItem,
6044    cache: &mut StorageCache,
6045    #[cfg_attr(
6046        not(any(feature = "cuda", feature = "vulkan")),
6047        allow(unused_variables)
6048    )]
6049    devices: &mut DeviceRegistry,
6050    layout_cache: &mut HashMap<NodeId, Layout>,
6051    produced_syms: &mut SymEnv,
6052    // Step E A4b open question #4 — "event only where waited": whether
6053    // THIS item's node id is in the realize's `WaitSet` (`will_be_waited`
6054    // in `pipelined.rs`, computed once per item by the caller). Forwarded
6055    // to every `execute_compiled_with_wait_hint` call below so a CUDA
6056    // kernel with no mid-walk reader skips its `Event` entirely.
6057    will_be_waited: bool,
6058    // CapturedRun executor build-out: persistent-output mode. `None` on
6059    // every existing realize path ⇒ byte-identical (fresh alloc, nothing
6060    // recorded). `Some(Record)` records each Kernel output's fixed Arc;
6061    // `Some(Reuse)` reuses the recorded buffer (no alloc — capture-safe)
6062    // and the write-into kernel path writes into it in place. Only the
6063    // `Kernel` arm consults it; every other arm ignores it.
6064    mut persistent: Option<&mut PersistentOutputs>,
6065) -> Result<CompletionHandle> {
6066    match &item.kind {
6067        WorkItemKind::ConstAdopt => {
6068            if !cache.contains_key(&item.node_id) {
6069                return Err(Error::Msg(format!(
6070                    "PipelinedExecutor: Const node {:?} not in input cache",
6071                    item.node_id
6072                ))
6073                .bt());
6074            }
6075            // Layout for input cache entries was seeded at realize
6076            // start; refresh from the WorkItem in case the side-table
6077            // was set after seeding.
6078            layout_cache.insert(item.node_id, item.output_layout.clone());
6079            Ok(CompletionHandle::Ready)
6080        }
6081        WorkItemKind::ViewOf { input } => {
6082            let input_arc = cache.get(input).cloned().ok_or_else(|| {
6083                Error::Msg(format!(
6084                    "PipelinedExecutor: view-op input {:?} of {:?} not realized",
6085                    input, item.node_id,
6086                ))
6087                .bt()
6088            })?;
6089            cache.insert(item.node_id, input_arc);
6090            layout_cache.insert(item.node_id, item.output_layout.clone());
6091            Ok(CompletionHandle::Ready)
6092        }
6093        WorkItemKind::SlotView { producer } => {
6094            // Op::View — multi-output projection. Same realization
6095            // shape as ViewOf: clone the producer's Storage Arc into
6096            // the View's cache slot. The WorkItem's output_layout was
6097            // computed at graph-build time by `Tensor::view`, with
6098            // the slot's byte_offset baked into start_offset (in
6099            // slot-dtype-element units). Downstream kernels reading
6100            // the producer's bytes as the slot's dtype starting at
6101            // that offset see the slot's typed window.
6102            let producer_arc = cache.get(producer).cloned().ok_or_else(|| {
6103                Error::Msg(format!(
6104                    "PipelinedExecutor: Op::View producer {:?} of {:?} not realized",
6105                    producer, item.node_id,
6106                ))
6107                .bt()
6108            })?;
6109            cache.insert(item.node_id, producer_arc);
6110            layout_cache.insert(item.node_id, item.output_layout.clone());
6111            Ok(CompletionHandle::Ready)
6112        }
6113        WorkItemKind::SlotOwn { producer, slot } => {
6114            // Op::ViewOwned — allocate a fresh Storage of the slot's
6115            // (shape, dtype) on the producer's device and copy the
6116            // slot's bytes in. Per-backend fast paths:
6117            //   - CPU:    direct &[u8]→&mut[u8] memcpy via CpuStorageBytes
6118            //   - CUDA:   D2D via CudaStorageBytes::slot_copy_to_new
6119            //             (cuMemcpyDtoDAsync with offset src pointer)
6120            //   - Vulkan: vkCmdCopyBuffer via
6121            //             VulkanBackend::slot_copy_to_new_handle
6122            //             (srcOffset/dstOffset/size)
6123            // For backends without a copy-with-offset hook we fall
6124            // back to a host round-trip (`to_host_buffer_dyn` →
6125            // slice → `storage_from_host_buffer_owned_dyn`), which
6126            // works but is wasteful.
6127            let producer_arc = cache.get(producer).cloned().ok_or_else(|| {
6128                Error::Msg(format!(
6129                    "PipelinedExecutor: Op::ViewOwned producer {:?} of {:?} not realized",
6130                    producer, item.node_id,
6131                ))
6132                .bt()
6133            })?;
6134            let new_storage = {
6135                let guard = producer_arc
6136                    .read()
6137                    .map_err(|_| poisoned("ViewOwned producer storage"))?;
6138                let bundle = guard.bundle().ok_or_else(|| {
6139                    Error::Msg(format!(
6140                        "Op::ViewOwned: producer {:?} has no bundle side-table \
6141                         — the multi-output authoring contract requires \
6142                         Storage::with_bundle / new_bundled at allocation \
6143                         time. Node {:?} slot {} cannot resolve its source.",
6144                        producer, item.node_id, slot,
6145                    ))
6146                    .bt()
6147                })?;
6148                let sv = bundle.get(*slot as usize).cloned().ok_or_else(|| {
6149                    Error::Msg(format!(
6150                        "Op::ViewOwned: slot {} out of range for producer {:?} \
6151                         (bundle has {} slots)",
6152                        slot,
6153                        producer,
6154                        bundle.len(),
6155                    ))
6156                    .bt()
6157                })?;
6158                use fuel_memory::BackendStorage;
6159                match &guard.inner {
6160                    BackendStorage::Cpu(cpu_bytes) => {
6161                        let src_bytes = cpu_bytes.bytes();
6162                        let end = sv.byte_offset + sv.len_bytes();
6163                        if end > src_bytes.len() {
6164                            return Err(Error::Msg(format!(
6165                                "Op::ViewOwned: slot {} byte range [{}..{}) \
6166                                 exceeds producer's CPU byte length {}",
6167                                slot,
6168                                sv.byte_offset,
6169                                end,
6170                                src_bytes.len(),
6171                            ))
6172                            .bt());
6173                        }
6174                        let owned = fuel_cpu_backend::CpuStorageBytes::from_bytes(
6175                            &src_bytes[sv.byte_offset..end],
6176                        );
6177                        fuel_memory::Storage::new(BackendStorage::Cpu(owned), sv.dtype)
6178                    }
6179                    #[cfg(feature = "cuda")]
6180                    BackendStorage::Cuda(cuda_bytes) => {
6181                        let dst = cuda_bytes.slot_copy_to_new(sv.byte_offset, sv.len_bytes())?;
6182                        fuel_memory::Storage::new(BackendStorage::Cuda(dst), sv.dtype)
6183                    }
6184                    #[cfg(feature = "vulkan")]
6185                    BackendStorage::Vulkan(vk_bytes) => {
6186                        let backend = vk_bytes.backend().ok_or_else(|| {
6187                            Error::Msg(format!(
6188                                "Op::ViewOwned: producer {:?} is on Vulkan but \
6189                                 its storage has no VulkanBackend handle. \
6190                                 Storages flowing through the pipelined executor \
6191                                 must be constructed via alloc_bytes_handle / \
6192                                 upload_bytes_handle so the bundle's slot extraction \
6193                                 path can reach the backend.",
6194                                producer,
6195                            ))
6196                            .bt()
6197                        })?;
6198                        let dst = backend.slot_copy_to_new_handle(
6199                            vk_bytes,
6200                            sv.byte_offset,
6201                            sv.len_bytes(),
6202                        )?;
6203                        fuel_memory::Storage::new(BackendStorage::Vulkan(dst), sv.dtype)
6204                    }
6205                    #[allow(unreachable_patterns)]
6206                    _ => {
6207                        return Err(Error::Msg(format!(
6208                            "Op::ViewOwned: producer {:?} is on a backend \
6209                             without a slot-copy-with-offset hook \
6210                             (CPU + CUDA + Vulkan wired). Add a per-backend \
6211                             `slot_copy_to_new`-equivalent and extend the \
6212                             match arm.",
6213                            producer,
6214                        ))
6215                        .bt());
6216                    }
6217                }
6218            };
6219            cache.insert(item.node_id, Arc::new(RwLock::new(new_storage)));
6220            layout_cache.insert(item.node_id, item.output_layout.clone());
6221            // A4b-1: Op::ViewOwned's slot copy (CUDA D2D) is same-stream; its
6222            // completion is carried by the realize-end full-stream sync in
6223            // `to_cpu_bytes` (unchanged) — `Ready` here is behavior-preserving.
6224            Ok(CompletionHandle::Ready)
6225        }
6226        WorkItemKind::WriteSlice { dest, source } => {
6227            let compiled = item.compiled.as_ref().ok_or_else(|| {
6228                Error::Msg(format!(
6229                    "PipelinedExecutor: WriteSlice work item {:?} has no compiled node",
6230                    item.node_id,
6231                ))
6232                .bt()
6233            })?;
6234            // Increment 2b: if the offset is DATA-DETERMINED, resolve it from
6235            // the producer-bound `produced_syms` and run the kernel against
6236            // the patched (resolved-range) node. `None` on the common path.
6237            let patched_ws = resolve_deferred_write_slice(compiled, produced_syms, item.node_id)?;
6238            let compiled = patched_ws.as_ref().unwrap_or(compiled);
6239            let dest_arc = cache.get(dest).cloned().ok_or_else(|| {
6240                Error::Msg(format!(
6241                    "PipelinedExecutor: WriteSlice destination {:?} of {:?} not realized",
6242                    dest, item.node_id,
6243                ))
6244                .bt()
6245            })?;
6246            let source_arc = cache.get(source).cloned().ok_or_else(|| {
6247                Error::Msg(format!(
6248                    "PipelinedExecutor: WriteSlice source {:?} of {:?} not realized",
6249                    source, item.node_id,
6250                ))
6251                .bt()
6252            })?;
6253            let dest_layout = layout_cache.get(dest).cloned().ok_or_else(|| {
6254                Error::Msg(format!(
6255                    "PipelinedExecutor: WriteSlice destination {:?} of {:?} has no cached layout",
6256                    dest, item.node_id,
6257                ))
6258                .bt()
6259            })?;
6260            let source_layout = layout_cache.get(source).cloned().ok_or_else(|| {
6261                Error::Msg(format!(
6262                    "PipelinedExecutor: WriteSlice source {:?} of {:?} has no cached layout",
6263                    source, item.node_id,
6264                ))
6265                .bt()
6266            })?;
6267            // v1 contract: destination must be contiguous + zero
6268            // offset. Strided dests would force the kernel to walk
6269            // both source and dest strides; defer until KV cache
6270            // exposes a non-contig dest. Source CAN be non-contig —
6271            // we auto-contiguize it here so the kernel sees a flat
6272            // slab.
6273            if !dest_layout.is_contiguous() || dest_layout.start_offset() != 0 {
6274                return Err(Error::Msg(format!(
6275                    "Op::WriteSlice (Phase E.3.2 v1): destination {:?} must be \
6276                     contiguous + zero-offset; got Layout {:?}",
6277                    dest, dest_layout,
6278                ))
6279                .bt());
6280            }
6281            let source_arc_contig = {
6282                let s_dtype = source_arc
6283                    .read()
6284                    .map_err(|_| poisoned("WriteSlice source storage"))?
6285                    .dtype;
6286                let s_len_bytes = source_arc
6287                    .read()
6288                    .map_err(|_| poisoned("WriteSlice source storage"))?
6289                    .inner
6290                    .len_bytes();
6291                let layout_bytes = source_layout.shape().elem_count() * s_dtype.size_in_bytes();
6292                let bytes_match_shape = s_len_bytes == layout_bytes;
6293                let already_contig = source_layout.is_contiguous()
6294                    && source_layout.start_offset() == 0
6295                    && bytes_match_shape;
6296                if already_contig {
6297                    source_arc
6298                } else {
6299                    auto_contiguize(&source_arc, &source_layout)?
6300                }
6301            };
6302            let source_layout_kernel = fuel_ir::Layout::contiguous(source_layout.shape().clone());
6303            // The kernel sees inputs=[source] and outputs=[dest_arc].
6304            // The dest input slot is intentionally absent — the kernel
6305            // doesn't read from dest; it only writes to its bytes
6306            // through the output slot's write lock.
6307            let input_arcs = vec![source_arc_contig];
6308            let mut output_arcs = vec![dest_arc.clone()];
6309            let kernel_layouts = vec![source_layout_kernel, dest_layout.clone()];
6310            // A4b-1: defer the wait — return the handle to the realize loop.
6311            let handle = execute_compiled_with_wait_hint(
6312                compiled,
6313                &input_arcs,
6314                &mut output_arcs,
6315                &kernel_layouts,
6316                will_be_waited,
6317            )?;
6318            // Adopt the dest Arc at this WriteSlice node's slot. The
6319            // realize loop's destructive_input cleanup evicts the
6320            // dest's own NodeId from the cache afterward — downstream
6321            // readers go through this node's NodeId.
6322            cache.insert(item.node_id, dest_arc);
6323            layout_cache.insert(item.node_id, item.output_layout.clone());
6324            Ok(handle)
6325        }
6326        WorkItemKind::WriteSliceRotating {
6327            dest,
6328            source,
6329            position,
6330        } => {
6331            // Same shape as WriteSlice but with a position input.
6332            // Kernel sees `[source, position]` as inputs; `dest` is the
6333            // pre-allocated output buffer (in-place adoption).
6334            let compiled = item.compiled.as_ref().ok_or_else(|| {
6335                Error::Msg(format!(
6336                    "PipelinedExecutor: WriteSliceRotating work item {:?} has no compiled node",
6337                    item.node_id,
6338                ))
6339                .bt()
6340            })?;
6341            let dest_arc = cache.get(dest).cloned().ok_or_else(|| {
6342                Error::Msg(format!(
6343                    "PipelinedExecutor: WriteSliceRotating destination {:?} of {:?} not realized",
6344                    dest, item.node_id,
6345                ))
6346                .bt()
6347            })?;
6348            let source_arc = cache.get(source).cloned().ok_or_else(|| {
6349                Error::Msg(format!(
6350                    "PipelinedExecutor: WriteSliceRotating source {:?} of {:?} not realized",
6351                    source, item.node_id,
6352                ))
6353                .bt()
6354            })?;
6355            let position_arc = cache.get(position).cloned().ok_or_else(|| {
6356                Error::Msg(format!(
6357                    "PipelinedExecutor: WriteSliceRotating position {:?} of {:?} not realized",
6358                    position, item.node_id,
6359                ))
6360                .bt()
6361            })?;
6362            let dest_layout = layout_cache.get(dest).cloned().ok_or_else(|| {
6363                Error::Msg(format!(
6364                    "PipelinedExecutor: WriteSliceRotating destination {:?} of {:?} has no cached layout",
6365                    dest, item.node_id,
6366                ))
6367                .bt()
6368            })?;
6369            let source_layout = layout_cache.get(source).cloned().ok_or_else(|| {
6370                Error::Msg(format!(
6371                    "PipelinedExecutor: WriteSliceRotating source {:?} of {:?} has no cached layout",
6372                    source, item.node_id,
6373                ))
6374                .bt()
6375            })?;
6376            // v1: destination contiguous + zero offset (same as WriteSlice).
6377            if !dest_layout.is_contiguous() || dest_layout.start_offset() != 0 {
6378                return Err(Error::Msg(format!(
6379                    "Op::WriteSliceRotating (v1): destination {:?} must be \
6380                     contiguous + zero-offset; got Layout {:?}",
6381                    dest, dest_layout,
6382                ))
6383                .bt());
6384            }
6385            let source_arc_contig = {
6386                let s_dtype = source_arc
6387                    .read()
6388                    .map_err(|_| poisoned("WriteSliceRotating source storage"))?
6389                    .dtype;
6390                let s_len_bytes = source_arc
6391                    .read()
6392                    .map_err(|_| poisoned("WriteSliceRotating source storage"))?
6393                    .inner
6394                    .len_bytes();
6395                let layout_bytes = source_layout.shape().elem_count() * s_dtype.size_in_bytes();
6396                let bytes_match_shape = s_len_bytes == layout_bytes;
6397                let already_contig = source_layout.is_contiguous()
6398                    && source_layout.start_offset() == 0
6399                    && bytes_match_shape;
6400                if already_contig {
6401                    source_arc
6402                } else {
6403                    auto_contiguize(&source_arc, &source_layout)?
6404                }
6405            };
6406            let source_layout_kernel = fuel_ir::Layout::contiguous(source_layout.shape().clone());
6407            let position_layout = fuel_ir::Layout::contiguous(fuel_ir::Shape::from_dims(&[]));
6408            let input_arcs = vec![source_arc_contig, position_arc];
6409            let mut output_arcs = vec![dest_arc.clone()];
6410            let kernel_layouts = vec![source_layout_kernel, position_layout, dest_layout.clone()];
6411            // A4b-1: defer the wait — return the handle to the realize loop.
6412            let handle = execute_compiled_with_wait_hint(
6413                compiled,
6414                &input_arcs,
6415                &mut output_arcs,
6416                &kernel_layouts,
6417                will_be_waited,
6418            )?;
6419            cache.insert(item.node_id, dest_arc);
6420            layout_cache.insert(item.node_id, item.output_layout.clone());
6421            Ok(handle)
6422        }
6423        WorkItemKind::WriteSliceDoff {
6424            dest,
6425            source,
6426            offset,
6427        } => {
6428            // Same shape as WriteSliceRotating: kernel sees
6429            // `[source, offset]` as inputs; `dest` is the pre-allocated
6430            // output buffer (in-place adoption). The offset (rank-0
6431            // I64) is passed through as a kernel input — the CUDA
6432            // wrapper threads its device pointer straight to the kernel
6433            // (no D2H), which is what makes a captured graph replay at
6434            // the host-updated position.
6435            let compiled = item.compiled.as_ref().ok_or_else(|| {
6436                Error::Msg(format!(
6437                    "PipelinedExecutor: WriteSliceDoff work item {:?} has no compiled node",
6438                    item.node_id,
6439                ))
6440                .bt()
6441            })?;
6442            let dest_arc = cache.get(dest).cloned().ok_or_else(|| {
6443                Error::Msg(format!(
6444                    "PipelinedExecutor: WriteSliceDoff destination {:?} of {:?} not realized",
6445                    dest, item.node_id,
6446                ))
6447                .bt()
6448            })?;
6449            let source_arc = cache.get(source).cloned().ok_or_else(|| {
6450                Error::Msg(format!(
6451                    "PipelinedExecutor: WriteSliceDoff source {:?} of {:?} not realized",
6452                    source, item.node_id,
6453                ))
6454                .bt()
6455            })?;
6456            let offset_arc = cache.get(offset).cloned().ok_or_else(|| {
6457                Error::Msg(format!(
6458                    "PipelinedExecutor: WriteSliceDoff offset {:?} of {:?} not realized",
6459                    offset, item.node_id,
6460                ))
6461                .bt()
6462            })?;
6463            let dest_layout = layout_cache.get(dest).cloned().ok_or_else(|| {
6464                Error::Msg(format!(
6465                    "PipelinedExecutor: WriteSliceDoff destination {:?} of {:?} has no cached layout",
6466                    dest, item.node_id,
6467                ))
6468                .bt()
6469            })?;
6470            let source_layout = layout_cache.get(source).cloned().ok_or_else(|| {
6471                Error::Msg(format!(
6472                    "PipelinedExecutor: WriteSliceDoff source {:?} of {:?} has no cached layout",
6473                    source, item.node_id,
6474                ))
6475                .bt()
6476            })?;
6477            // v1: destination contiguous + zero offset (same as WriteSlice).
6478            if !dest_layout.is_contiguous() || dest_layout.start_offset() != 0 {
6479                return Err(Error::Msg(format!(
6480                    "Op::WriteSliceDoff (v1): destination {:?} must be \
6481                     contiguous + zero-offset; got Layout {:?}",
6482                    dest, dest_layout,
6483                ))
6484                .bt());
6485            }
6486            let source_arc_contig = {
6487                let s_dtype = source_arc
6488                    .read()
6489                    .map_err(|_| poisoned("WriteSliceDoff source storage"))?
6490                    .dtype;
6491                let s_len_bytes = source_arc
6492                    .read()
6493                    .map_err(|_| poisoned("WriteSliceDoff source storage"))?
6494                    .inner
6495                    .len_bytes();
6496                let layout_bytes = source_layout.shape().elem_count() * s_dtype.size_in_bytes();
6497                let bytes_match_shape = s_len_bytes == layout_bytes;
6498                let already_contig = source_layout.is_contiguous()
6499                    && source_layout.start_offset() == 0
6500                    && bytes_match_shape;
6501                if already_contig {
6502                    source_arc
6503                } else {
6504                    auto_contiguize(&source_arc, &source_layout)?
6505                }
6506            };
6507            let source_layout_kernel = fuel_ir::Layout::contiguous(source_layout.shape().clone());
6508            let offset_layout = fuel_ir::Layout::contiguous(fuel_ir::Shape::from_dims(&[]));
6509            let input_arcs = vec![source_arc_contig, offset_arc];
6510            let mut output_arcs = vec![dest_arc.clone()];
6511            let kernel_layouts = vec![source_layout_kernel, offset_layout, dest_layout.clone()];
6512            // A4b-1: defer the wait — return the handle to the realize loop.
6513            let handle = execute_compiled_with_wait_hint(
6514                compiled,
6515                &input_arcs,
6516                &mut output_arcs,
6517                &kernel_layouts,
6518                will_be_waited,
6519            )?;
6520            cache.insert(item.node_id, dest_arc);
6521            layout_cache.insert(item.node_id, item.output_layout.clone());
6522            Ok(handle)
6523        }
6524        WorkItemKind::Alloc { target_location } => {
6525            // Op::Alloc { target }: allocate a fresh, zero-init storage
6526            // on target_location. No inputs, no kernel call — direct
6527            // executor dispatch. For non-CPU targets the per-backend
6528            // device handle comes from the `DeviceRegistry` the caller
6529            // handed the realize (a `*_with_devices` entry point).
6530            // Used only by the Vulkan arm below (alloc_bytes_handle); a
6531            // default-feature build sees it unused. GAP-229: 68161981's
6532            // unused_variables --fix renamed it `_n_bytes` at default
6533            // features and broke `--features vulkan` (E0425). Guard the
6534            // decline instead of the name so the binding stays usable.
6535            #[cfg_attr(not(feature = "vulkan"), allow(unused_variables))]
6536            let n_bytes = item.elem_count * item.dtype.size_in_bytes();
6537            let alloced: Storage = match target_location {
6538                // CPU has no separate uninit alloc primitive in safe
6539                // Rust (`vec![0; n]` is the canonical path). Op::Alloc
6540                // on CPU returns zero-init storage; the following
6541                // Op::ZeroFill is a redundant memset the optimizer
6542                // can elide and LLVM folds away regardless.
6543                DeviceLocation::Cpu => fuel_memory::alloc_cpu_zeroed(item.dtype, item.elem_count)?,
6544                #[cfg(feature = "cuda")]
6545                DeviceLocation::Cuda { gpu_id } => {
6546                    let cuda_dev = devices.cuda(*gpu_id).ok_or_else(|| {
6547                        Error::Msg(format!(
6548                            "Op::Alloc on Cuda {{ gpu_id: {} }}: no CUDA \
6549                             device registered for this place. Hand the device to \
6550                             the realize in a `DeviceRegistry` (a `*_with_devices` \
6551                             entry point).",
6552                            gpu_id,
6553                        ))
6554                        .bt()
6555                    })?;
6556                    // Phase 3a follow-up: true uninit alloc via
6557                    // baracuda alpha.30's unsafe alloc. The bytes are
6558                    // uninit until a subsequent Op::ZeroFill or full-
6559                    // overwrite op runs. The byte-storage Arc has no
6560                    // typed-slice accessor that would dereference
6561                    // uninit bytes.
6562                    let cuda_bytes =
6563                        fuel_cuda_backend::CudaStorageBytes::alloc_uninit(&cuda_dev, n_bytes)?;
6564                    Storage::new(fuel_memory::BackendStorage::Cuda(cuda_bytes), item.dtype)
6565                }
6566                #[cfg(not(feature = "cuda"))]
6567                DeviceLocation::Cuda { .. } => {
6568                    return Err(Error::Msg(
6569                        "Op::Alloc on Cuda but fuel-storage wasn't built \
6570                         with --features cuda"
6571                            .to_string(),
6572                    )
6573                    .bt());
6574                }
6575                #[cfg(feature = "vulkan")]
6576                DeviceLocation::Vulkan { gpu_id } => {
6577                    let backend = devices.vulkan(*gpu_id).ok_or_else(|| {
6578                        Error::Msg(format!(
6579                            "Op::Alloc on Vulkan {{ gpu_id: {} }}: no Vulkan \
6580                             device registered for this place. Hand the device to \
6581                             the realize in a `DeviceRegistry` (a `*_with_devices` \
6582                             entry point).",
6583                            gpu_id,
6584                        ))
6585                        .bt()
6586                    })?;
6587                    // Phase 3a follow-up: true uninit alloc. The old
6588                    // `upload_bytes_handle(vec![0u8; n])` host-staged
6589                    // zeros (~2× the bandwidth of a device-side fill);
6590                    // we now allocate uninit and rely on a paired
6591                    // Op::ZeroFill (vkCmdFillBuffer) for the
6592                    // initialization. Faster KV-cache init on Vulkan.
6593                    let vk_bytes = backend.alloc_bytes_handle(n_bytes)?;
6594                    Storage::new(fuel_memory::BackendStorage::Vulkan(vk_bytes), item.dtype)
6595                }
6596                #[cfg(not(feature = "vulkan"))]
6597                DeviceLocation::Vulkan { .. } => {
6598                    return Err(Error::Msg(
6599                        "Op::Alloc on Vulkan but fuel-storage wasn't built \
6600                         with --features vulkan"
6601                            .to_string(),
6602                    )
6603                    .bt());
6604                }
6605                other => {
6606                    return Err(Error::Msg(format!(
6607                        "Op::Alloc on {:?}: target not yet wired (CPU + \
6608                         CUDA + Vulkan land in Phase 3a of bridge-retirement; \
6609                         Metal extends when its byte-storage substrate is \
6610                         ready).",
6611                        other,
6612                    ))
6613                    .bt());
6614                }
6615            };
6616            cache.insert(item.node_id, Arc::new(RwLock::new(alloced)));
6617            layout_cache.insert(item.node_id, item.output_layout.clone());
6618            Ok(CompletionHandle::Ready)
6619        }
6620        WorkItemKind::Iota {
6621            len,
6622            target_location,
6623        } => {
6624            // Op::Iota { len }: 0-input F32 position generator
6625            // [0.0, 1.0, …, (len-1)]. Direct executor dispatch (no kernel /
6626            // binding-table lookup), like WorkItemKind::Alloc. Generated on the host, then, for a
6627            // CUDA target, uploaded (an Iota is a tiny index constant: a device kernel would cost a
6628            // launch to save a few hundred bytes of transfer). The decomposed PAGED_ATTN recipe
6629            // (GAP-380) is the CUDA consumer; a build without the `cuda` feature, or any other
6630            // non-CPU backend, still errors rather than guessing.
6631            #[cfg(feature = "cuda")]
6632            if item.target_backend == BackendId::Cuda {
6633                let gpu_id = match target_location {
6634                    Some(DeviceLocation::Cuda { gpu_id }) => *gpu_id,
6635                    _ => 0,
6636                };
6637                let cuda_dev = devices.cuda(gpu_id).ok_or_else(|| {
6638                    Error::Msg(format!(
6639                        "Op::Iota on Cuda {{ gpu_id: {gpu_id} }}: no CUDA device registered for                          this place. Hand the device to the realize via a `*_with_devices` entry point."
6640                    ))
6641                    .bt()
6642                })?;
6643                let bytes: Vec<u8> = (0..*len).flat_map(|i| (i as f32).to_le_bytes()).collect();
6644                let cuda_bytes =
6645                    fuel_cuda_backend::CudaStorageBytes::from_cpu_bytes(&cuda_dev, &bytes)?;
6646                let st = Storage::new(fuel_memory::BackendStorage::Cuda(cuda_bytes), item.dtype);
6647                cache.insert(item.node_id, Arc::new(RwLock::new(st)));
6648                layout_cache.insert(item.node_id, item.output_layout.clone());
6649                return Ok(CompletionHandle::Ready);
6650            }
6651            #[cfg(not(feature = "cuda"))]
6652            let _ = target_location;
6653            if item.target_backend != BackendId::Cpu {
6654                return Err(Error::Msg(format!(
6655                    "WorkItemKind::Iota: only CPU is wired today, got {:?}",
6656                    item.target_backend,
6657                ))
6658                .bt());
6659            }
6660            let v: Vec<f32> = (0..*len).map(|i| i as f32).collect();
6661            let iota = fuel_memory::from_slice_cpu(&v);
6662            cache.insert(item.node_id, Arc::new(RwLock::new(iota)));
6663            layout_cache.insert(item.node_id, item.output_layout.clone());
6664            Ok(CompletionHandle::Ready)
6665        }
6666        WorkItemKind::ZeroFill => {
6667            // Op::ZeroFill: in-place zero the input's bytes. Output
6668            // adopts the input's Storage Arc (same Storage; bytes
6669            // are mutated). Direct per-backend dispatch — no kernel
6670            // call, no binding-table lookup.
6671            if item.inputs.len() != 1 {
6672                return Err(Error::Msg(format!(
6673                    "PipelinedExecutor: ZeroFill work item {:?} expects \
6674                     1 input, got {}",
6675                    item.node_id,
6676                    item.inputs.len(),
6677                ))
6678                .bt());
6679            }
6680            let src_id = item.inputs[0];
6681            let src_arc = cache.get(&src_id).cloned().ok_or_else(|| {
6682                Error::Msg(format!(
6683                    "PipelinedExecutor: ZeroFill input {:?} of {:?} \
6684                     not realized",
6685                    src_id, item.node_id,
6686                ))
6687                .bt()
6688            })?;
6689            // Per-backend in-place fill. Acquired the write lock once
6690            // for the duration of the fill — kernels on async backends
6691            // (CUDA / Vulkan) issue the memset and return; the fence
6692            // happens when downstream readers acquire the read lock
6693            // through the executor's standard synchronization path.
6694            {
6695                let mut guard = src_arc
6696                    .write()
6697                    .map_err(|_| poisoned("ZeroFill destination storage"))?;
6698                match &mut guard.inner {
6699                    fuel_memory::BackendStorage::Cpu(c) => {
6700                        let bytes = c.bytes_mut();
6701                        bytes.fill(0);
6702                    }
6703                    #[cfg(feature = "cuda")]
6704                    fuel_memory::BackendStorage::Cuda(c) => {
6705                        c.zero_async()?;
6706                    }
6707                    #[cfg(feature = "vulkan")]
6708                    fuel_memory::BackendStorage::Vulkan(v) => {
6709                        let backend = v
6710                            .backend()
6711                            .ok_or_else(|| {
6712                                Error::Msg(
6713                                    "Op::ZeroFill on Vulkan: input has no \
6714                                 attached backend handle. Storage must \
6715                                 come from VulkanBackend::alloc_bytes_handle \
6716                                 / upload_bytes_handle."
6717                                        .to_string(),
6718                                )
6719                                .bt()
6720                            })?
6721                            .clone();
6722                        backend.fill_bytes_zero(v)?;
6723                    }
6724                    #[allow(unreachable_patterns)]
6725                    other => {
6726                        return Err(Error::Msg(format!(
6727                            "Op::ZeroFill: backend not wired ({other:?}); \
6728                             CPU + CUDA + Vulkan covered, Metal extends \
6729                             when its byte-storage substrate is ready.",
6730                        ))
6731                        .bt());
6732                    }
6733                }
6734            }
6735            // Adopt the (now-zero) Storage Arc at this node's slot.
6736            // Downstream readers go through `node_id`; the original
6737            // input's NodeId is evicted from the cache by the
6738            // realize loop's destructive_input cleanup.
6739            cache.insert(item.node_id, src_arc);
6740            layout_cache.insert(item.node_id, item.output_layout.clone());
6741            // A4b-1: ZeroFill's CUDA memset is same-stream (and Op::Alloc
6742            // typically zero-inits, so this is usually elided). Its completion
6743            // is carried by the realize-end full-stream sync in `to_cpu_bytes`
6744            // (unchanged) and same-stream ordering — `Ready` is behavior-preserving.
6745            Ok(CompletionHandle::Ready)
6746        }
6747        WorkItemKind::Copy { target_location } | WorkItemKind::Move { target_location } => {
6748            // Op::Copy / Op::Move { target }: kernel lookup at
6749            // (OpKind::Copy, [dt, dt], source_backend) — the wrapper
6750            // downloads from its own residency into a freshly-
6751            // allocated output on `target_location`. We auto-
6752            // contiguize the input first so the kernel always sees
6753            // the logical view's bytes (a transpose-view source
6754            // materializes into a contiguous buffer before download).
6755            //
6756            // Move shares this entire data-movement half; its
6757            // destructive half (release the source) is driven by the
6758            // realize loop's `destructive_input` cleanup after this
6759            // arm returns — see `WorkItemKind::Move`.
6760            let op_label = if matches!(item.kind, WorkItemKind::Move { .. }) {
6761                "Move"
6762            } else {
6763                "Copy"
6764            };
6765            let compiled = item.compiled.as_ref().ok_or_else(|| {
6766                Error::Msg(format!(
6767                    "PipelinedExecutor: {op_label} work item {:?} has no compiled node",
6768                    item.node_id,
6769                ))
6770                .bt()
6771            })?;
6772            if item.inputs.len() != 1 {
6773                return Err(Error::Msg(format!(
6774                    "PipelinedExecutor: {op_label} work item {:?} expects 1 input, got {}",
6775                    item.node_id,
6776                    item.inputs.len(),
6777                ))
6778                .bt());
6779            }
6780            let src_id = item.inputs[0];
6781            let src_arc = cache.get(&src_id).cloned().ok_or_else(|| {
6782                Error::Msg(format!(
6783                    "PipelinedExecutor: {op_label} input {:?} of {:?} not realized",
6784                    src_id, item.node_id,
6785                ))
6786                .bt()
6787            })?;
6788            // Multi-output Option C guard: Op::Copy on a bundled
6789            // producer would silently drop the bundle metadata on
6790            // the destination, and the auto-contiguize step below
6791            // would treat the bundle as a flat slot-0-shaped buffer
6792            // and corrupt non-primary slots. Until the per-backend
6793            // whole-bundle-Copy hook lands, point callers at the
6794            // supported per-slot path:
6795            // Op::View → Op::Copy → Op::ViewOwned.
6796            //
6797            // Exception: when the immediate input is an Op::View
6798            // projection (its layout's byte extent is strictly less
6799            // than the bundle's total bytes), the View has already
6800            // narrowed the slab. auto-contiguize walks the View's
6801            // layout and produces a flat slot-shaped buffer that's
6802            // correctly sized — no data loss, no slot corruption.
6803            // The guard only fires when the Copy targets the bundle
6804            // root directly.
6805            {
6806                let guard = src_arc
6807                    .read()
6808                    .map_err(|_| poisoned("Copy source storage"))?;
6809                if guard.is_bundled() {
6810                    let layout_bytes_for_guard = layout_cache
6811                        .get(&src_id)
6812                        .map(|l| l.shape().elem_count() * guard.dtype.size_in_bytes())
6813                        .unwrap_or(usize::MAX);
6814                    let bundle_bytes = guard.inner.len_bytes();
6815                    let is_whole_bundle = layout_bytes_for_guard >= bundle_bytes;
6816                    if is_whole_bundle {
6817                        return Err(Error::Msg(format!(
6818                            "PipelinedExecutor: Op::{op_label} on a bundled producer \
6819                             ({:?}) is not yet supported (Option C followup). \
6820                             Use Op::View → Op::Copy → Op::ViewOwned for \
6821                             per-slot cross-device moves, or wait for the \
6822                             per-backend whole-bundle-Copy hook.",
6823                            src_id,
6824                        ))
6825                        .bt());
6826                    }
6827                }
6828            }
6829            let src_layout = layout_cache.get(&src_id).cloned().ok_or_else(|| {
6830                Error::Msg(format!(
6831                    "PipelinedExecutor: {op_label} input {:?} of {:?} has no cached layout",
6832                    src_id, item.node_id,
6833                ))
6834                .bt()
6835            })?;
6836            let src_dtype = src_arc
6837                .read()
6838                .map_err(|_| poisoned("Copy source storage"))?
6839                .dtype;
6840            let src_len_bytes = src_arc
6841                .read()
6842                .map_err(|_| poisoned("Copy source storage"))?
6843                .inner
6844                .len_bytes();
6845            let layout_bytes = src_layout.shape().elem_count() * src_dtype.size_in_bytes();
6846            let bytes_match_shape = src_len_bytes == layout_bytes;
6847            let already_contig =
6848                src_layout.is_contiguous() && src_layout.start_offset() == 0 && bytes_match_shape;
6849            let src_input = if already_contig {
6850                src_arc
6851            } else {
6852                auto_contiguize(&src_arc, &src_layout)?
6853            };
6854            let kernel_input_layout = fuel_ir::Layout::contiguous(src_layout.shape().clone());
6855            // CapturedRun build-out (4b-ζ): in Reuse (capture/replay) mode,
6856            // reuse the fixed-address buffer recorded during the warm run
6857            // instead of allocating — device allocation is illegal inside a
6858            // capture scope. Only a same-device CUDA target_location ever
6859            // reaches Reuse mode for a Copy node in practice: capture_decode's
6860            // validation loop rejects every Cpu/Vulkan target_location before
6861            // a capture scope is ever entered (Move is rejected unconditionally
6862            // there too), so this arm trusts that invariant rather than
6863            // re-deriving it — the `DeviceLocation::Cuda` guard below is just
6864            // belt-and-suspenders for any other Reuse-mode caller.
6865            let reuse_arc = match &persistent {
6866                Some(p) if p.mode == PersistentMode::Reuse => match target_location {
6867                    DeviceLocation::Cuda { .. } => p.map.get(&item.node_id).cloned(),
6868                    _ => None,
6869                },
6870                _ => None,
6871            };
6872            // Allocate the output on `target_location`. Phase 2
6873            // covered D2H (target=Cpu); Phase 3b extends to H2D
6874            // (target=Cuda / Vulkan from a CPU source). For non-CPU
6875            // targets the device handle comes from the caller's
6876            // `DeviceRegistry` (a `*_with_devices` entry point), as for
6877            // Op::Alloc.
6878            // Used only by the Vulkan arm below (alloc_bytes_handle); a
6879            // default-feature build sees it unused. GAP-229: 68161981's
6880            // unused_variables --fix renamed it `_n_bytes` at default
6881            // features and broke `--features vulkan` (E0425). Guard the
6882            // decline instead of the name so the binding stays usable.
6883            #[cfg_attr(not(feature = "vulkan"), allow(unused_variables))]
6884            let n_bytes = item.elem_count * item.dtype.size_in_bytes();
6885            let input_arcs = vec![src_input];
6886            let mut output_arcs = if let Some(arc) = reuse_arc {
6887                vec![arc]
6888            } else {
6889                let output = match target_location {
6890                    DeviceLocation::Cpu => {
6891                        fuel_memory::alloc_cpu_zeroed(item.dtype, item.elem_count)?
6892                    }
6893                    #[cfg(feature = "cuda")]
6894                    DeviceLocation::Cuda { gpu_id } => {
6895                        let cuda_dev = devices.cuda(*gpu_id).ok_or_else(|| {
6896                            Error::Msg(format!(
6897                                "Op::{op_label} on Cuda {{ gpu_id: {} }}: no CUDA \
6898                                 device registered for this place. Hand the device to \
6899                                 the realize in a `DeviceRegistry` (a `*_with_devices` \
6900                                 entry point) before an H2D Op::{op_label}.",
6901                                gpu_id,
6902                            ))
6903                            .bt()
6904                        })?;
6905                        let cuda_bytes =
6906                            fuel_cuda_backend::CudaStorageBytes::alloc_uninit(&cuda_dev, n_bytes)?;
6907                        Storage::new(fuel_memory::BackendStorage::Cuda(cuda_bytes), item.dtype)
6908                    }
6909                    #[cfg(not(feature = "cuda"))]
6910                    DeviceLocation::Cuda { .. } => {
6911                        return Err(Error::Msg(format!(
6912                            "Op::{op_label} target Cuda but fuel-storage wasn't built \
6913                             with --features cuda",
6914                        ))
6915                        .bt());
6916                    }
6917                    #[cfg(feature = "vulkan")]
6918                    DeviceLocation::Vulkan { gpu_id } => {
6919                        let backend = devices.vulkan(*gpu_id).ok_or_else(|| {
6920                            Error::Msg(format!(
6921                                "Op::{op_label} on Vulkan {{ gpu_id: {} }}: no Vulkan \
6922                                 device registered for this place. Hand the device to \
6923                                 the realize in a `DeviceRegistry` (a `*_with_devices` \
6924                                 entry point) before an H2D Op::{op_label}.",
6925                                gpu_id,
6926                            ))
6927                            .bt()
6928                        })?;
6929                        let vk_bytes = backend.alloc_bytes_handle(n_bytes)?;
6930                        Storage::new(fuel_memory::BackendStorage::Vulkan(vk_bytes), item.dtype)
6931                    }
6932                    #[cfg(not(feature = "vulkan"))]
6933                    DeviceLocation::Vulkan { .. } => {
6934                        return Err(Error::Msg(format!(
6935                            "Op::{op_label} target Vulkan but fuel-storage wasn't built \
6936                             with --features vulkan",
6937                        ))
6938                        .bt());
6939                    }
6940                    other => {
6941                        return Err(Error::Msg(format!(
6942                            "PipelinedExecutor: Op::{op_label} target_location {:?} not yet \
6943                             wired (CPU + CUDA + Vulkan covered; Metal extends when \
6944                             its byte-storage substrate is ready).",
6945                            other
6946                        ))
6947                        .bt());
6948                    }
6949                };
6950                vec![Arc::new(RwLock::new(output))]
6951            };
6952            let kernel_layouts = vec![kernel_input_layout, item.output_layout.clone()];
6953            // A4b-1: defer the wait — return the handle to the realize loop.
6954            let handle = execute_compiled_with_wait_hint(
6955                compiled,
6956                &input_arcs,
6957                &mut output_arcs,
6958                &kernel_layouts,
6959                will_be_waited,
6960            )?;
6961            let arc = output_arcs.into_iter().next().expect("one output");
6962            // CapturedRun build-out (4b-ζ): Record (warm) mode remembers this
6963            // node's fixed output buffer so the capture run reuses the
6964            // identical device address. No-op in Reuse mode (the buffer came
6965            // FROM the map) and in None mode. Mirrors the Kernel arm's
6966            // Record-mode snapshot (above) exactly.
6967            if let Some(p) = persistent.as_deref_mut()
6968                && p.mode == PersistentMode::Record
6969            {
6970                p.map.insert(item.node_id, Arc::clone(&arc));
6971            }
6972            cache.insert(item.node_id, arc);
6973            layout_cache.insert(item.node_id, item.output_layout.clone());
6974            Ok(handle)
6975        }
6976        WorkItemKind::ReleaseMarker => {
6977            // Emit a zero-byte CPU storage at the Release node's
6978            // slot. Per Op::Release's contract the marker is never
6979            // read — this exists so any downstream cache lookup of
6980            // `release_id` resolves rather than failing. The actual
6981            // deallocation of `inputs[0]` is driven by the realize
6982            // loop's `destructive_input` cleanup (Phase B).
6983            let marker = fuel_memory::alloc_cpu_zeroed(item.dtype, 0)?;
6984            cache.insert(item.node_id, Arc::new(RwLock::new(marker)));
6985            layout_cache.insert(item.node_id, item.output_layout.clone());
6986            Ok(CompletionHandle::Ready)
6987        }
6988        WorkItemKind::ContiguizeOf { input } => {
6989            let input_arc = cache.get(input).cloned().ok_or_else(|| {
6990                Error::Msg(format!(
6991                    "PipelinedExecutor: reshape input {:?} of {:?} not realized",
6992                    input, item.node_id,
6993                ))
6994                .bt()
6995            })?;
6996            let input_layout = layout_cache.get(input).cloned().ok_or_else(|| {
6997                Error::Msg(format!(
6998                    "PipelinedExecutor: reshape input {:?} of {:?} has no cached layout",
6999                    input, item.node_id,
7000                ))
7001                .bt()
7002            })?;
7003            // CapturedRun build-out (4b-γ): in Reuse (capture/replay) mode,
7004            // reuse the fixed-address buffer recorded during the warm run —
7005            // device allocation is illegal inside a capture scope. Always
7006            // write-into when reusing (skip the zero-copy-vs-allocate
7007            // branch entirely): a given ContiguizeOf node's zero-copy-ness
7008            // is a static layout/stride property, identical across the warm
7009            // and capture passes (both replay the same compiled item list
7010            // with the same static layouts per capture_decode's own
7011            // design), so if this node ever needed the map entry it
7012            // allocated on warm too and the entry is guaranteed present.
7013            let reuse_arc = match &persistent {
7014                Some(p) if p.mode == PersistentMode::Reuse => p.map.get(&item.node_id).cloned(),
7015                _ => None,
7016            };
7017            let out_arc = if let Some(dest_arc) = reuse_arc {
7018                contiguize_into(&dest_arc, &input_arc, &input_layout)?;
7019                dest_arc
7020            } else if input_layout.is_contiguous() && input_layout.start_offset() == 0 {
7021                // Zero-copy when the input is already contiguous + zero
7022                // offset — never allocates, so Record mode has nothing to
7023                // record for this node (no fixed address to reuse).
7024                input_arc
7025            } else {
7026                // Allocate + copy via the contiguize kernel.
7027                let arc = auto_contiguize(&input_arc, &input_layout)?;
7028                if let Some(p) = persistent.as_deref_mut()
7029                    && p.mode == PersistentMode::Record
7030                {
7031                    p.map.insert(item.node_id, Arc::clone(&arc));
7032                }
7033                arc
7034            };
7035            cache.insert(item.node_id, out_arc);
7036            layout_cache.insert(item.node_id, item.output_layout.clone());
7037            // A4b-1: a materializing contiguize (CUDA) is same-stream; its
7038            // completion is carried by the realize-end full-stream sync in
7039            // `to_cpu_bytes` (unchanged) — `Ready` here is behavior-preserving.
7040            Ok(CompletionHandle::Ready)
7041        }
7042        WorkItemKind::Kernel => {
7043            let compiled = item.compiled.as_ref().ok_or_else(|| {
7044                Error::Msg(format!(
7045                    "PipelinedExecutor: Kernel work item {:?} has no compiled node",
7046                    item.node_id,
7047                ))
7048                .bt()
7049            })?;
7050            // Dynamic-M matmul (sparse MoE): resolve a DATA-DETERMINED row
7051            // count from the producer-bound `produced_syms` and run against
7052            // the patched (resolved-M) node. `None` on the common path.
7053            let patched_mm = resolve_deferred_matmul(compiled, produced_syms, item.node_id)?;
7054            let compiled = patched_mm.as_ref().unwrap_or(compiled);
7055            // Gather input Arcs from the cache, auto-contiguizing
7056            // any input whose layout is non-contiguous (typically
7057            // produced by an upstream metadata-only view op).
7058            // Today's kernels assume contiguous; this pass keeps
7059            // that invariant true at every kernel call site.
7060            //
7061            // We assemble a parallel `kernel_layouts` vec — the layout
7062            // of the bytes the kernel actually receives. After
7063            // auto-contiguize, that's `Layout::contiguous(shape)` for
7064            // the input's shape; for inputs already contiguous we use
7065            // the cached layout directly. Output layout comes last.
7066            let mut input_arcs: Vec<Arc<RwLock<Storage>>> = Vec::with_capacity(item.inputs.len());
7067            let mut kernel_layouts: Vec<fuel_ir::Layout> =
7068                Vec::with_capacity(item.inputs.len() + 1);
7069            // The kernel's `strided_input` cap lets non-contiguous
7070            // inputs (broadcast, transpose, etc.) flow through without
7071            // materialization — the kernel walks strides itself. Inputs
7072            // with non-zero `start_offset` still go through auto-
7073            // Contiguize today; offset honoring on the byte buffer is
7074            // a separate concern from stride support.
7075            let kernel_handles_strided = compiled.caps.strided_input;
7076            let t_gather = crate::compiled::op_profile::PhaseTimer::start("kernel.gather_inputs");
7077            for in_id in &item.inputs {
7078                let in_arc = cache.get(in_id).cloned().ok_or_else(|| {
7079                    Error::Msg(format!(
7080                        "PipelinedExecutor: input {:?} of {:?} not realized",
7081                        in_id, item.node_id,
7082                    ))
7083                    .bt()
7084                })?;
7085                let in_layout = layout_cache.get(in_id).cloned().ok_or_else(|| {
7086                    Error::Msg(format!(
7087                        "PipelinedExecutor: input {:?} of {:?} has no cached layout",
7088                        in_id, item.node_id,
7089                    ))
7090                    .bt()
7091                })?;
7092                // "Already contig" means more than `is_contiguous()`:
7093                // the LAYOUT's element count must also match the
7094                // STORAGE's byte count for shape-validating kernels
7095                // (concat_cpu, etc.) that read `storage.len_bytes()`.
7096                // A first-N slice view has `is_contiguous() == true`
7097                // (strides match canonical [1] for shape [N]) but its
7098                // storage is the parent's full bytes — too big. In
7099                // that case we auto-contiguize to materialize only
7100                // the view's portion as a fresh storage.
7101                //
7102                // Same constraint applies to strided_ok: kernels that
7103                // declare strided support can walk strided inputs, but
7104                // the byte count check at the kernel surface still
7105                // assumes storage.len_bytes() == layout.elem_count() *
7106                // dtype.size_bytes(). Until kernels universally trust
7107                // layout over storage, we conservatively materialize.
7108                let in_dtype = in_arc.read().map_err(|_| poisoned("input storage"))?.dtype;
7109                let in_len_bytes = in_arc
7110                    .read()
7111                    .map_err(|_| poisoned("input storage"))?
7112                    .inner
7113                    .len_bytes();
7114                let layout_bytes = in_layout.shape().elem_count() * in_dtype.size_in_bytes();
7115                let bytes_match_shape = in_len_bytes == layout_bytes;
7116                let already_contig =
7117                    in_layout.is_contiguous() && in_layout.start_offset() == 0 && bytes_match_shape;
7118                let strided_ok =
7119                    kernel_handles_strided && in_layout.start_offset() == 0 && bytes_match_shape;
7120                if already_contig || strided_ok {
7121                    input_arcs.push(in_arc);
7122                    kernel_layouts.push(in_layout);
7123                } else {
7124                    let contig_arc = auto_contiguize(&in_arc, &in_layout)?;
7125                    input_arcs.push(contig_arc);
7126                    kernel_layouts.push(fuel_ir::Layout::contiguous(in_layout.shape().clone()));
7127                }
7128            }
7129            drop(t_gather);
7130            kernel_layouts.push(item.output_layout.clone());
7131
7132            // Allocate output on the target backend. For GPU backends
7133            // we derive the device handle from the first input —
7134            // every kernel has ≥1 input (Op::Const is handled via
7135            // ConstAdopt, never via Kernel), and an input on the
7136            // target backend carries its own device. This avoids
7137            // threading a device handle through `realize`.
7138            //
7139            // Multi-output (Option C, item 3): when the WorkItem
7140            // carries an `output_bundle`, size the allocation to
7141            // span every slot's bytes (primary-dtype-element count
7142            // rounded up from the bundle's total byte span) and
7143            // attach the bundle metadata after allocation.
7144            let (alloc_elem_count, bundle_to_attach) = match &item.output_bundle {
7145                Some(bundle) => {
7146                    let dtype_bytes = item.dtype.size_in_bytes().max(1);
7147                    let total_bytes = bundle.iter().fold(0usize, |acc, s| {
7148                        let end = s.byte_offset.saturating_add(s.len_bytes());
7149                        acc.max(end)
7150                    });
7151                    let elems = total_bytes.div_ceil(dtype_bytes);
7152                    (elems, Some(Arc::clone(bundle)))
7153                }
7154                None => (item.elem_count, None),
7155            };
7156            // CapturedRun build-out: in Reuse (capture/replay) mode, reuse the
7157            // FIXED-ADDRESS buffer recorded during the warm run instead of
7158            // allocating — device allocation is illegal inside a capture scope,
7159            // and reusing the same address is what makes the captured graph's
7160            // baked kernel arguments valid on replay. In Record (warm) or None
7161            // mode, allocate as usual (below).
7162            let reuse_arc = match &persistent {
7163                Some(p) if p.mode == PersistentMode::Reuse => {
7164                    Some(p.map.get(&item.node_id).cloned().ok_or_else(|| {
7165                        Error::Msg(format!(
7166                            "PipelinedExecutor: capture (reuse) mode has no persistent \
7167                             output buffer for kernel node {:?}; the warm (record) run \
7168                             must realize every kernel node before capture",
7169                            item.node_id,
7170                        ))
7171                        .bt()
7172                    })?)
7173                }
7174                _ => None,
7175            };
7176            let t_alloc = crate::compiled::op_profile::PhaseTimer::start("kernel.alloc_output");
7177            let mut output_arcs = if let Some(arc) = reuse_arc {
7178                vec![arc]
7179            } else {
7180                let output = match item.target_backend {
7181                    BackendId::Cpu => fuel_memory::alloc_cpu_zeroed(item.dtype, alloc_elem_count)?,
7182                    #[cfg(feature = "cuda")]
7183                    BackendId::Cuda => {
7184                        let first_in = input_arcs.first().ok_or_else(|| {
7185                            Error::Msg(format!(
7186                                "PipelinedExecutor: kernel {:?} on Cuda has no inputs; \
7187                             cannot derive device for output allocation",
7188                                item.node_id,
7189                            ))
7190                            .bt()
7191                        })?;
7192                        let guard = first_in.read().map_err(|_| poisoned("input storage"))?;
7193                        let cuda_in = match &guard.inner {
7194                            fuel_memory::BackendStorage::Cuda(c) => c,
7195                            other => {
7196                                return Err(Error::Msg(format!(
7197                                    "PipelinedExecutor: kernel {:?} target_backend=Cuda but \
7198                                 input has BackendStorage::{:?}; mixed-backend kernels \
7199                                 require an explicit Op::Copy first",
7200                                    item.node_id,
7201                                    other.backend_id(),
7202                                ))
7203                                .bt());
7204                            }
7205                        };
7206                        let n_bytes = alloc_elem_count * item.dtype.size_in_bytes();
7207                        let cuda_bytes =
7208                            fuel_cuda_backend::CudaStorageBytes::alloc(cuda_in.device(), n_bytes)?;
7209                        fuel_memory::Storage::new(
7210                            fuel_memory::BackendStorage::Cuda(cuda_bytes),
7211                            item.dtype,
7212                        )
7213                    }
7214                    #[cfg(feature = "vulkan")]
7215                    BackendId::Vulkan => {
7216                        // Mirror the CUDA path: derive the backend handle
7217                        // from the first input's `VulkanStorageBytes::backend()`.
7218                        // Vulkan catch-up V.1.B (2026-05-21) — requires
7219                        // inputs constructed via `alloc_bytes_handle` /
7220                        // `upload_bytes_handle` so they carry the
7221                        // `Arc<VulkanBackend>` (mirroring CUDA's
7222                        // `Arc<CudaDevice>`).
7223                        let first_in = input_arcs.first().ok_or_else(|| {
7224                            Error::Msg(format!(
7225                                "PipelinedExecutor: kernel {:?} on Vulkan has no inputs; \
7226                             cannot derive backend handle for output allocation",
7227                                item.node_id,
7228                            ))
7229                            .bt()
7230                        })?;
7231                        let guard = first_in.read().map_err(|_| poisoned("input storage"))?;
7232                        let vk_in = match &guard.inner {
7233                            fuel_memory::BackendStorage::Vulkan(v) => v,
7234                            other => {
7235                                return Err(Error::Msg(format!(
7236                                    "PipelinedExecutor: kernel {:?} target_backend=Vulkan but \
7237                                 input has BackendStorage::{:?}; mixed-backend kernels \
7238                                 require an explicit Op::Copy first",
7239                                    item.node_id,
7240                                    other.backend_id(),
7241                                ))
7242                                .bt());
7243                            }
7244                        };
7245                        let backend = vk_in.backend().ok_or_else(|| {
7246                            Error::Msg(format!(
7247                                "PipelinedExecutor: Vulkan kernel {:?} input has no backend \
7248                             handle. Storages flowing through the pipelined executor's \
7249                             Vulkan path must be constructed via \
7250                             VulkanBackend::alloc_bytes_handle / upload_bytes_handle \
7251                             (not the legacy alloc_bytes / upload_bytes which leave \
7252                             VulkanStorageBytes::backend = None).",
7253                                item.node_id,
7254                            ))
7255                            .bt()
7256                        })?;
7257                        let n_bytes = alloc_elem_count * item.dtype.size_in_bytes();
7258                        let vk_bytes = backend.alloc_bytes_handle(n_bytes)?;
7259                        fuel_memory::Storage::new(
7260                            fuel_memory::BackendStorage::Vulkan(vk_bytes),
7261                            item.dtype,
7262                        )
7263                    }
7264                    other => {
7265                        return Err(Error::Msg(format!(
7266                            "PipelinedExecutor: target_backend {:?} output allocation \
7267                         not yet implemented (CPU + CUDA + Vulkan wired; Metal extends later)",
7268                            other
7269                        ))
7270                        .bt());
7271                    }
7272                };
7273                // Attach bundle metadata when this is a multi-output op.
7274                // The kernel sees the allocated bytes; the bundle lives
7275                // at the Storage wrapper level so downstream Op::View /
7276                // Op::ViewOwned can resolve their slot windows.
7277                let output = match bundle_to_attach {
7278                    Some(bundle) => output.with_bundle(bundle)?,
7279                    None => output,
7280                };
7281                vec![Arc::new(RwLock::new(output))]
7282            };
7283            drop(t_alloc);
7284
7285            // A4b-1: defer the wait — return the handle to the realize loop.
7286            let t_launch =
7287                crate::compiled::op_profile::PhaseTimer::start("kernel.execute_compiled");
7288            let handle = execute_compiled_with_wait_hint(
7289                compiled,
7290                &input_arcs,
7291                &mut output_arcs,
7292                &kernel_layouts,
7293                will_be_waited,
7294            )?;
7295            drop(t_launch);
7296
7297            let arc = output_arcs.into_iter().next().expect("one output");
7298
7299            // CapturedRun build-out: Record (warm) mode remembers this node's
7300            // fixed output buffer so the capture run reuses the identical
7301            // device address. No-op in Reuse mode (the buffer came FROM the
7302            // map) and in None mode.
7303            if let Some(p) = persistent
7304                && p.mode == PersistentMode::Record
7305            {
7306                p.map.insert(item.node_id, Arc::clone(&arc));
7307            }
7308
7309            // Data-determined dynamic-shapes seam (increment 2a): a
7310            // producer that computes a runtime count publishes it into the
7311            // per-pass `SymEnv` so downstream ops can consume it as a
7312            // dynamic extent. `Op::NonZeroIndices` writes its count into
7313            // bundle slot 1; read it back and bind `count_sym`. This is the
7314            // FIRST op to bind a *data-determined* symbol mid-realize (all
7315            // prior binds are host-known before realize). Single-threaded:
7316            // the executor runs items topologically, so this bind precedes
7317            // any consumer's execute-time resolution.
7318            if let OpParams::NonZeroIndices {
7319                capacity,
7320                count_sym,
7321            } = &compiled.op_params
7322            {
7323                bind_data_determined_count(&arc, *capacity, *count_sym, produced_syms)?;
7324            }
7325
7326            cache.insert(item.node_id, arc);
7327            layout_cache.insert(item.node_id, item.output_layout.clone());
7328            Ok(handle)
7329        }
7330        WorkItemKind::InplaceKernel { target_idx } => {
7331            let compiled = item.compiled.as_ref().ok_or_else(|| {
7332                Error::Msg(format!(
7333                    "PipelinedExecutor: InplaceKernel work item {:?} has no compiled node",
7334                    item.node_id,
7335                ))
7336                .bt()
7337            })?;
7338            let target_id = *item.inputs.get(*target_idx).ok_or_else(|| {
7339                Error::Msg(format!(
7340                    "PipelinedExecutor: InplaceKernel work item {:?} target_idx={} \
7341                     out of bounds (inputs.len()={})",
7342                    item.node_id,
7343                    target_idx,
7344                    item.inputs.len(),
7345                ))
7346                .bt()
7347            })?;
7348            let target_arc = cache.get(&target_id).cloned().ok_or_else(|| {
7349                Error::Msg(format!(
7350                    "PipelinedExecutor: InplaceKernel target {:?} of {:?} not realized",
7351                    target_id, item.node_id,
7352                ))
7353                .bt()
7354            })?;
7355            let target_layout = layout_cache.get(&target_id).cloned().ok_or_else(|| {
7356                Error::Msg(format!(
7357                    "PipelinedExecutor: InplaceKernel target {:?} of {:?} has no cached layout",
7358                    target_id, item.node_id,
7359                ))
7360                .bt()
7361            })?;
7362            // v1 contract: target must be contiguous + zero offset.
7363            // Strided in-place targets would force the kernel to walk
7364            // strides for writes too; defer until a concrete consumer
7365            // needs it (mirrors `Op::WriteSlice`'s v1 dest contract).
7366            if !target_layout.is_contiguous() || target_layout.start_offset() != 0 {
7367                return Err(Error::Msg(format!(
7368                    "InplaceKernel (Phase 3 v1): target {:?} must be contiguous + \
7369                     zero-offset; got Layout {:?}",
7370                    target_id, target_layout,
7371                ))
7372                .bt());
7373            }
7374            // Kernel sees inputs=[non-target IR inputs in order] and
7375            // outputs=[target_arc]. For unary in-place (1 IR input at
7376            // target_idx=0) the input vec is empty, matching the
7377            // original Phase 3e contract. For binary in-place
7378            // (target_idx=0, 2 IR inputs) the wrapper sees the
7379            // non-destructive RHS as `inputs[0]`. The wrapper acquires
7380            // outputs[0]'s write lock and mutates through its
7381            // bytes_mut(). Layout vector contains the kernel's
7382            // inputs+outputs layouts in that order.
7383            let mut input_arcs: Vec<Arc<RwLock<Storage>>> = Vec::new();
7384            let mut kernel_layouts: Vec<Layout> = Vec::new();
7385            for (i, &input_id) in item.inputs.iter().enumerate() {
7386                if i == *target_idx {
7387                    continue;
7388                }
7389                let arc = cache.get(&input_id).cloned().ok_or_else(|| {
7390                    Error::Msg(format!(
7391                        "PipelinedExecutor: InplaceKernel non-target input {:?} of {:?} \
7392                         not realized",
7393                        input_id, item.node_id,
7394                    ))
7395                    .bt()
7396                })?;
7397                let lay = layout_cache.get(&input_id).cloned().ok_or_else(|| {
7398                    Error::Msg(format!(
7399                        "PipelinedExecutor: InplaceKernel non-target input {:?} of {:?} \
7400                         has no cached layout",
7401                        input_id, item.node_id,
7402                    ))
7403                    .bt()
7404                })?;
7405                input_arcs.push(arc);
7406                kernel_layouts.push(lay);
7407            }
7408            let mut output_arcs = vec![target_arc.clone()];
7409            kernel_layouts.push(target_layout.clone());
7410            // A4b-1: defer the wait — return the handle to the realize loop.
7411            let handle = execute_compiled_with_wait_hint(
7412                compiled,
7413                &input_arcs,
7414                &mut output_arcs,
7415                &kernel_layouts,
7416                will_be_waited,
7417            )?;
7418            // Adopt the target Arc at this node's slot. The realize
7419            // loop's destructive_input cleanup evicts the target's own
7420            // NodeId from the cache afterward.
7421            cache.insert(item.node_id, target_arc);
7422            layout_cache.insert(item.node_id, item.output_layout.clone());
7423            Ok(handle)
7424        }
7425    }
7426}
7427
7428fn poisoned(what: &'static str) -> Error {
7429    Error::Msg(format!("PipelinedExecutor: {} poisoned", what)).bt()
7430}
7431
7432/// Step E A4b-1: record a node's [`CompletionHandle`] in the executor's
7433/// per-node handle map.
7434///
7435/// `Ready` handles (CPU / Vulkan / view-and-alloc arms) carry no async work, so
7436/// we DON'T store them — keeping the map to genuinely-pending entries makes the
7437/// realize-end empty-after-drain assert (open question #6) meaningful and keeps
7438/// the drain O(pending) rather than O(nodes). A re-used NodeId (in-place adopt
7439/// re-keys an existing slot) waits the prior handle first so nothing leaks.
7440#[inline]
7441/// ROADMAP row 158: after a kernel node was submitted, add its compile-time estimate to the device it
7442/// landed on. The device comes from the OUTPUT storage (the same source `produce_pending` reads), so a
7443/// node stamped for one backend but realized elsewhere is priced where it actually runs. Nothing is added
7444/// for a non-kernel item, a CPU output, a `0` estimate, or a storage that cannot name its device.
7445fn feed_backlog(
7446    ledger: &mut crate::dispatch::BacklogLedger,
7447    cache: &StorageCache,
7448    item: &WorkItem,
7449) {
7450    // OFF by default (`FUEL_BACKLOG_FEED`, `set_backlog_feed_enabled`): see `dispatch::BACKLOG_FEED_ENV`.
7451    if !crate::dispatch::backlog_feed_enabled() {
7452        return;
7453    }
7454    // Take back what the GPU has already finished first, so the picker reads QUEUED work, not everything
7455    // this realize has submitted so far.
7456    ledger.retire_completed();
7457    let Some(compiled) = item.compiled.as_ref() else {
7458        return;
7459    };
7460    if !matches!(item.kind, WorkItemKind::Kernel) || compiled.est_ns == 0 {
7461        return;
7462    }
7463    let Some(arc) = cache.get(&item.node_id) else {
7464        return;
7465    };
7466    let Ok(guard) = arc.read() else {
7467        return;
7468    };
7469    if let Some(loc) = guard.inner.location() {
7470        match completion_probe(&guard.inner) {
7471            Some(done) if !crate::dispatch::backlog_retire_disabled() => {
7472                ledger.add_until(loc, compiled.est_ns, done)
7473            }
7474            _ => ledger.add(loc, compiled.est_ns),
7475        }
7476    }
7477}
7478
7479/// A non-blocking "has the work just submitted into this storage finished?" probe, from the backend that
7480/// holds it (ROADMAP row 158): Vulkan reads its dispatch clock against the count stamped now, after the
7481/// kernel was recorded; CUDA records an event on the device stream now and queries it. `None` for a backend
7482/// with no probe (the estimate then stays until the end of the realize).
7483fn completion_probe(
7484    inner: &fuel_memory::BackendStorage,
7485) -> Option<Box<dyn Fn() -> bool + Send + Sync>> {
7486    match inner {
7487        #[cfg(feature = "vulkan")]
7488        fuel_memory::BackendStorage::Vulkan(v) => {
7489            let clock = v.backend()?.dispatch_clock();
7490            let stamp = clock.recorded();
7491            Some(Box::new(move || clock.retired() >= stamp))
7492        }
7493        #[cfg(feature = "cuda")]
7494        fuel_memory::BackendStorage::Cuda(c) => {
7495            let ev = c.record_completion_event().ok()?;
7496            // A failed query counts as finished: a fault surfaces at the realize's own sync, and the
7497            // estimate must not stay on the backlog because the probe could not answer.
7498            Some(Box::new(move || ev.is_complete().unwrap_or(true)))
7499        }
7500        #[allow(unreachable_patterns)]
7501        _ => None,
7502    }
7503}
7504
7505fn store_handle(
7506    handles: &mut HashMap<NodeId, CompletionHandle>,
7507    node_id: NodeId,
7508    handle: CompletionHandle,
7509) {
7510    if matches!(handle, CompletionHandle::Ready) {
7511        // A prior pending handle at this slot must still be waited (don't drop a
7512        // Pending silently). In practice NodeIds are unique per realize, so this
7513        // is just defensive.
7514        if let Some(prev) = handles.remove(&node_id) {
7515            let _ = prev.wait();
7516        }
7517        return;
7518    }
7519    if let Some(prev) = handles.insert(node_id, handle) {
7520        let _ = prev.wait();
7521    }
7522}
7523
7524/// Step E A4b-3: the FINER cross-device producer wait.
7525///
7526/// Before dispatching a cross-device `Op::Copy` / `Op::Move` WorkItem, the
7527/// executor calls this on the copy's single source input. It removes the
7528/// source producer's [`CompletionHandle`] from the map and waits it — so the
7529/// specific producer P is complete before the D2H reads P's device buffer,
7530/// WITHOUT draining the whole source device (the conservative pre-A4b-3
7531/// behavior, where `to_cpu_bytes`'s `device.synchronize()` blocked on ALL
7532/// in-flight work on that device — including the OTHER sub-DAG's independent
7533/// work A4b-4 wants to overlap).
7534///
7535/// - **CUDA producer** → waits P's recorded `Event` (`cuEventSynchronize`):
7536///   fires after P + its already-ordered stream predecessors, nothing else.
7537/// - **Absent / `Ready` producer** (CPU producer, or a Vulkan producer — which
7538///   under A4b-2 is `Ready` mid-walk because nothing is submitted until
7539///   realize-end) → no-op. A Vulkan SOURCE's own ordering is handled inside
7540///   `download_bytes` (it `force_flush`es the open batch then reads), so there
7541///   is no mid-walk Vulkan handle to wait here; the cross-device Vulkan→CPU hop
7542///   stays correct without one.
7543///
7544/// Removing the handle here (rather than waiting it again at realize-end) keeps
7545/// `drain_handles`' post-drain empty-map assert meaningful and avoids a
7546/// double-wait. Waiting it twice would be harmless (`cuEventSynchronize` on an
7547/// already-signalled event is a fast no-op), but the consume-once contract is
7548/// cleaner. The producing node's *storage* stays in the cache for downstream
7549/// readers; only its completion handle is consumed.
7550fn wait_producer_handle(
7551    handles: &mut HashMap<NodeId, CompletionHandle>,
7552    producer: NodeId,
7553) -> Result<()> {
7554    if let Some(handle) = handles.remove(&producer) {
7555        handle.wait()?;
7556    }
7557    Ok(())
7558}
7559
7560/// Step E A4b-1: realize-end drain — wait every outstanding async handle, then
7561/// clear the map.
7562///
7563/// **Event-recording / wait strategy (A4b-1 §1.2).** CUDA has one stream per
7564/// device, and an `Event` recorded after a node's launch signals when that
7565/// node *and all prior stream work* have completed. So once the
7566/// latest-recorded event on a device has signalled, every earlier event on that
7567/// device is already signalled too: waiting them is a non-blocking
7568/// `cuEventQuery` fast-path, not N host stalls. We therefore wait every stored
7569/// handle (correct + simple).
7570///
7571/// **Open question #4 — "event only where waited" — RESOLVED.** Recording an
7572/// `Event` for every node was measured negligible on a 32-op synthetic, but
7573/// real decode graphs run 150-200+ ops; `pipelined`'s `WaitSet` pre-scan (see
7574/// `compiler_work_and_wait_set_for` / `build_wait_set`) now restricts event
7575/// production to the nodes some later cross-device `Copy`/`Move` will
7576/// individually wait — same-device-only ("elided") nodes get
7577/// `CompletionHandle::Ready` with no `cuEventCreate`/`cuEventRecord` at all
7578/// (`execute_compiled_with_wait_hint`). This drain therefore now retires only
7579/// the (typically few) wait-set handles that were never consumed mid-walk by
7580/// `wait_producer_handle`; it is no longer sufficient on its own to guarantee
7581/// every enqueued CUDA kernel has completed — `sync_active_cuda_devices` below
7582/// covers the elided remainder. We keep a per-node handle (rather than a
7583/// single per-device event) for the wait-set members because A4b-3's finer
7584/// cross-device wait needs to wait a *specific producer's* completion — the
7585/// per-node handle is that seam.
7586fn drain_handles(handles: &mut HashMap<NodeId, CompletionHandle>) -> Result<()> {
7587    for (_node, handle) in handles.drain() {
7588        handle.wait()?;
7589    }
7590    // Open question #6: once handles are stored instead of `wait`ed inline, the
7591    // `#[must_use]` on `CompletionHandle` can't catch a leaked (never-waited)
7592    // handle at the call site. The drain consumes the whole map, so it is empty
7593    // here by construction; assert it to catch a future leak (e.g. a new
7594    // dispatch path that forgets to thread its handle through `store_handle`).
7595    debug_assert!(
7596        handles.is_empty(),
7597        "A4b-1: handle map must be empty after drain"
7598    );
7599    Ok(())
7600}
7601
7602/// Step E A4b open question #4 step 3 — the realize-end complement to the
7603/// "event only where waited" elision. Because most CUDA nodes in a long
7604/// single-device chain no longer record an `Event` (see `drain_handles`'s
7605/// doc), this does ONE blanket `cuStreamSynchronize` per CUDA device that
7606/// still holds LIVE storage in `cache` — the realize target(s) plus any
7607/// surviving intermediates — instead of relying on per-node handles to cover
7608/// them.
7609///
7610/// **Why this is safe + sufficient.** CUDA has one stream per device, and
7611/// this executor dispatches strictly sequentially (one work item at a time,
7612/// in topological order) — so by the time a live node's own kernel was
7613/// launched, every same-device ancestor it depends on was ALREADY enqueued
7614/// earlier on the SAME stream. Stream ordering (not a host wait) guarantees
7615/// those ancestors run to completion no later than the live node's own
7616/// kernel. Syncing the live node's device therefore flushes its entire
7617/// same-device dependency chain, elided or not. Cross-device ancestors are
7618/// unaffected by elision — they always went through an `Op::Copy`/`Move`,
7619/// whose producer is in the `WaitSet` and was already waited explicitly at
7620/// the cross-device boundary (`wait_producer_handle`), mid-walk.
7621///
7622/// **Why evicted (non-live) intermediates don't need this.** A node whose
7623/// storage was evicted before realize-end (the `destructive_input` cleanup)
7624/// is never read by anything this realize returns; A3's stream-ordered
7625/// alloc/free already makes its eventual completion safe without a host
7626/// wait (the driver serializes the free after the freeing stream position,
7627/// same as any other stream-ordered op) — nothing to synchronize for.
7628///
7629/// No-op when `cache` holds no CUDA storage (CPU/Vulkan-only realize).
7630#[cfg(feature = "cuda")]
7631fn sync_active_cuda_devices(cache: &StorageCache) -> Result<()> {
7632    let mut devices: HashMap<fuel_ir::DeviceLocation, fuel_cuda_backend::CudaDevice> =
7633        HashMap::new();
7634    for arc in cache.values() {
7635        let guard = arc
7636            .read()
7637            .map_err(|_| poisoned("cache storage (cuda realize-end sync scan)"))?;
7638        if let fuel_memory::BackendStorage::Cuda(c) = &guard.inner {
7639            devices
7640                .entry(c.device().location())
7641                .or_insert_with(|| c.device().clone());
7642        }
7643    }
7644    for dev in devices.values() {
7645        dev.synchronize()?;
7646    }
7647    Ok(())
7648}
7649
7650/// Non-CUDA builds never produce CUDA storage, so there is nothing to sync —
7651/// keeps the call site unconditional across both feature configurations.
7652#[cfg(not(feature = "cuda"))]
7653fn sync_active_cuda_devices(_cache: &StorageCache) -> Result<()> {
7654    Ok(())
7655}
7656
7657/// Step E A4b-2: a Vulkan [`Completion`](crate::compiled::Completion) over an
7658/// in-flight (submitted, not-yet-waited) batch. `wait` blocks on the batch's
7659/// fence (`vkWaitForFences`) — which fires when the whole submitted command
7660/// buffer has retired on the single compute queue — then releases the batch
7661/// (frees the CB / descriptor sets / transient buffers / retired pool, all now
7662/// idle on the GPU).
7663///
7664/// The fence is per-BATCH, not per-node: one `submit_pending` flushes every op
7665/// recorded since the last submit, so this single handle covers a contiguous run
7666/// of Vulkan nodes (the A2 batching win, preserved — fewer fences, larger
7667/// submissions). `backend` keeps the [`VulkanBackend`] alive so the
7668/// post-fence pool retire + the `DeviceInner` the batch's resources reference
7669/// outlive the wait.
7670///
7671/// `Send` (required by `Completion`): every owned field is `Send` — `Fence` /
7672/// `CommandBuffer` / `DescriptorSet` / `Buffer` / `Allocation` / `CommandPool`
7673/// are all `Send` in vulkane (Arc-of-`DeviceInner` + explicit `unsafe impl`s),
7674/// and `Arc<VulkanBackend>` is `Send + Sync`.
7675/// Step E B1: `batch` is an `Option` ONLY so [`Drop`] can coexist with the
7676/// by-value `into_wait` consume. A type with a `Drop` impl cannot be
7677/// destructured by move (`let VulkanCompletion { backend, batch } = self`,
7678/// E0509), so `into_wait` `take()`s the batch out of the `Option` instead of
7679/// moving it out of the struct, then lets the normal `Drop` run. In every
7680/// reachable state the batch is `Some` until exactly one `into_wait` consumes it.
7681#[cfg(feature = "vulkan")]
7682struct VulkanCompletion {
7683    backend: Arc<fuel_vulkan_backend::VulkanBackend>,
7684    batch: Option<fuel_vulkan_backend::SubmittedBatch>,
7685    /// The device this submitted batch counts against in the in-flight counter
7686    /// (Step E B1). `Drop` decrements this slot.
7687    loc: fuel_ir::DeviceLocation,
7688}
7689
7690/// Step E A4b-4: the element type of the executor's in-flight-Vulkan-batch list.
7691/// A [`VulkanCompletion`] on a Vulkan build; a zero-sized placeholder otherwise
7692/// so the realize loops carry one `Vec<InflightVulkan>` local without `cfg` on
7693/// every use site (the helpers `eager_submit_all_vulkan` / `drain_inflight_vulkan`
7694/// are the only code that ever pushes/drains it, and they are `cfg`-gated).
7695#[cfg(feature = "vulkan")]
7696type InflightVulkan = VulkanCompletion;
7697#[cfg(not(feature = "vulkan"))]
7698type InflightVulkan = ();
7699
7700/// Step E A4b-4: is the cross-device copy's SOURCE buffer Vulkan-resident?
7701///
7702/// Used at the cross-device `Op::Copy`/`Op::Move` boundary to decide whether the
7703/// executor must wait the in-flight Vulkan batches before the copy. A Vulkan→CPU
7704/// D2H reads the source on the host, and the Vulkan `download` path only
7705/// `force_flush`es the OPEN batch (never the executor's eagerly-submitted
7706/// in-flight ones), so for a VULKAN source we must `drain_inflight_vulkan` first
7707/// to read completed data. For a CUDA / CPU source we must NOT wait Vulkan — the
7708/// copy doesn't read any Vulkan buffer, and waiting Vulkan there would needlessly
7709/// serialize the independent Vulkan sub-DAG (killing the overlap A4b-4 exists to
7710/// win). Returns `false` when the producer's storage isn't in the cache (treated
7711/// as not-Vulkan → no Vulkan wait; the CUDA/CPU producer handle still covers it).
7712#[cfg(feature = "vulkan")]
7713fn copy_source_is_vulkan(cache: &StorageCache, producer: NodeId) -> Result<bool> {
7714    if let Some(arc) = cache.get(&producer) {
7715        let guard = arc
7716            .read()
7717            .map_err(|_| poisoned("storage lock probing copy-source backend"))?;
7718        return Ok(matches!(
7719            guard.inner,
7720            fuel_memory::BackendStorage::Vulkan(_)
7721        ));
7722    }
7723    Ok(false)
7724}
7725
7726#[cfg(not(feature = "vulkan"))]
7727#[inline]
7728fn copy_source_is_vulkan(_cache: &StorageCache, _producer: NodeId) -> Result<bool> {
7729    Ok(false)
7730}
7731
7732#[cfg(feature = "vulkan")]
7733impl crate::compiled::Completion for VulkanCompletion {
7734    fn wait(self: Box<Self>) -> Result<()> {
7735        // Move the whole `VulkanCompletion` out of the `Box` (allowed even with a
7736        // `Drop` impl — it's a full move, not a destructure) and consume by value.
7737        (*self).into_wait()
7738    }
7739}
7740
7741#[cfg(feature = "vulkan")]
7742impl VulkanCompletion {
7743    /// Build the handle for an eagerly-submitted Vulkan batch and register it as
7744    /// one in-flight batch on `loc` (Step E B1). The matching decrement is in
7745    /// [`Drop`]. `loc` is the backend's `DeviceLocation::Vulkan { gpu_id }`.
7746    fn new(
7747        backend: Arc<fuel_vulkan_backend::VulkanBackend>,
7748        batch: fuel_vulkan_backend::SubmittedBatch,
7749        loc: fuel_ir::DeviceLocation,
7750    ) -> Self {
7751        crate::dispatch::inflight_inc(loc);
7752        Self {
7753            backend,
7754            batch: Some(batch),
7755            loc,
7756        }
7757    }
7758
7759    /// Block on this batch's fence, retire pools, then free the batch. Consumes
7760    /// `self` by value (the by-value sibling of the boxed `Completion::wait`),
7761    /// used by the executor's `inflight_vulkan` drain (A4b-4) where we hold the
7762    /// `VulkanCompletion` unboxed in a `Vec`.
7763    ///
7764    /// Step E B1: `take()`s the batch out of the `Option` (NOT a destructure
7765    /// move — that's illegal with a `Drop` impl) and waits it; the in-flight
7766    /// decrement then rides `self`'s `Drop` as this returns. So a wait-consume
7767    /// and a bare drop (e.g. an error unwinding before the wait) BOTH decrement
7768    /// exactly once, and `into_wait` never double-counts.
7769    fn into_wait(mut self) -> Result<()> {
7770        // `wait_submitted` consumes the batch by value: waits the fence, retires
7771        // pools, then drops the batch (UAF-safe — nothing the in-flight CB
7772        // references frees before the fence signals). After a `new` the batch is
7773        // always `Some`; `take` leaves `None` so `Drop` doesn't touch it again.
7774        if let Some(batch) = self.batch.take() {
7775            self.backend.wait_submitted(batch)?;
7776        }
7777        Ok(())
7778        // `self` drops here → `inflight_dec(self.loc)`.
7779    }
7780
7781    /// Step E A2.1 (deferred-deletion): retain an evicted DATA buffer until THIS
7782    /// in-flight batch's fence signals, then free it post-fence (on the batch's
7783    /// `Drop` — guaranteed post-fence by follow-on #2). Delegates to
7784    /// [`fuel_vulkan_backend::SubmittedBatch::retain_buffer`].
7785    ///
7786    /// The executor calls this for every in-flight batch when it evicts a Vulkan
7787    /// buffer those batches' CBs may read, INSTEAD of host-blocking on a drain.
7788    /// `batch` is `Some` in every reachable mid-walk state (it is `take`n only by
7789    /// `into_wait`/`wait`, which consume the whole `VulkanCompletion`), so the
7790    /// retain always lands on a live in-flight batch.
7791    fn retain_data(&mut self, buf: std::sync::Arc<fuel_vulkan_backend::VulkanBuffer>) {
7792        if let Some(batch) = self.batch.as_mut() {
7793            batch.retain_buffer(buf);
7794        }
7795    }
7796}
7797
7798#[cfg(feature = "vulkan")]
7799impl Drop for VulkanCompletion {
7800    fn drop(&mut self) {
7801        // The single in-flight decrement for a Vulkan batch — fires whether the
7802        // batch was waited (`into_wait` / `wait`) or merely dropped (error
7803        // unwind), so the per-device count returns to baseline. Relaxed +
7804        // saturating (a scheduling hint, never a correctness gate).
7805        crate::dispatch::inflight_dec(self.loc);
7806    }
7807}
7808
7809/// Step E A4b-4 — eager Vulkan submission during the walk (the OVERLAP enabler).
7810///
7811/// Submits each DISTINCT Vulkan backend's currently-open batch WITHOUT waiting,
7812/// pushing the resulting in-flight [`VulkanCompletion`]s onto `inflight` so the
7813/// executor waits them later (at the in-flight-lifetime guard / realize-end). An
7814/// empty open batch yields `None` and is skipped (idempotent).
7815///
7816/// This is what makes a Vulkan sub-DAG actually START on the iGPU while the
7817/// executor records/dispatches the next (CUDA) chunk — without it the Vulkan
7818/// batch sits merely *recorded* until realize-end and never overlaps the CUDA
7819/// stream (design §5). Called ONLY on a genuinely multi-backend realize (gated by
7820/// the executor's `multi_backend` flag); on a single-device graph it is never
7821/// reached, so pure-Vulkan stays byte-identical to A4b-2 (one realize-end submit).
7822///
7823/// **Whole-chunk granularity (UAF/race-safety, design §4 + the Vulkan
7824/// single-queue OOO-completion semantics).** We submit only at chunk boundaries
7825/// and before a cross-device wait — never mid-chunk — so the batch handed to the
7826/// GPU is a COMPLETE contiguous run of Vulkan nodes with all its intra-CB
7827/// dependency barriers (`recorder.rs` `vkCmdPipelineBarrier`) already in place.
7828/// Vulkan only guarantees that batches on one queue BEGIN in submission order;
7829/// they may overlap / complete out of order, so a split mid-chunk would lose the
7830/// write-before-read ordering for ops that read an earlier op's buffer in the
7831/// SAME chunk. By submitting whole chunks and re-syncing (`drain_inflight_vulkan`)
7832/// before any later Vulkan op records, before any cross-device copy, and before
7833/// any Vulkan-referenced eviction, no in-flight batch is ever read or freed while
7834/// still running.
7835#[cfg(feature = "vulkan")]
7836fn eager_submit_all_vulkan(
7837    cache: &StorageCache,
7838    inflight: &mut Vec<VulkanCompletion>,
7839) -> Result<()> {
7840    // Collect distinct Vulkan backends referenced by the cache (dedup by gpu_id).
7841    let mut seen: Vec<usize> = Vec::new();
7842    let mut backends: Vec<Arc<fuel_vulkan_backend::VulkanBackend>> = Vec::new();
7843    for arc in cache.values() {
7844        let guard = arc
7845            .read()
7846            .map_err(|_| poisoned("storage lock during eager vulkan submit"))?;
7847        if let fuel_memory::BackendStorage::Vulkan(v) = &guard.inner
7848            && let Some(backend) = v.backend()
7849            && !seen.contains(&backend.gpu_id)
7850        {
7851            seen.push(backend.gpu_id);
7852            backends.push(backend.clone());
7853        }
7854    }
7855    for backend in backends {
7856        // Step E B1: the per-device location for the in-flight counter. A batch
7857        // submitted here is one in-flight unit on this iGPU until its handle's
7858        // `Drop` (after `drain_inflight_vulkan` / realize-end).
7859        let loc = DeviceLocation::Vulkan {
7860            gpu_id: backend.gpu_id,
7861        };
7862        if let Some(batch) = backend.submit_pending()? {
7863            inflight.push(VulkanCompletion::new(backend, batch, loc));
7864        }
7865    }
7866    Ok(())
7867}
7868
7869#[cfg(not(feature = "vulkan"))]
7870#[inline]
7871fn eager_submit_all_vulkan(
7872    _cache: &StorageCache,
7873    _inflight: &mut Vec<InflightVulkan>,
7874) -> Result<()> {
7875    Ok(())
7876}
7877
7878/// Step E A4b-4 — wait every in-flight (eagerly-submitted) Vulkan batch, then
7879/// clear the list. The re-sync half of [`eager_submit_all_vulkan`].
7880///
7881/// Each `into_wait` blocks on the batch fence (`vkWaitForFences`), retires the
7882/// backend's descriptor pools, and frees the batch (CB / descriptor sets /
7883/// transient buffers / retired command pool — all now idle on the GPU). After
7884/// this returns, NO submitted Vulkan command buffer is still executing, so it is
7885/// safe to (a) record a new Vulkan op that may read a just-produced buffer,
7886/// (b) D2H-copy a Vulkan buffer on the host, or (c) free a buffer a batch read.
7887///
7888/// Because the eager submit happened at the PRIOR chunk boundary and an
7889/// intervening (e.g. CUDA) chunk has since been recorded/dispatched, the fence is
7890/// typically already signalled here — the wait is a fast no-op, and the iGPU work
7891/// genuinely overlapped the other device's stream. Waiting the Vulkan fence does
7892/// NOT touch the CUDA stream, so the other device keeps running (concurrency
7893/// preserved — design §5 "the per-device guards don't cross-stall").
7894#[cfg(feature = "vulkan")]
7895fn drain_inflight_vulkan(inflight: &mut Vec<VulkanCompletion>) -> Result<()> {
7896    for vc in inflight.drain(..) {
7897        vc.into_wait()?;
7898    }
7899    Ok(())
7900}
7901
7902#[cfg(not(feature = "vulkan"))]
7903#[inline]
7904fn drain_inflight_vulkan(_inflight: &mut Vec<InflightVulkan>) -> Result<()> {
7905    Ok(())
7906}
7907
7908/// Step E A4b-2: the realize-end Vulkan drain, SPLIT into submit-then-wait.
7909///
7910/// Replaces A2's `force_flush_all_vulkan` (which submitted + waited atomically
7911/// inside `force_flush`). For each DISTINCT Vulkan backend referenced by the
7912/// cache, `submit_pending` submits the still-open batch WITHOUT waiting (→ a
7913/// `SubmittedBatch`), wraps it in the executor's [`VulkanCompletion`] handle, and
7914/// `wait`s it. Net for a pure-Vulkan realize: the batch still accumulates across
7915/// the whole walk (the per-op path keeps returning `Ready`; no eager submit —
7916/// that is A4b-4) and is submitted ONCE here, then waited — **byte-identical to
7917/// A2**, same single submission at realize-end, just split through the handle.
7918///
7919/// Idempotent across repeated cache arcs: the first `submit_pending` on a backend
7920/// returns `Some(batch)`; subsequent calls on the same backend see an empty batch
7921/// and return `None` (skipped) — exactly the `force_flush` idempotence A2 relied
7922/// on. No-op for a non-Vulkan build.
7923#[cfg(feature = "vulkan")]
7924fn drain_vulkan_pending(cache: &StorageCache) -> Result<()> {
7925    use crate::compiled::CompletionHandle;
7926    for arc in cache.values() {
7927        let backend = {
7928            let guard = arc
7929                .read()
7930                .map_err(|_| poisoned("storage lock during vulkan submit_pending"))?;
7931            match &guard.inner {
7932                fuel_memory::BackendStorage::Vulkan(v) => v.backend().cloned(),
7933                _ => None,
7934            }
7935        };
7936        let Some(backend) = backend else { continue };
7937        // Submit the open batch (if any) without waiting, then wait via the
7938        // completion handle. Empty batch → None → nothing to wait.
7939        // Step E B1: `new` increments the in-flight counter for this device;
7940        // `handle.wait()` waits + drops the `VulkanCompletion`, decrementing it
7941        // — a balanced submit/retire even on this transient realize-end path.
7942        let loc = DeviceLocation::Vulkan {
7943            gpu_id: backend.gpu_id,
7944        };
7945        if let Some(batch) = backend.submit_pending()? {
7946            let handle: CompletionHandle =
7947                CompletionHandle::Pending(Box::new(VulkanCompletion::new(backend, batch, loc)));
7948            handle.wait()?;
7949        }
7950    }
7951    Ok(())
7952}
7953
7954#[cfg(not(feature = "vulkan"))]
7955fn drain_vulkan_pending(_cache: &StorageCache) -> Result<()> {
7956    Ok(())
7957}
7958
7959/// Step E A2: force the Vulkan backend behind `arc` (if any) to submit + WAIT
7960/// its open batch — the blocking drain before freeing a buffer the batch may
7961/// reference (a destructive eviction) so a recorded-but-unsubmitted command never
7962/// reads freed memory. No-op for non-Vulkan storage, an empty batch, or a
7963/// non-Vulkan build.
7964///
7965/// **Retained for the SINGLE-DEVICE path (byte-identical to pre-A2.1).** A2.1's
7966/// deferred-deletion ([`defer_evicted_vulkan_buffer`]) replaces this only on a
7967/// MULTI-backend realize, where eager-submit + in-flight tracking + the
7968/// realize-end `drain_inflight_vulkan` are all live. On a single-device Vulkan
7969/// realize the A4b machinery is gated off (`multi_backend == false`): the
7970/// cross-batch RAW guard (`pipelined.rs:832`) does not run, so a later Vulkan op
7971/// reading a buffer an eager-submitted batch wrote could race (separate
7972/// submissions only BEGIN in order, may overlap). The blocking `force_flush`
7973/// (submit + wait) is the coherent eviction drain there — exactly the original
7974/// behavior — so single-device stays byte-identical and UAF-safe.
7975#[cfg(feature = "vulkan")]
7976fn force_flush_vulkan(arc: &Arc<RwLock<Storage>>) -> Result<()> {
7977    let guard = arc
7978        .read()
7979        .map_err(|_| poisoned("storage lock during vulkan force_flush"))?;
7980    if let fuel_memory::BackendStorage::Vulkan(v) = &guard.inner
7981        && let Some(backend) = v.backend()
7982    {
7983        backend.force_flush()?;
7984    }
7985    Ok(())
7986}
7987
7988#[cfg(not(feature = "vulkan"))]
7989fn force_flush_vulkan(_arc: &Arc<RwLock<Storage>>) -> Result<()> {
7990    Ok(())
7991}
7992
7993/// Step E A2.1 — DEFERRED-DELETION of a Vulkan data buffer evicted while Vulkan
7994/// work is in flight (the throughput refinement that REPLACES the eviction-time
7995/// drain on a MULTI-backend realize). Called at the per-NodeId destructive
7996/// eviction (`Op::Release`/`Op::Move` cleanup) for the buffer about to leave the
7997/// cache, INSTEAD of `drain_inflight_vulkan` + `force_flush` (two host-blocking
7998/// fence waits) — so the iGPU work the executor was overlapping with CUDA is not
7999/// stalled at every eviction.
8000///
8001/// Two classes of Vulkan reader can hold a reference to `destroyed`'s buffer at
8002/// the eviction:
8003///   1. the **in-flight** `SubmittedBatch`es in `inflight` (submitted CBs, each
8004///      fenced), and
8005///   2. the **open**, not-yet-submitted recorder batch (recorded commands, NO
8006///      fence yet).
8007///
8008/// We make BOTH fence-gated without blocking the host:
8009///   - `eager_submit_all_vulkan` submits the open batch WITHOUT waiting, turning
8010///     it into one more in-flight `SubmittedBatch` (now fenced) pushed onto
8011///     `inflight`. (Whole-chunk granularity — UAF/race-safe per its contract; at a
8012///     destructive eviction the open batch is a contiguous Vulkan run.)
8013///   - We then move a refcount clone of the evicted buffer's `Arc<VulkanBuffer>`
8014///     into EVERY in-flight batch (conservative: we cannot cheaply map
8015///     buffer→batch, exactly the reason the old drain waited *all* of them). Each
8016///     batch frees its retained clone POST-fence on `Drop` (follow-on #2).
8017///
8018/// After this returns the caller `cache.remove`s `destroyed`; the cache's
8019/// `Arc<RwLock<Storage>>` drops, but the buffer's recycler
8020/// (`VulkanBuffer::drop`) reclaims it only when its LAST `Arc` drops — and the
8021/// retained clones keep it alive until their owning batches' fences signal. So the
8022/// GPU's last read of the buffer strictly precedes the free (NO use-after-free),
8023/// the host never blocks at the eviction (the iGPU keeps overlapping CUDA — the
8024/// throughput win), and every batch (hence every retained buffer) is drained by
8025/// realize-end at the latest (`drain_inflight_vulkan`, `pipelined.rs:916/1238`,
8026/// runs unconditionally → NO leak).
8027///
8028/// **Multi-backend only** (the call site gates `if multi_backend`). On a
8029/// single-device realize the open batch is drained by the blocking
8030/// [`force_flush_vulkan`] instead (byte-identical to pre-A2.1; see its doc for
8031/// why the deferred path is unsafe without the cross-batch RAW guard). No-op for a
8032/// non-Vulkan storage, an empty open + no in-flight batches, or a non-Vulkan build.
8033/// Open-batch size (dispatches) at which a deferred eviction submits the batch so the
8034/// GPU runs it while the host keeps recording.
8035#[cfg(feature = "vulkan")]
8036const EVICT_SUBMIT_MIN_DISPATCHES: usize = 48;
8037
8038#[cfg(feature = "vulkan")]
8039fn defer_evicted_vulkan_buffer(
8040    cache: &StorageCache,
8041    destroyed: NodeId,
8042    inflight: &mut Vec<VulkanCompletion>,
8043) -> Result<()> {
8044    // Pull the evicted buffer's device Arc (and its backend) out of the cache BEFORE
8045    // it is removed. Non-Vulkan storage, a host-evicted (no device buffer) Vulkan
8046    // storage, or an absent entry → nothing to retain (no Vulkan reader can hold a
8047    // device buffer).
8048    let (buf, backend) = {
8049        let Some(arc) = cache.get(&destroyed) else {
8050            return Ok(());
8051        };
8052        let guard = arc
8053            .read()
8054            .map_err(|_| poisoned("storage lock during deferred-eviction retain"))?;
8055        match &guard.inner {
8056            fuel_memory::BackendStorage::Vulkan(v) => (v.device_buffer_arc(), v.backend().cloned()),
8057            _ => (None, None),
8058        }
8059    };
8060    let Some(buf) = buf else { return Ok(()) };
8061
8062    // The OPEN batch may hold recorded-but-unsubmitted commands that read `destroyed`:
8063    // retain the buffer on the open batch itself (freed post-fence once that batch is
8064    // submitted and waited). This neither submits nor waits — it used to eager-submit
8065    // here, i.e. one queue submit per eviction (61 per Qwen3 decode step).
8066    // Whether the open batch held recorded work (so the retain above actually kept a reader's
8067    // buffer alive instead of blocking): read BEFORE the eager submit below empties it.
8068    let retained_in_open_batch = backend.as_ref().is_some_and(|b| b.open_batch_len() > 0);
8069    if let Some(backend) = &backend {
8070        backend.retain_in_open_batch(buf.clone());
8071    }
8072    // Retain a clone of the evicted buffer in EVERY in-flight batch. Each frees it
8073    // POST-fence on `Drop` — the buffer outlives the GPU's last read with no host
8074    // block. Conservative over all batches (no cheap buffer→batch map); over-retention
8075    // only lengthens the lifetime, never a UAF, and all batches drain by realize-end.
8076    for vc in inflight.iter_mut() {
8077        vc.retain_data(buf.clone());
8078    }
8079    // Keep the GPU fed: submit the open batch once it has grown by a chunk.
8080    if let Some(backend) = backend
8081        && backend.open_batch_len() >= EVICT_SUBMIT_MIN_DISPATCHES
8082    {
8083        eager_submit_all_vulkan(cache, inflight)?;
8084    }
8085    // Step E A2.1 — throughput-observability. Count a DEFERRED retain that
8086    // actually replaced a host block: an evicted Vulkan buffer retained onto ≥1
8087    // in-flight batch (the open-batch eager-submit and/or pre-existing in-flight
8088    // batches). Pre-A2.1 every such site host-blocked (`force_flush` and/or
8089    // `drain_inflight_vulkan`); now it does not. A test reads
8090    // [`deferred_eviction_retains`] to assert the deferred path fired without a
8091    // drain (deterministic — no wall-clock, which is noisy on this box). When
8092    // `inflight` is empty AND the open batch was empty there was genuinely no in-flight/open
8093    // Vulkan reader to wait for, so no host block was avoided (and none was needed) — not
8094    // counted. A retain onto a non-empty OPEN batch counts (GAP-371: the counter used to look
8095    // only at in-flight batches, so an eviction inside the still-open batch, which is the
8096    // common single-chunk case, never advanced it even though it avoided the host block).
8097    if retained_in_open_batch || !inflight.is_empty() {
8098        DEFERRED_EVICTION_RETAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8099    }
8100    Ok(())
8101}
8102
8103/// Step E A2.1 — cumulative count of deferred-deletion retains that replaced a
8104/// host-blocking eviction drain (an evicted Vulkan buffer retained onto ≥1
8105/// in-flight batch instead of waiting it). Process-global, `Relaxed` — a pure
8106/// test/telemetry observation, never a correctness gate (mirrors the B1 in-flight
8107/// counter idiom). Read by the live deferred-eviction throughput test.
8108#[cfg(feature = "vulkan")]
8109pub static DEFERRED_EVICTION_RETAINS: std::sync::atomic::AtomicUsize =
8110    std::sync::atomic::AtomicUsize::new(0);
8111
8112/// Read the A2.1 deferred-eviction-retain counter (see
8113/// [`DEFERRED_EVICTION_RETAINS`]). `pub` so the live throughput test can assert a
8114/// deferred retain fired (the eviction did NOT host-block on a Vulkan fence).
8115#[cfg(feature = "vulkan")]
8116pub fn deferred_eviction_retains() -> usize {
8117    DEFERRED_EVICTION_RETAINS.load(std::sync::atomic::Ordering::Relaxed)
8118}
8119
8120#[cfg(not(feature = "vulkan"))]
8121#[inline]
8122fn defer_evicted_vulkan_buffer(
8123    _cache: &StorageCache,
8124    _destroyed: NodeId,
8125    _inflight: &mut Vec<InflightVulkan>,
8126) -> Result<()> {
8127    Ok(())
8128}
8129
8130/// Materialize a contiguous Storage Arc from a non-contiguous one.
8131/// Allocates a fresh buffer on the input's backend and copies the
8132/// strided / offset / broadcast input into it via the backend's
8133/// contiguize kernel. The returned Arc is a brand-new buffer; the
8134/// caller is responsible for replacing the cache entry only for the
8135/// duration of one kernel call (the upstream view op's output stays
8136/// in the cache so other consumers still see the strided view).
8137///
8138/// Stage 4 of Layout-on-Node — auto-Contiguize.
8139fn auto_contiguize(arc: &Arc<RwLock<Storage>>, layout: &Layout) -> Result<Arc<RwLock<Storage>>> {
8140    let in_guard = arc
8141        .read()
8142        .map_err(|_| poisoned("input storage lock during auto_contiguize"))?;
8143    let dtype = in_guard.dtype;
8144    let dtype_size = dtype.size_in_bytes();
8145    let new_storage = match &in_guard.inner {
8146        fuel_memory::BackendStorage::Cpu(c) => {
8147            let new_bytes = fuel_cpu_backend::byte_kernels::contiguize_cpu(c, layout, dtype_size)?;
8148            Storage::new(fuel_memory::BackendStorage::Cpu(new_bytes), dtype)
8149        }
8150        #[cfg(feature = "cuda")]
8151        fuel_memory::BackendStorage::Cuda(c) => {
8152            // Native baracuda contiguize (alpha.29). Byte-width-
8153            // dispatched: 1/2/4/8/16 byte elements all route to the
8154            // appropriate kernel. Handles signed strides (Flip),
8155            // zero strides (BroadcastTo), and non-zero element offset.
8156            //
8157            // Three host-side fast paths bake into the baracuda
8158            // launchers: already-contiguous → single cuMemcpyDtoDAsync;
8159            // innermost-stride-1 → per-outer-coord run copy; generic
8160            // → one thread per output element. Retires the prior
8161            // D2H → CPU contiguize_cpu → H2D fallback (two device
8162            // round-trips per non-contig input).
8163            let contig = fuel_cuda_backend::baracuda::contiguize::contiguize_to_fresh(
8164                c, layout, dtype_size,
8165            )?;
8166            Storage::new(fuel_memory::BackendStorage::Cuda(contig), dtype)
8167        }
8168        #[cfg(feature = "vulkan")]
8169        fuel_memory::BackendStorage::Vulkan(v) => {
8170            // Native `strided_copy_signed_*` kernel when it applies (2/4/8-byte
8171            // elements; see `contiguize_vulkan`). Otherwise the V.1.B host round trip:
8172            // D2H → CPU contiguize_cpu → H2D, which forces a flush and a wait
8173            // per call.
8174            let backend = v.backend().ok_or_else(|| {
8175                Error::Msg(
8176                    "auto_contiguize: Vulkan input has no backend handle. \
8177                     Storages flowing through the pipelined executor's Vulkan \
8178                     path must be constructed via VulkanBackend::alloc_bytes_handle \
8179                     / upload_bytes_handle (not the legacy alloc_bytes / \
8180                     upload_bytes which leave VulkanStorageBytes::backend = None)."
8181                        .to_string(),
8182                )
8183                .bt()
8184            })?;
8185            if let Some(native) = fuel_vulkan_backend::contiguize_vulkan(v, layout, dtype_size)? {
8186                return Ok(Arc::new(RwLock::new(Storage::new(
8187                    fuel_memory::BackendStorage::Vulkan(native),
8188                    dtype,
8189                ))));
8190            }
8191            let _t = crate::compiled::op_profile::PhaseTimer::start(
8192                "auto_contiguize.vulkan_host_roundtrip",
8193            );
8194            let host_bytes = backend.download_bytes(v)?;
8195            let host_cpu = fuel_cpu_backend::byte_storage::CpuStorageBytes::from_bytes(&host_bytes);
8196            let contig_cpu =
8197                fuel_cpu_backend::byte_kernels::contiguize_cpu(&host_cpu, layout, dtype_size)?;
8198            let host_contig_bytes = contig_cpu.bytes().to_vec();
8199            let vk_bytes = backend.upload_bytes_handle(&host_contig_bytes)?;
8200            Storage::new(fuel_memory::BackendStorage::Vulkan(vk_bytes), dtype)
8201        }
8202        #[allow(unreachable_patterns)]
8203        _ => {
8204            return Err(Error::Msg(
8205                "auto_contiguize: backend not wired (CPU + CUDA + Vulkan are \
8206                 wired today; Metal extends this match when its byte-storage \
8207                 substrate lands)"
8208                    .to_string(),
8209            )
8210            .bt());
8211        }
8212    };
8213    Ok(Arc::new(RwLock::new(new_storage)))
8214}
8215
8216/// Write-into sibling of [`auto_contiguize`] (CapturedRun executor
8217/// build-out, 4b-γ): materializes a contiguous copy of `arc` at `layout`
8218/// INTO `dest`'s EXISTING buffer instead of allocating a fresh one — the
8219/// path `WorkItemKind::ContiguizeOf`'s Reuse-mode branch needs (device
8220/// allocation is illegal inside a capture scope). `dest` must already be
8221/// sized to the contiguized output's byte count — true by construction,
8222/// since the persistent map only ever holds a buffer THIS SAME code path
8223/// (the warm-run `auto_contiguize` allocation) sized.
8224///
8225/// CUDA-only today: `PersistentOutputs::reuse` (Reuse mode) is only ever
8226/// constructed inside [`PipelinedExecutor::capture_decode`], which is
8227/// `#[cfg(feature = "cuda")]`-gated and validates every compute node
8228/// targets `Cuda` — a CPU or Vulkan storage can never actually reach this
8229/// function in practice. Per this project's "never panic on production
8230/// paths" rule, the other backends still surface a typed gap rather than
8231/// silently mishandling it (never a crash).
8232#[cfg_attr(not(feature = "cuda"), allow(unused_variables))]
8233fn contiguize_into(
8234    dest: &Arc<RwLock<Storage>>,
8235    arc: &Arc<RwLock<Storage>>,
8236    layout: &Layout,
8237) -> Result<()> {
8238    let in_guard = arc
8239        .read()
8240        .map_err(|_| poisoned("input storage lock during contiguize_into"))?;
8241    match &in_guard.inner {
8242        #[cfg(feature = "cuda")]
8243        fuel_memory::BackendStorage::Cuda(src_cuda) => {
8244            let dtype_size = in_guard.dtype.size_in_bytes();
8245            let mut dest_guard = dest
8246                .write()
8247                .map_err(|_| poisoned("dest storage lock during contiguize_into"))?;
8248            let dest_cuda = match &mut dest_guard.inner {
8249                fuel_memory::BackendStorage::Cuda(d) => d,
8250                other => {
8251                    return Err(Error::Msg(format!(
8252                        "contiguize_into: dest is BackendStorage::{:?}, not Cuda",
8253                        other.backend_id(),
8254                    ))
8255                    .bt());
8256                }
8257            };
8258            fuel_cuda_backend::baracuda::contiguize::contiguize_into(
8259                src_cuda, layout, dest_cuda, dtype_size,
8260            )
8261        }
8262        #[allow(unreachable_patterns)]
8263        _ => Err(Error::Msg(
8264            "contiguize_into: only CUDA is wired (PersistentOutputs::reuse / \
8265             capture_decode is CUDA-only today — no CPU/Vulkan consumer exists \
8266             yet; extend this match if one appears)"
8267                .to_string(),
8268        )
8269        .bt()),
8270    }
8271}
8272
8273#[cfg(test)]
8274mod backend_neutral_tests {
8275    use super::*;
8276
8277    #[test]
8278    fn only_deviceless_items_are_backend_neutral() {
8279        let n = NodeId(0);
8280        // Adopting an input-cache entry or aliasing a producer touches no device.
8281        assert!(is_backend_neutral(&WorkItemKind::ConstAdopt));
8282        assert!(is_backend_neutral(&WorkItemKind::ViewOf { input: n }));
8283        assert!(is_backend_neutral(&WorkItemKind::SlotView { producer: n }));
8284        // Contiguize runs on its input's backend; its own `target_backend` is a
8285        // placeholder, so it must not count as a backend switch.
8286        assert!(is_backend_neutral(&WorkItemKind::ContiguizeOf { input: n }));
8287        // Sabotage siblings: anything that runs a kernel of its own or moves bytes
8288        // across devices is NOT, so a real backend switch still arms the
8289        // chunk-boundary logic.
8290        assert!(!is_backend_neutral(&WorkItemKind::Kernel));
8291        assert!(!is_backend_neutral(&WorkItemKind::Copy {
8292            target_location: DeviceLocation::Cpu
8293        }));
8294        assert!(!is_backend_neutral(&WorkItemKind::WriteSlice {
8295            dest: n,
8296            source: n
8297        }));
8298    }
8299}
8300
8301#[cfg(test)]
8302mod tests {
8303    // ---- GAP-380 (a2): the plan-time arm guard ----------------------------------------------
8304
8305    fn iota_graph(backend: BackendId) -> (Graph, NodeId) {
8306        let mut g = Graph::new();
8307        let id = g.push(Node {
8308            op: Op::Iota { len: 4 },
8309            inputs: vec![],
8310            shape: fuel_ir::Shape::from_dims(&[4]),
8311            dtype: DType::F32,
8312        });
8313        g.set_target_backend(id, backend);
8314        (g, id)
8315    }
8316
8317    #[test]
8318    fn an_iota_on_a_backend_with_no_arm_fails_at_plan_time_naming_node_and_op() {
8319        let (g, id) = iota_graph(BackendId::Vulkan);
8320        let err = check_direct_arms_wired(&g, &[id])
8321            .expect_err("Vulkan has no Iota arm")
8322            .to_string();
8323        assert!(
8324            err.contains(&format!("Node#{}", id.0)),
8325            "names the node: {err}"
8326        );
8327        assert!(err.contains("Iota"), "names the op: {err}");
8328        assert!(err.contains("Vulkan"), "names the backend: {err}");
8329    }
8330
8331    /// Sabotage siblings: the same guard passes where the arm IS wired, so the red above is the
8332    /// missing arm and not the guard rejecting everything.
8333    #[test]
8334    fn an_iota_on_cpu_passes_the_arm_guard_and_other_ops_are_not_direct_dispatched() {
8335        let (g, id) = iota_graph(BackendId::Cpu);
8336        check_direct_arms_wired(&g, &[id]).expect("CPU Iota is wired");
8337        assert_eq!(
8338            direct_arm_wired(&Op::Add, BackendId::Cuda),
8339            None,
8340            "Add goes through the binding table"
8341        );
8342        assert_eq!(
8343            direct_arm_wired(&Op::Iota { len: 1 }, BackendId::Cpu),
8344            Some(true)
8345        );
8346        assert_eq!(
8347            direct_arm_wired(&Op::Iota { len: 1 }, BackendId::Cuda),
8348            Some(cfg!(feature = "cuda")),
8349            "the CUDA arm is wired exactly when the cuda feature compiles it"
8350        );
8351    }
8352
8353    use super::*;
8354    use fuel_graph::Node;
8355    use fuel_ir::Shape;
8356
8357    /// Task 5 (C6): `Op::Scan` has no native kernel in Phase 1 — it is
8358    /// always lowered/re-fused before execution — so `op_to_op_kind` must
8359    /// fall through its `_ => None` wildcard for it, exactly like any other
8360    /// not-yet-wired op. Regression lock, not born-red: this is expected to
8361    /// pass immediately.
8362    #[test]
8363    fn scan_has_no_dispatch_op_kind() {
8364        use fuel_graph::{Op, ScanEmit};
8365        assert_eq!(
8366            crate::pipelined::op_to_op_kind(&Op::Scan {
8367                n_carries: 1,
8368                n_xs: 0,
8369                bound: 2,
8370                emit: ScanEmit::All,
8371                early_exit: None
8372            }),
8373            None,
8374        );
8375    }
8376
8377    /// Step E A4b open question #4 — "event only where waited", step 1.
8378    /// `build_wait_set` collects exactly the producers of `Op::Copy`/`Move`
8379    /// nodes in the order: a same-device-only node (never copied/moved) must
8380    /// be ABSENT, and the Copy's own node id must not appear either (it is
8381    /// not its own producer).
8382    #[test]
8383    fn build_wait_set_collects_only_cross_device_copy_producers() {
8384        let mut g = Graph::new();
8385        let const_id = g.push(Node {
8386            op: Op::Const,
8387            inputs: vec![],
8388            shape: Shape::from_dims(&[4]),
8389            dtype: DType::F32,
8390        });
8391        // Same-device-only consumer of const_id — never fed into a Copy/Move.
8392        let same_device_id = g.push(Node {
8393            op: Op::Contiguize,
8394            inputs: vec![const_id],
8395            shape: Shape::from_dims(&[4]),
8396            dtype: DType::F32,
8397        });
8398        // A cross-device Copy whose producer is `same_device_id`.
8399        let copy_id = g.push(Node {
8400            op: Op::Copy {
8401                target: DeviceLocation::Cuda { gpu_id: 0 },
8402            },
8403            inputs: vec![same_device_id],
8404            shape: Shape::from_dims(&[4]),
8405            dtype: DType::F32,
8406        });
8407        let order = vec![const_id, same_device_id, copy_id];
8408
8409        let set = build_wait_set(&g, &order);
8410        assert!(
8411            set.contains(&same_device_id),
8412            "the Copy's producer must be in the wait set"
8413        );
8414        assert!(
8415            !set.contains(&const_id),
8416            "a node with no Copy/Move consumer must be absent from the wait set"
8417        );
8418        assert!(
8419            !set.contains(&copy_id),
8420            "the Copy node itself is not its own producer"
8421        );
8422        assert_eq!(
8423            set.len(),
8424            1,
8425            "only the one true cross-device producer is in the set"
8426        );
8427    }
8428
8429    /// A `Move` producer is collected the same way as a `Copy` producer.
8430    #[test]
8431    fn build_wait_set_collects_move_producers_too() {
8432        let mut g = Graph::new();
8433        let const_id = g.push(Node {
8434            op: Op::Const,
8435            inputs: vec![],
8436            shape: Shape::from_dims(&[4]),
8437            dtype: DType::F32,
8438        });
8439        let move_id = g.push(Node {
8440            op: Op::Move {
8441                target: DeviceLocation::Cpu,
8442            },
8443            inputs: vec![const_id],
8444            shape: Shape::from_dims(&[4]),
8445            dtype: DType::F32,
8446        });
8447        let order = vec![const_id, move_id];
8448
8449        let set = build_wait_set(&g, &order);
8450        assert!(
8451            set.contains(&const_id),
8452            "the Move's producer must be in the wait set"
8453        );
8454        assert_eq!(set.len(), 1);
8455    }
8456
8457    /// A CPU-only order (no `Op::Copy`/`Op::Move` anywhere) yields an empty
8458    /// wait set — every node in it is eligible for elision.
8459    #[test]
8460    fn build_wait_set_is_empty_for_cpu_only_order() {
8461        let mut g = Graph::new();
8462        let const_id = g.push(Node {
8463            op: Op::Const,
8464            inputs: vec![],
8465            shape: Shape::from_dims(&[4]),
8466            dtype: DType::F32,
8467        });
8468        let contig_id = g.push(Node {
8469            op: Op::Contiguize,
8470            inputs: vec![const_id],
8471            shape: Shape::from_dims(&[4]),
8472            dtype: DType::F32,
8473        });
8474        let order = vec![const_id, contig_id];
8475
8476        let set = build_wait_set(&g, &order);
8477        assert!(
8478            set.is_empty(),
8479            "a CPU-only order (no Copy/Move) yields an empty wait set"
8480        );
8481    }
8482
8483    /// `will_be_waited`'s two arms: the conservative `None` fallback (the
8484    /// `OrderSource::Streaming` case) is always `true`; a `Some(set)` checks
8485    /// membership.
8486    #[test]
8487    fn will_be_waited_none_is_conservative_true_for_any_node() {
8488        let ws: WaitSet = None;
8489        assert!(will_be_waited(&ws, NodeId(0)));
8490        assert!(will_be_waited(&ws, NodeId(12345)));
8491    }
8492
8493    #[test]
8494    fn will_be_waited_some_checks_membership() {
8495        let mut set = HashSet::new();
8496        set.insert(NodeId(3));
8497        let ws: WaitSet = Some(set);
8498        assert!(will_be_waited(&ws, NodeId(3)), "member must be waited");
8499        assert!(!will_be_waited(&ws, NodeId(4)), "non-member must be elided");
8500    }
8501
8502    /// A4b-1 test double: a `Completion` whose `wait` flips a shared flag, so a
8503    /// test can observe whether the drain actually waited it.
8504    struct FlagCompletion(std::sync::Arc<std::sync::atomic::AtomicUsize>);
8505    impl crate::compiled::Completion for FlagCompletion {
8506        fn wait(self: Box<Self>) -> Result<()> {
8507            self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
8508            Ok(())
8509        }
8510    }
8511
8512    /// A4b-1: `store_handle` keeps only `Pending` handles (so the post-drain
8513    /// empty-map assert is meaningful and the drain is O(pending)), and
8514    /// `drain_handles` waits each pending handle exactly once then empties the map.
8515    #[test]
8516    fn handle_map_stores_pending_and_drains_once() {
8517        use std::sync::Arc as StdArc;
8518        use std::sync::atomic::{AtomicUsize, Ordering};
8519
8520        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
8521
8522        // Ready handles are not stored.
8523        store_handle(&mut handles, NodeId(1), CompletionHandle::Ready);
8524        assert!(handles.is_empty(), "Ready handles must not be stored");
8525
8526        // Two pending handles are stored and each waited once on drain.
8527        let waited = StdArc::new(AtomicUsize::new(0));
8528        store_handle(
8529            &mut handles,
8530            NodeId(2),
8531            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8532        );
8533        store_handle(
8534            &mut handles,
8535            NodeId(3),
8536            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8537        );
8538        assert_eq!(handles.len(), 2);
8539
8540        drain_handles(&mut handles).expect("drain");
8541        assert_eq!(
8542            waited.load(Ordering::SeqCst),
8543            2,
8544            "each pending handle waited once"
8545        );
8546        assert!(handles.is_empty(), "map empty after drain");
8547    }
8548
8549    /// A4b-1: re-keying a NodeId with a new Pending handle waits the prior one
8550    /// (no leaked async work), and storing `Ready` over a prior Pending also
8551    /// waits it. Defensive — NodeIds are unique per realize in practice.
8552    #[test]
8553    fn handle_map_rekey_waits_previous() {
8554        use std::sync::Arc as StdArc;
8555        use std::sync::atomic::{AtomicUsize, Ordering};
8556
8557        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
8558        let waited = StdArc::new(AtomicUsize::new(0));
8559
8560        store_handle(
8561            &mut handles,
8562            NodeId(7),
8563            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8564        );
8565        // Re-key with another Pending → prior is waited.
8566        store_handle(
8567            &mut handles,
8568            NodeId(7),
8569            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8570        );
8571        assert_eq!(
8572            waited.load(Ordering::SeqCst),
8573            1,
8574            "rekey waited the prior pending"
8575        );
8576
8577        // Store Ready over the live Pending → it is waited too.
8578        store_handle(&mut handles, NodeId(7), CompletionHandle::Ready);
8579        assert_eq!(
8580            waited.load(Ordering::SeqCst),
8581            2,
8582            "Ready-over-Pending waited it"
8583        );
8584        assert!(handles.is_empty());
8585
8586        drain_handles(&mut handles).expect("drain empty");
8587    }
8588
8589    /// A4b-3: `wait_producer_handle` waits the named producer's handle EXACTLY
8590    /// once and removes it from the map (the finer cross-device source-drain
8591    /// consumes the producer's completion before the Copy reads its buffer), and
8592    /// is a no-op for an absent producer (CPU / Vulkan-`Ready` source, or an
8593    /// already-consumed handle). The realize-end drain then waits only what
8594    /// remains — no double-wait.
8595    #[test]
8596    fn wait_producer_handle_consumes_named_handle_once() {
8597        use std::sync::Arc as StdArc;
8598        use std::sync::atomic::{AtomicUsize, Ordering};
8599
8600        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
8601        let waited = StdArc::new(AtomicUsize::new(0));
8602
8603        // Two producers in flight; the Copy's source is NodeId(2).
8604        store_handle(
8605            &mut handles,
8606            NodeId(2),
8607            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8608        );
8609        store_handle(
8610            &mut handles,
8611            NodeId(5),
8612            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8613        );
8614
8615        // Absent producer → no-op (a CPU/Vulkan-Ready source has no handle).
8616        wait_producer_handle(&mut handles, NodeId(99)).expect("absent is no-op");
8617        assert_eq!(
8618            waited.load(Ordering::SeqCst),
8619            0,
8620            "absent producer waited nothing"
8621        );
8622        assert_eq!(handles.len(), 2);
8623
8624        // The cross-device copy's source: waited once, removed from the map.
8625        wait_producer_handle(&mut handles, NodeId(2)).expect("wait source");
8626        assert_eq!(
8627            waited.load(Ordering::SeqCst),
8628            1,
8629            "source producer waited once"
8630        );
8631        assert!(!handles.contains_key(&NodeId(2)), "source handle consumed");
8632        assert!(
8633            handles.contains_key(&NodeId(5)),
8634            "unrelated handle untouched"
8635        );
8636
8637        // Re-waiting the (now absent) source is a no-op — no double-wait.
8638        wait_producer_handle(&mut handles, NodeId(2)).expect("re-wait is no-op");
8639        assert_eq!(waited.load(Ordering::SeqCst), 1, "no double-wait");
8640
8641        // Realize-end drain waits only the remaining unrelated producer.
8642        drain_handles(&mut handles).expect("drain");
8643        assert_eq!(
8644            waited.load(Ordering::SeqCst),
8645            2,
8646            "drain waited the remaining one"
8647        );
8648        assert!(handles.is_empty());
8649    }
8650
8651    /// Op::Contiguize on a contiguous-already input is zero-copy:
8652    /// the executor adopts the input Storage Arc unchanged.
8653    #[test]
8654    fn op_contiguize_zero_copy_on_contiguous_input() {
8655        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
8656
8657        let graph = Arc::new(RwLock::new(Graph::new()));
8658        let (const_id, contig_id) = {
8659            let mut g = graph.write().unwrap();
8660            let const_id = g.push(Node {
8661                op: Op::Const,
8662                inputs: vec![],
8663                shape: Shape::from_dims(&[2, 2]),
8664                dtype: DType::F32,
8665            });
8666            let contig_id = g.push(Node {
8667                op: Op::Contiguize,
8668                inputs: vec![const_id],
8669                shape: Shape::from_dims(&[2, 2]),
8670                dtype: DType::F32,
8671            });
8672            // No need to set target_backend on Contiguize — the
8673            // executor inherits or defaults to CPU.
8674            (const_id, contig_id)
8675        };
8676
8677        let mut inputs = StorageCache::new();
8678        let input_arc = Arc::new(RwLock::new(storage));
8679        let input_arc_for_compare = Arc::clone(&input_arc);
8680        inputs.insert(const_id, input_arc);
8681
8682        let (result_arc, _) =
8683            PipelinedExecutor::realize(graph, contig_id, inputs).expect("realize");
8684
8685        // Same Arc → zero-copy adoption. Compare by raw pointer.
8686        assert!(
8687            Arc::ptr_eq(&result_arc, &input_arc_for_compare),
8688            "Op::Contiguize on contiguous input must adopt the input Arc (zero copy)",
8689        );
8690    }
8691
8692    /// Op::Contiguize on a strided input (here: a transposed view)
8693    /// materializes a fresh contiguous Storage. The output bytes
8694    /// reflect the strided view's logical content, not the input
8695    /// storage's underlying memory order.
8696    #[test]
8697    fn op_contiguize_materializes_on_strided_input() {
8698        // 2x3 row-major: [[1,2,3],[4,5,6]] → transpose → 3x2:
8699        // [[1,4],[2,5],[3,6]]. The transposed view shares the
8700        // original buffer; Op::Contiguize on the transpose
8701        // materializes contiguous bytes matching the transposed
8702        // logical order.
8703        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
8704
8705        let graph = Arc::new(RwLock::new(Graph::new()));
8706        let (const_id, _transpose_id, contig_id) = {
8707            let mut g = graph.write().unwrap();
8708            let const_id = g.push(Node {
8709                op: Op::Const,
8710                inputs: vec![],
8711                shape: Shape::from_dims(&[2, 3]),
8712                dtype: DType::F32,
8713            });
8714            let transpose_id = g.push(Node {
8715                op: Op::Transpose,
8716                inputs: vec![const_id],
8717                shape: Shape::from_dims(&[3, 2]),
8718                dtype: DType::F32,
8719            });
8720            let contig_id = g.push(Node {
8721                op: Op::Contiguize,
8722                inputs: vec![transpose_id],
8723                shape: Shape::from_dims(&[3, 2]),
8724                dtype: DType::F32,
8725            });
8726            (const_id, transpose_id, contig_id)
8727        };
8728
8729        let mut inputs = StorageCache::new();
8730        inputs.insert(const_id, Arc::new(RwLock::new(storage)));
8731
8732        let (result_arc, _) =
8733            PipelinedExecutor::realize(graph, contig_id, inputs).expect("realize");
8734
8735        let guard = result_arc.read().unwrap();
8736        let cpu = if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
8737            c
8738        } else {
8739            panic!("expected Cpu storage");
8740        };
8741        let typed: &[f32] = cpu.as_slice().expect("f32 cast");
8742        // Transposed logical order: [1,4,2,5,3,6].
8743        assert_eq!(
8744            typed,
8745            &[1.0, 4.0, 2.0, 5.0, 3.0, 6.0],
8746            "contiguized transpose must reflect logical (transposed) byte order",
8747        );
8748    }
8749
8750    /// E2E: 3-node graph (Const + Const + Add), pre-seeded inputs,
8751    /// realized through the compiler+executor thread pair, returns
8752    /// expected sum bytes.
8753    #[test]
8754    fn pipelined_realize_const_const_add() {
8755        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
8756        let rhs_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
8757
8758        let graph = Arc::new(RwLock::new(Graph::new()));
8759        let (lhs_id, rhs_id, add_id) = {
8760            let mut g = graph.write().unwrap();
8761            let lhs_id = g.push(Node {
8762                op: Op::Const,
8763                inputs: vec![],
8764                shape: Shape::from_dims(&[3]),
8765                dtype: DType::F32,
8766            });
8767            let rhs_id = g.push(Node {
8768                op: Op::Const,
8769                inputs: vec![],
8770                shape: Shape::from_dims(&[3]),
8771                dtype: DType::F32,
8772            });
8773            let add_id = g.push(Node {
8774                op: Op::Add,
8775                inputs: vec![lhs_id, rhs_id],
8776                shape: Shape::from_dims(&[3]),
8777                dtype: DType::F32,
8778            });
8779            g.set_target_backend(add_id, BackendId::Cpu);
8780            (lhs_id, rhs_id, add_id)
8781        };
8782
8783        let mut inputs = StorageCache::new();
8784        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
8785        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
8786
8787        let (result_arc, _result_layout) =
8788            PipelinedExecutor::realize(graph, add_id, inputs).expect("realize");
8789
8790        let guard = result_arc.read().unwrap();
8791        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
8792            let typed: &[f32] = c.as_slice().expect("f32 cast");
8793            assert_eq!(typed, &[11.0, 22.0, 33.0]);
8794        } else {
8795            panic!("expected CPU output");
8796        }
8797    }
8798
8799    /// CapturedRun executor build-out (Increment 1): capture a 2-op binary
8800    /// chain `z = (a + b) * c` THROUGH the pipelined executor's
8801    /// persistent-output mode, then prove the three capture guarantees on a
8802    /// live GPU:
8803    ///   1. after capture, the fixed output buffer holds the warm-run result
8804    ///      (capture RECORDS launches, it does not execute them);
8805    ///   2. `replay()` recomputes bit-exactly into the SAME fixed buffer;
8806    ///   3. replay reads the FIXED input addresses — overwriting an input
8807    ///      buffer in place and replaying yields the new result, matching an
8808    ///      independent uncaptured `realize`. This is the whole mechanism:
8809    ///      the write-into binary wrapper + the executor's reuse mode +
8810    ///      `capture_run` compose into a replayable decode-step graph.
8811    #[test]
8812    #[ignore = "requires a live CUDA device"]
8813    #[cfg(feature = "cuda")]
8814    fn capture_decode_binary_chain_replays_bit_exact_cuda() {
8815        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8816        use fuel_ir::Shape;
8817        use fuel_memory::BackendStorage;
8818
8819        let Ok(dev) = CudaDevice::new(0) else {
8820            return fuel_test_support::hardware::skip(
8821                fuel_test_support::hardware::Hardware::Cuda,
8822                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
8823            );
8824        };
8825
8826        // z = (a + b) * c, shape [4]. `y = a + b` is a persistent
8827        // INTERMEDIATE; `z` is the persistent target — both fixed-address.
8828        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId, NodeId, NodeId) {
8829            let graph = Arc::new(RwLock::new(Graph::new()));
8830            let (a, b, c, z) = {
8831                let mut g = graph.write().unwrap();
8832                let a = g.push(Node {
8833                    op: Op::Const,
8834                    inputs: vec![],
8835                    shape: Shape::from_dims(&[4]),
8836                    dtype: DType::F32,
8837                });
8838                let b = g.push(Node {
8839                    op: Op::Const,
8840                    inputs: vec![],
8841                    shape: Shape::from_dims(&[4]),
8842                    dtype: DType::F32,
8843                });
8844                let c = g.push(Node {
8845                    op: Op::Const,
8846                    inputs: vec![],
8847                    shape: Shape::from_dims(&[4]),
8848                    dtype: DType::F32,
8849                });
8850                let y = g.push(Node {
8851                    op: Op::Add,
8852                    inputs: vec![a, b],
8853                    shape: Shape::from_dims(&[4]),
8854                    dtype: DType::F32,
8855                });
8856                let z = g.push(Node {
8857                    op: Op::Mul,
8858                    inputs: vec![y, c],
8859                    shape: Shape::from_dims(&[4]),
8860                    dtype: DType::F32,
8861                });
8862                g.set_target_backend(y, BackendId::Cuda);
8863                g.set_target_backend(z, BackendId::Cuda);
8864                (a, b, c, z)
8865            };
8866            (graph, a, b, c, z)
8867        };
8868
8869        let up = |v: &[f32]| -> Arc<RwLock<Storage>> {
8870            let bytes: &[u8] = bytemuck::cast_slice(v);
8871            let cb = CudaStorageBytes::from_cpu_bytes(&dev, bytes).expect("h2d");
8872            Arc::new(RwLock::new(Storage::new(
8873                BackendStorage::Cuda(cb),
8874                DType::F32,
8875            )))
8876        };
8877        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8878            let g = arc.read().unwrap();
8879            let BackendStorage::Cuda(c) = &g.inner else {
8880                panic!("not cuda")
8881            };
8882            let host = c.to_cpu_bytes().expect("d2h");
8883            bytemuck::cast_slice(&host).to_vec()
8884        };
8885
8886        let a_data = [1.0_f32, 2.0, 3.0, 4.0];
8887        let b_data = [10.0_f32, 20.0, 30.0, 40.0];
8888        let c_data = [2.0_f32, 2.0, 2.0, 2.0];
8889        let expect0 = [22.0_f32, 44.0, 66.0, 88.0]; // (a+b)*c
8890
8891        // Fixed input Arcs (shared into capture; overwritten in place later).
8892        let a_arc = up(&a_data);
8893        let b_arc = up(&b_data);
8894        let c_arc = up(&c_data);
8895
8896        let (graph, a, b, c, z) = build();
8897        let mut inputs = StorageCache::new();
8898        inputs.insert(a, a_arc.clone());
8899        inputs.insert(b, b_arc.clone());
8900        inputs.insert(c, c_arc.clone());
8901
8902        let captured =
8903            PipelinedExecutor::capture_decode(Arc::clone(&graph), z, inputs, SymEnv::default())
8904                .expect("capture_decode");
8905
8906        // (1) warm-run result sits in the captured output buffer.
8907        assert_eq!(
8908            read(&captured.output),
8909            &expect0,
8910            "warm-run result after capture"
8911        );
8912
8913        // (2) replay with the same inputs recomputes bit-exactly.
8914        captured.run.replay(&dev).expect("replay");
8915        dev.synchronize().expect("sync");
8916        assert_eq!(read(&captured.output), &expect0, "replay reproduces result");
8917
8918        // (3) overwrite input `a` IN PLACE (same device address), replay ->
8919        //     the new result flows from the FIXED input address. Compare to
8920        //     an independent uncaptured realize with the same new input.
8921        let a2 = [100.0_f32, 200.0, 300.0, 400.0];
8922        {
8923            let g = a_arc.read().unwrap();
8924            let BackendStorage::Cuda(c) = &g.inner else {
8925                panic!("a not cuda")
8926            };
8927            c.write_from_host(bytemuck::cast_slice(&a2))
8928                .expect("in-place H2D");
8929        }
8930        captured.run.replay(&dev).expect("replay 2");
8931        dev.synchronize().expect("sync 2");
8932        let got = read(&captured.output);
8933
8934        let (graph_ref, ar, br, cr, zr) = build();
8935        let mut inputs_ref = StorageCache::new();
8936        inputs_ref.insert(ar, up(&a2));
8937        inputs_ref.insert(br, up(&b_data));
8938        inputs_ref.insert(cr, up(&c_data));
8939        let (ref_arc, _) =
8940            PipelinedExecutor::realize(graph_ref, zr, inputs_ref).expect("ref realize");
8941        let expect1 = read(&ref_arc); // (a2+b)*c = [220,440,660,880]
8942        assert_eq!(
8943            got, expect1,
8944            "replay after in-place input update matches uncaptured realize"
8945        );
8946        assert_eq!(expect1, vec![220.0, 440.0, 660.0, 880.0]);
8947    }
8948
8949    /// CapturedRun executor build-out (Increment 3): capture a DECODE-SHAPED
8950    /// graph — the full dense op-set composing in one capture — and prove it
8951    /// replays bit-exactly against an independent uncaptured realize.
8952    ///
8953    /// Graph (an FFN block + norms, batch=seq=1 like real decode):
8954    ///   n1 = rms_norm(x);  u = n1 · w_up;  s = silu(u);
8955    /// cuBLAS `gemm_dense` matmul IS graph-capturable (regression for the
8956    /// dangling-input bug that once masqueraded as "cuBLAS not replay-safe").
8957    /// Captures `y = a·w` where the caller does NOT retain `w`, FORCES the
8958    /// freed-`w` slot to be reused by garbage buffers, then replays 50× — all
8959    /// must equal the uncaptured realize. Passes iff `capture_decode` retains
8960    /// its input buffers (`CapturedDecode::retained_inputs`).
8961    #[test]
8962    #[ignore = "requires a live CUDA device"]
8963    #[cfg(feature = "cuda")]
8964    fn capture_decode_matmul_replays_bit_exact_cuda() {
8965        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
8966        use fuel_ir::Shape;
8967        use fuel_memory::BackendStorage;
8968        let Ok(dev) = CudaDevice::new(0) else { return };
8969        const H: usize = 4;
8970        const F: usize = 8;
8971        let a_data: Vec<f32> = (0..H).map(|i| 0.5 + i as f32).collect();
8972        let w_data: Vec<f32> = (0..H * F).map(|i| 0.01 * (i as f32 + 1.0)).collect();
8973        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId, NodeId) {
8974            let graph = Arc::new(RwLock::new(Graph::new()));
8975            let (a, w, y) = {
8976                let mut g = graph.write().unwrap();
8977                let a = g.push(Node {
8978                    op: Op::Const,
8979                    inputs: vec![],
8980                    shape: Shape::from_dims(&[1, H]),
8981                    dtype: DType::F32,
8982                });
8983                let w = g.push(Node {
8984                    op: Op::Const,
8985                    inputs: vec![],
8986                    shape: Shape::from_dims(&[H, F]),
8987                    dtype: DType::F32,
8988                });
8989                let y = g.push(Node {
8990                    op: Op::MatMul,
8991                    inputs: vec![a, w],
8992                    shape: Shape::from_dims(&[1, F]),
8993                    dtype: DType::F32,
8994                });
8995                g.set_target_backend(y, BackendId::Cuda);
8996                (a, w, y)
8997            };
8998            (graph, a, w, y)
8999        };
9000        let up = |v: &[f32]| {
9001            let b: Vec<u8> = v.iter().flat_map(|f| f.to_le_bytes()).collect();
9002            Arc::new(RwLock::new(Storage::new(
9003                BackendStorage::Cuda(CudaStorageBytes::from_cpu_bytes(&dev, &b).unwrap()),
9004                DType::F32,
9005            )))
9006        };
9007        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9008            let g = arc.read().unwrap();
9009            let BackendStorage::Cuda(c) = &g.inner else {
9010                panic!("not cuda")
9011            };
9012            c.to_cpu_bytes()
9013                .unwrap()
9014                .chunks_exact(4)
9015                .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
9016                .collect()
9017        };
9018        // Reference (uncaptured).
9019        let (gr, ar, wr, yr) = build();
9020        let mut insr = StorageCache::new();
9021        insr.insert(ar, up(&a_data));
9022        insr.insert(wr, up(&w_data));
9023        let (refarc, _) = PipelinedExecutor::realize(gr, yr, insr).unwrap();
9024        let expect = read(&refarc);
9025        // Capture (a + w NOT retained by caller).
9026        let (graph, a, w, y) = build();
9027        let mut inputs = StorageCache::new();
9028        inputs.insert(a, up(&a_data));
9029        inputs.insert(w, up(&w_data));
9030        let captured =
9031            PipelinedExecutor::capture_decode(Arc::clone(&graph), y, inputs, SymEnv::default())
9032                .expect("capture");
9033        assert_eq!(read(&captured.output), expect, "warm result after capture");
9034        // FORCE freed-memory reuse: same-size (H*F) garbage buffers. If `w`
9035        // were dangling, replay would read 999.0s.
9036        let mut squatters = Vec::new();
9037        for _ in 0..8 {
9038            let g: Vec<u8> = (0..H * F).flat_map(|_| 999.0f32.to_le_bytes()).collect();
9039            squatters.push(CudaStorageBytes::from_cpu_bytes(&dev, &g).unwrap());
9040        }
9041        dev.synchronize().unwrap();
9042        let mut bad = 0usize;
9043        for _ in 0..50 {
9044            captured.run.replay(&dev).unwrap();
9045            dev.synchronize().unwrap();
9046            if read(&captured.output) != expect {
9047                bad += 1;
9048            }
9049        }
9050        assert_eq!(
9051            bad, 0,
9052            "cuBLAS matmul capture replays bit-exact ({bad}/50 wrong)"
9053        );
9054    }
9055
9056    /// `Op::MulScalar` / `OpKind::Affine` (the `1/√d` attention scale) is
9057    /// capture-safe (write-into variant + forced-reuse regression).
9058    #[test]
9059    #[ignore = "requires a live CUDA device"]
9060    #[cfg(feature = "cuda")]
9061    fn capture_decode_affine_replays_bit_exact_cuda() {
9062        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
9063        use fuel_ir::Shape;
9064        use fuel_memory::BackendStorage;
9065        let Ok(dev) = CudaDevice::new(0) else { return };
9066        const N: usize = 6;
9067        let x_data: Vec<f32> = (0..N).map(|i| 1.0 + i as f32).collect();
9068        let expect: Vec<f32> = x_data.iter().map(|v| v * 0.5).collect();
9069        let graph = Arc::new(RwLock::new(Graph::new()));
9070        let (x, y) = {
9071            let mut g = graph.write().unwrap();
9072            let x = g.push(Node {
9073                op: Op::Const,
9074                inputs: vec![],
9075                shape: Shape::from_dims(&[1, N]),
9076                dtype: DType::F32,
9077            });
9078            let y = g.push(Node {
9079                op: Op::MulScalar(0.5),
9080                inputs: vec![x],
9081                shape: Shape::from_dims(&[1, N]),
9082                dtype: DType::F32,
9083            });
9084            g.set_target_backend(y, BackendId::Cuda);
9085            (x, y)
9086        };
9087        let up = |v: &[f32]| {
9088            let b: Vec<u8> = v.iter().flat_map(|f| f.to_le_bytes()).collect();
9089            Arc::new(RwLock::new(Storage::new(
9090                BackendStorage::Cuda(CudaStorageBytes::from_cpu_bytes(&dev, &b).unwrap()),
9091                DType::F32,
9092            )))
9093        };
9094        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9095            let g = arc.read().unwrap();
9096            let BackendStorage::Cuda(c) = &g.inner else {
9097                panic!("not cuda")
9098            };
9099            c.to_cpu_bytes()
9100                .unwrap()
9101                .chunks_exact(4)
9102                .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
9103                .collect()
9104        };
9105        let mut inputs = StorageCache::new();
9106        inputs.insert(x, up(&x_data));
9107        let captured =
9108            PipelinedExecutor::capture_decode(Arc::clone(&graph), y, inputs, SymEnv::default())
9109                .expect("capture");
9110        assert_eq!(read(&captured.output), expect, "warm result after capture");
9111        let mut sq = Vec::new();
9112        for _ in 0..8 {
9113            let g: Vec<u8> = (0..N).flat_map(|_| 999.0f32.to_le_bytes()).collect();
9114            sq.push(CudaStorageBytes::from_cpu_bytes(&dev, &g).unwrap());
9115        }
9116        dev.synchronize().unwrap();
9117        let mut bad = 0usize;
9118        for _ in 0..50 {
9119            captured.run.replay(&dev).unwrap();
9120            dev.synchronize().unwrap();
9121            if read(&captured.output) != expect {
9122                bad += 1;
9123            }
9124        }
9125        assert_eq!(bad, 0, "affine capture replays bit-exact ({bad}/50 wrong)");
9126    }
9127
9128    /// `index_select` (embedding lookup) IS graph-capturable (regression for
9129    /// the dangling-input bug that once looked like "element 0 dropped on
9130    /// replay"). Captures `emb = index_select(wte, tok)` with `wte` NOT
9131    /// retained by the caller, FORCES the freed-`wte` slot to be reused by
9132    /// garbage buffers, then replays 50× — all must be `[1,2,3,4]`. Passes iff
9133    /// `capture_decode` retains its input buffers.
9134    #[test]
9135    #[ignore = "requires a live CUDA device"]
9136    #[cfg(feature = "cuda")]
9137    fn capture_decode_index_select_replays_bit_exact_cuda() {
9138        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
9139        use fuel_ir::Shape;
9140        use fuel_memory::BackendStorage;
9141        let Ok(dev) = CudaDevice::new(0) else { return };
9142        const V: usize = 3;
9143        const H: usize = 4;
9144        let wte_data: Vec<f32> = (0..V)
9145            .flat_map(|v| (0..H).map(move |c| 1.0 + 10.0 * v as f32 + c as f32))
9146            .collect();
9147        let graph = Arc::new(RwLock::new(Graph::new()));
9148        let (tok, wte, emb) = {
9149            let mut g = graph.write().unwrap();
9150            let tok = g.push(Node {
9151                op: Op::Const,
9152                inputs: vec![],
9153                shape: Shape::from_dims(&[1]),
9154                dtype: DType::U32,
9155            });
9156            let wte = g.push(Node {
9157                op: Op::Const,
9158                inputs: vec![],
9159                shape: Shape::from_dims(&[V, H]),
9160                dtype: DType::F32,
9161            });
9162            let emb = g.push(Node {
9163                op: Op::IndexSelect { dim: 0 },
9164                inputs: vec![wte, tok],
9165                shape: Shape::from_dims(&[1, H]),
9166                dtype: DType::F32,
9167            });
9168            g.set_target_backend(emb, BackendId::Cuda);
9169            (tok, wte, emb)
9170        };
9171        let up_f32 = |v: &[f32]| {
9172            let b: Vec<u8> = v.iter().flat_map(|f| f.to_le_bytes()).collect();
9173            Arc::new(RwLock::new(Storage::new(
9174                BackendStorage::Cuda(CudaStorageBytes::from_cpu_bytes(&dev, &b).unwrap()),
9175                DType::F32,
9176            )))
9177        };
9178        let up_u32 = |v: &[u32]| {
9179            let b: Vec<u8> = v.iter().flat_map(|x| x.to_le_bytes()).collect();
9180            Arc::new(RwLock::new(Storage::new(
9181                BackendStorage::Cuda(CudaStorageBytes::from_cpu_bytes(&dev, &b).unwrap()),
9182                DType::U32,
9183            )))
9184        };
9185        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9186            let g = arc.read().unwrap();
9187            let BackendStorage::Cuda(c) = &g.inner else {
9188                panic!("not cuda")
9189            };
9190            c.to_cpu_bytes()
9191                .unwrap()
9192                .chunks_exact(4)
9193                .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
9194                .collect()
9195        };
9196        let tok_arc = up_u32(&[0]);
9197        let mut inputs = StorageCache::new();
9198        inputs.insert(tok, tok_arc.clone());
9199        inputs.insert(wte, up_f32(&wte_data));
9200        let captured =
9201            PipelinedExecutor::capture_decode(Arc::clone(&graph), emb, inputs, SymEnv::default())
9202                .expect("capture");
9203        assert_eq!(
9204            read(&captured.output),
9205            vec![1.0, 2.0, 3.0, 4.0],
9206            "warm result after capture"
9207        );
9208        // FORCE freed-memory reuse: same-size (V*H) garbage buffers reclaim
9209        // `wte`'s slot if it were dangling — replay would then read 999.0s.
9210        let mut squatters = Vec::new();
9211        for _ in 0..8 {
9212            let g: Vec<u8> = (0..V * H).flat_map(|_| 999.0f32.to_le_bytes()).collect();
9213            squatters.push(CudaStorageBytes::from_cpu_bytes(&dev, &g).unwrap());
9214        }
9215        dev.synchronize().unwrap();
9216        let mut bad = 0usize;
9217        for _ in 0..50 {
9218            captured.run.replay(&dev).unwrap();
9219            dev.synchronize().unwrap();
9220            if read(&captured.output) != vec![1.0, 2.0, 3.0, 4.0] {
9221                bad += 1;
9222            }
9223        }
9224        assert_eq!(
9225            bad, 0,
9226            "index_select capture replays bit-exact ({bad}/50 wrong)"
9227        );
9228    }
9229
9230    ///   n1 = rms_norm(x);  s = silu(n1);  p = softmax(s);
9231    ///   r  = p + x;  n2 = rms_norm(r);  y = n2 + x
9232    /// Exercises rms_norm (×2 — proves the per-device RMS workspace is reused
9233    /// across sequential norms inside ONE captured graph), silu + softmax
9234    /// (write-into), and residual adds through the persistent-output capture
9235    /// path. Verified across two input value-sets (robust, not luck).
9236    ///
9237    /// Deliberately EXCLUDES matmul (cuBLAS not graph-replay-safe) and
9238    /// index_select (its host-side shape/stride arrays dangle under capture —
9239    /// proven to mis-replay). Both are surfaced `capture_decode` gaps, not
9240    /// silent mis-replays. See `op_kind_is_capture_writeinto`.
9241    #[test]
9242    #[ignore = "requires a live CUDA device"]
9243    #[cfg(feature = "cuda")]
9244    fn capture_decode_norm_silu_softmax_replays_bit_exact_cuda() {
9245        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
9246        use fuel_graph::registry::{FusedOpParams, FusedOps};
9247        use fuel_ir::Shape;
9248        use fuel_memory::BackendStorage;
9249
9250        let Ok(dev) = CudaDevice::new(0) else {
9251            return fuel_test_support::hardware::skip(
9252                fuel_test_support::hardware::Hardware::Cuda,
9253                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
9254            );
9255        };
9256        const H: usize = 6;
9257        let eps = 1e-5f64;
9258
9259        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId) {
9260            let graph = Arc::new(RwLock::new(Graph::new()));
9261            let (x, y) = {
9262                let mut g = graph.write().unwrap();
9263                let mk = |g: &mut Graph, op: Op, ins: Vec<NodeId>, dims: &[usize]| {
9264                    g.push(Node {
9265                        op,
9266                        inputs: ins,
9267                        shape: Shape::from_dims(dims),
9268                        dtype: DType::F32,
9269                    })
9270                };
9271                let rms = || {
9272                    Op::Fused(
9273                        FusedOps::RMS_NORM_LAST_DIM,
9274                        FusedOpParams::RmsNormLastDim { eps },
9275                    )
9276                };
9277                let sm = || Op::Fused(FusedOps::SOFTMAX_LAST_DIM, FusedOpParams::SoftmaxLastDim);
9278                let x = mk(&mut g, Op::Const, vec![], &[1, H]);
9279                let n1 = mk(&mut g, rms(), vec![x], &[1, H]);
9280                let s = mk(&mut g, Op::Silu, vec![n1], &[1, H]);
9281                let p = mk(&mut g, sm(), vec![s], &[1, H]);
9282                let r = mk(&mut g, Op::Add, vec![p, x], &[1, H]);
9283                let n2 = mk(&mut g, rms(), vec![r], &[1, H]);
9284                let y = mk(&mut g, Op::Add, vec![n2, x], &[1, H]);
9285                for id in [n1, s, p, r, n2, y] {
9286                    g.set_target_backend(id, BackendId::Cuda);
9287                }
9288                (x, y)
9289            };
9290            (graph, x, y)
9291        };
9292
9293        let up = |v: &[f32]| -> Arc<RwLock<Storage>> {
9294            let cb = CudaStorageBytes::from_cpu_bytes(&dev, bytemuck::cast_slice(v)).expect("h2d");
9295            Arc::new(RwLock::new(Storage::new(
9296                BackendStorage::Cuda(cb),
9297                DType::F32,
9298            )))
9299        };
9300        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9301            let g = arc.read().unwrap();
9302            let BackendStorage::Cuda(c) = &g.inner else {
9303                panic!("not cuda")
9304            };
9305            bytemuck::cast_slice(&c.to_cpu_bytes().expect("d2h")).to_vec()
9306        };
9307
9308        let x_data: Vec<f32> = (0..H).map(|c| 0.1 * (c as f32 + 1.0)).collect();
9309        let x_arc = up(&x_data);
9310        let (graph, x, y) = build();
9311        let mut inputs = StorageCache::new();
9312        inputs.insert(x, x_arc.clone());
9313
9314        let captured =
9315            PipelinedExecutor::capture_decode(Arc::clone(&graph), y, inputs, SymEnv::default())
9316                .expect("capture_decode norm/silu/softmax");
9317
9318        let realize_ref = |xv: &[f32]| -> Vec<f32> {
9319            let (g, xr, yr) = build();
9320            let mut ins = StorageCache::new();
9321            ins.insert(xr, up(xv));
9322            let (arc, _) = PipelinedExecutor::realize(g, yr, ins).expect("ref realize");
9323            read(&arc)
9324        };
9325        let expect0 = realize_ref(&x_data);
9326
9327        // (1) after capture the output holds the warm result.
9328        assert_eq!(read(&captured.output), expect0, "warm result after capture");
9329        // (2) replay reproduces bit-exactly (incl. RMS workspace reuse on replay).
9330        captured.run.replay(&dev).expect("replay");
9331        dev.synchronize().expect("sync");
9332        assert_eq!(read(&captured.output), expect0, "replay reproduces result");
9333
9334        // (3) overwrite x in place, replay -> matches uncaptured realize (a
9335        //     DIFFERENT value-set — so the chain is robust, not input-lucky).
9336        let x2: Vec<f32> = (0..H).map(|c| 0.3 * (c as f32 + 1.0)).collect();
9337        {
9338            let g = x_arc.read().unwrap();
9339            let BackendStorage::Cuda(c) = &g.inner else {
9340                panic!("x not cuda")
9341            };
9342            c.write_from_host(bytemuck::cast_slice(&x2))
9343                .expect("in-place H2D");
9344        }
9345        captured.run.replay(&dev).expect("replay 2");
9346        dev.synchronize().expect("sync 2");
9347        assert_eq!(
9348            read(&captured.output),
9349            realize_ref(&x2),
9350            "replay after x update matches realize"
9351        );
9352    }
9353
9354    /// CapturedRun executor build-out (Increment 4b-γ): make `ContiguizeOf`
9355    /// (a non-contiguous reshape after `Permute` — the real decode graph's
9356    /// attention-merge reshape shape) AND a 2-input `Op::Concat` (the shape
9357    /// RoPE's CUDA decomposition emits for its rotate-half) BOTH
9358    /// capture-safe in ONE graph, so the crux 4b-γ exists for — allocation
9359    /// of an INTERMEDIATE, non-final buffer inside a capture scope — is
9360    /// actually exercised, not just each gap in isolation.
9361    ///
9362    /// Graph: `x [2,3,4] --Permute[1,0,2]--> [3,2,4]` (non-contiguous)
9363    /// `--Reshape[3,8]--> r` (`ContiguizeOf`, MUST allocate: its input is
9364    /// non-contiguous) `--Concat(dim=1, with b [3,8])--> y [3,16]` (target).
9365    #[test]
9366    #[ignore = "requires a live CUDA device"]
9367    #[cfg(feature = "cuda")]
9368    fn capture_decode_contiguize_then_concat_replays_bit_exact_cuda() {
9369        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
9370        use fuel_ir::Shape;
9371        use fuel_memory::BackendStorage;
9372
9373        let Ok(dev) = CudaDevice::new(0) else {
9374            return fuel_test_support::hardware::skip(
9375                fuel_test_support::hardware::Hardware::Cuda,
9376                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
9377            );
9378        };
9379
9380        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId, NodeId) {
9381            let graph = Arc::new(RwLock::new(Graph::new()));
9382            let (x, b, y) = {
9383                let mut g = graph.write().unwrap();
9384                let x = g.push(Node {
9385                    op: Op::Const,
9386                    inputs: vec![],
9387                    shape: Shape::from_dims(&[2, 3, 4]),
9388                    dtype: DType::F32,
9389                });
9390                let p = g.push(Node {
9391                    op: Op::Permute(vec![1, 0, 2]),
9392                    inputs: vec![x],
9393                    shape: Shape::from_dims(&[3, 2, 4]),
9394                    dtype: DType::F32,
9395                });
9396                let r = g.push(Node {
9397                    op: Op::Reshape(Shape::from_dims(&[3, 8])),
9398                    inputs: vec![p],
9399                    shape: Shape::from_dims(&[3, 8]),
9400                    dtype: DType::F32,
9401                });
9402                let b = g.push(Node {
9403                    op: Op::Const,
9404                    inputs: vec![],
9405                    shape: Shape::from_dims(&[3, 8]),
9406                    dtype: DType::F32,
9407                });
9408                let y = g.push(Node {
9409                    op: Op::Concat { dim: 1 },
9410                    inputs: vec![r, b],
9411                    shape: Shape::from_dims(&[3, 16]),
9412                    dtype: DType::F32,
9413                });
9414                g.set_target_backend(p, BackendId::Cuda);
9415                g.set_target_backend(r, BackendId::Cuda);
9416                g.set_target_backend(y, BackendId::Cuda);
9417                (x, b, y)
9418            };
9419            (graph, x, b, y)
9420        };
9421
9422        let up = |v: &[f32]| -> Arc<RwLock<Storage>> {
9423            let cb = CudaStorageBytes::from_cpu_bytes(&dev, bytemuck::cast_slice(v)).expect("h2d");
9424            Arc::new(RwLock::new(Storage::new(
9425                BackendStorage::Cuda(cb),
9426                DType::F32,
9427            )))
9428        };
9429        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9430            let g = arc.read().unwrap();
9431            let BackendStorage::Cuda(c) = &g.inner else {
9432                panic!("not cuda")
9433            };
9434            bytemuck::cast_slice(&c.to_cpu_bytes().expect("d2h")).to_vec()
9435        };
9436
9437        let x_data: Vec<f32> = (0..24).map(|i| i as f32).collect();
9438        let b_data: Vec<f32> = (0..24).map(|i| 100.0 + i as f32).collect();
9439        let x_arc = up(&x_data);
9440        let (graph, x, b, y) = build();
9441        let mut inputs = StorageCache::new();
9442        inputs.insert(x, x_arc.clone());
9443        // `b` deliberately NOT retained by a local variable — forces
9444        // reliance on `capture_decode`'s own `retained_inputs`, mirroring
9445        // the matmul/index_select regression precedent.
9446        inputs.insert(b, up(&b_data));
9447
9448        let captured =
9449            PipelinedExecutor::capture_decode(Arc::clone(&graph), y, inputs, SymEnv::default())
9450                .expect("capture_decode contiguize+concat");
9451
9452        let realize_ref = |xv: &[f32], bv: &[f32]| -> Vec<f32> {
9453            let (g, xr, br, yr) = build();
9454            let mut ins = StorageCache::new();
9455            ins.insert(xr, up(xv));
9456            ins.insert(br, up(bv));
9457            let (arc, _) = PipelinedExecutor::realize(g, yr, ins).expect("ref realize");
9458            read(&arc)
9459        };
9460        let expect0 = realize_ref(&x_data, &b_data);
9461
9462        // (1) warm-run result sits in the captured output buffer (capture
9463        //     RECORDS launches, it does not execute them at capture time).
9464        assert_eq!(read(&captured.output), expect0, "warm result after capture");
9465
9466        // (2) replay TWICE with unchanged inputs — proves the fixed-address
9467        //     reuse (both the ContiguizeOf intermediate and the Concat
9468        //     output) holds across multiple replay() calls, not just one.
9469        for i in 0..2 {
9470            captured
9471                .run
9472                .replay(&dev)
9473                .unwrap_or_else(|e| panic!("replay {i}: {e:?}"));
9474            dev.synchronize().expect("sync");
9475            assert_eq!(
9476                read(&captured.output),
9477                expect0,
9478                "replay {i} reproduces result"
9479            );
9480        }
9481
9482        // (3) overwrite x in place (a DIFFERENT value-set), replay again ->
9483        //     the new result flows from the FIXED input address, through
9484        //     the fixed ContiguizeOf intermediate, into the fixed Concat
9485        //     output — matches an independent uncaptured realize.
9486        let x2: Vec<f32> = (0..24).map(|i| 1000.0 + i as f32).collect();
9487        {
9488            let g = x_arc.read().unwrap();
9489            let BackendStorage::Cuda(c) = &g.inner else {
9490                panic!("x not cuda")
9491            };
9492            c.write_from_host(bytemuck::cast_slice(&x2))
9493                .expect("in-place H2D");
9494        }
9495        captured.run.replay(&dev).expect("replay 3");
9496        dev.synchronize().expect("sync 3");
9497        assert_eq!(
9498            read(&captured.output),
9499            realize_ref(&x2, &b_data),
9500            "replay after x update matches independent uncaptured realize"
9501        );
9502    }
9503
9504    /// CapturedRun executor build-out (Increment 4b-ζ): a same-device
9505    /// CUDA→CUDA `Op::Copy` — the shape `insert_safety_copies` emits for its
9506    /// aliasing-hazard snapshots in the real Llama decode graph — is
9507    /// capture-safe via `copy_from_cuda_wrapper`'s write-into
9508    /// `BackendStorage::Cuda` branch (`CudaStorageBytes::copy_from_device`).
9509    ///
9510    /// Graph: `x [2,4]`, `b [2,4]` --Copy{target: Cuda{0}}--> `c` (same-device
9511    /// snapshot of `x`) --Add(c, b)--> `y`. Capture, replay twice unchanged,
9512    /// then update `x` in place and replay again — every step must match an
9513    /// independent uncaptured `realize`.
9514    #[test]
9515    #[ignore = "requires a live CUDA device"]
9516    #[cfg(feature = "cuda")]
9517    fn capture_decode_same_device_copy_replays_bit_exact_cuda() {
9518        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
9519        use fuel_ir::Shape;
9520        use fuel_memory::BackendStorage;
9521
9522        let Ok(dev) = CudaDevice::new(0) else {
9523            return fuel_test_support::hardware::skip(
9524                fuel_test_support::hardware::Hardware::Cuda,
9525                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
9526            );
9527        };
9528
9529        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId, NodeId) {
9530            let graph = Arc::new(RwLock::new(Graph::new()));
9531            let (x, b, y) = {
9532                let mut g = graph.write().unwrap();
9533                let x = g.push(Node {
9534                    op: Op::Const,
9535                    inputs: vec![],
9536                    shape: Shape::from_dims(&[2, 4]),
9537                    dtype: DType::F32,
9538                });
9539                let b = g.push(Node {
9540                    op: Op::Const,
9541                    inputs: vec![],
9542                    shape: Shape::from_dims(&[2, 4]),
9543                    dtype: DType::F32,
9544                });
9545                // Same-device CUDA->CUDA copy — the write-into-safe case.
9546                let c = g.push(Node {
9547                    op: Op::Copy {
9548                        target: DeviceLocation::Cuda { gpu_id: 0 },
9549                    },
9550                    inputs: vec![x],
9551                    shape: Shape::from_dims(&[2, 4]),
9552                    dtype: DType::F32,
9553                });
9554                let y = g.push(Node {
9555                    op: Op::Add,
9556                    inputs: vec![c, b],
9557                    shape: Shape::from_dims(&[2, 4]),
9558                    dtype: DType::F32,
9559                });
9560                // Copy's target_backend = SOURCE backend (x is Cuda-resident).
9561                g.set_target_backend(c, BackendId::Cuda);
9562                g.set_target_backend(y, BackendId::Cuda);
9563                (x, b, y)
9564            };
9565            (graph, x, b, y)
9566        };
9567
9568        let up = |v: &[f32]| -> Arc<RwLock<Storage>> {
9569            let cb = CudaStorageBytes::from_cpu_bytes(&dev, bytemuck::cast_slice(v)).expect("h2d");
9570            Arc::new(RwLock::new(Storage::new(
9571                BackendStorage::Cuda(cb),
9572                DType::F32,
9573            )))
9574        };
9575        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9576            let g = arc.read().unwrap();
9577            let BackendStorage::Cuda(c) = &g.inner else {
9578                panic!("not cuda")
9579            };
9580            bytemuck::cast_slice(&c.to_cpu_bytes().expect("d2h")).to_vec()
9581        };
9582
9583        let x_data: Vec<f32> = (0..8).map(|i| i as f32).collect();
9584        let b_data: Vec<f32> = (0..8).map(|i| 100.0 + i as f32).collect();
9585        let x_arc = up(&x_data);
9586        let (graph, x, b, y) = build();
9587        let mut inputs = StorageCache::new();
9588        inputs.insert(x, x_arc.clone());
9589        // `b` deliberately NOT retained by a local variable — forces
9590        // reliance on `capture_decode`'s own `retained_inputs`.
9591        inputs.insert(b, up(&b_data));
9592
9593        let captured =
9594            PipelinedExecutor::capture_decode(Arc::clone(&graph), y, inputs, SymEnv::default())
9595                .expect("capture_decode same-device copy");
9596
9597        let realize_ref = |xv: &[f32], bv: &[f32]| -> Vec<f32> {
9598            let (g, xr, br, yr) = build();
9599            let mut ins = StorageCache::new();
9600            ins.insert(xr, up(xv));
9601            ins.insert(br, up(bv));
9602            let (arc, _) = PipelinedExecutor::realize(g, yr, ins).expect("ref realize");
9603            read(&arc)
9604        };
9605        let expect0 = realize_ref(&x_data, &b_data);
9606
9607        // (1) warm-run result sits in the captured output buffer.
9608        assert_eq!(read(&captured.output), expect0, "warm result after capture");
9609
9610        // (2) replay TWICE with unchanged inputs — the Copy's write-into
9611        //     destination buffer must stay bit-exact across replays.
9612        for i in 0..2 {
9613            captured
9614                .run
9615                .replay(&dev)
9616                .unwrap_or_else(|e| panic!("replay {i}: {e:?}"));
9617            dev.synchronize().expect("sync");
9618            assert_eq!(
9619                read(&captured.output),
9620                expect0,
9621                "replay {i} reproduces result"
9622            );
9623        }
9624
9625        // (3) overwrite x in place (a DIFFERENT value-set), replay again ->
9626        //     the Copy re-runs on the fixed input address into its fixed
9627        //     destination buffer -> matches an independent uncaptured realize.
9628        let x2: Vec<f32> = (0..8).map(|i| 1000.0 + i as f32).collect();
9629        {
9630            let g = x_arc.read().unwrap();
9631            let BackendStorage::Cuda(c) = &g.inner else {
9632                panic!("x not cuda")
9633            };
9634            c.write_from_host(bytemuck::cast_slice(&x2))
9635                .expect("in-place H2D");
9636        }
9637        captured.run.replay(&dev).expect("replay 3");
9638        dev.synchronize().expect("sync 3");
9639        assert_eq!(
9640            read(&captured.output),
9641            realize_ref(&x2, &b_data),
9642            "replay after x update matches independent uncaptured realize"
9643        );
9644    }
9645
9646    /// CapturedRun executor build-out (Increment 4b-ζ): a genuinely
9647    /// cross-device `Op::Copy` (D2H — `target: DeviceLocation::Cpu` from a
9648    /// CUDA-resident source) must still be REJECTED by `capture_decode`'s
9649    /// validation loop — a host round-trip can never be part of a CUDA
9650    /// graph capture. Fast check: no replay, just confirm the typed `Err`.
9651    #[test]
9652    #[ignore = "requires a live CUDA device"]
9653    #[cfg(feature = "cuda")]
9654    fn capture_decode_rejects_cross_device_copy_cuda() {
9655        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
9656        use fuel_ir::Shape;
9657        use fuel_memory::BackendStorage;
9658
9659        let Ok(dev) = CudaDevice::new(0) else {
9660            return fuel_test_support::hardware::skip(
9661                fuel_test_support::hardware::Hardware::Cuda,
9662                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
9663            );
9664        };
9665
9666        let graph = Arc::new(RwLock::new(Graph::new()));
9667        let (x, y) = {
9668            let mut g = graph.write().unwrap();
9669            let x = g.push(Node {
9670                op: Op::Const,
9671                inputs: vec![],
9672                shape: Shape::from_dims(&[2, 4]),
9673                dtype: DType::F32,
9674            });
9675            // Genuinely cross-device: D2H.
9676            let y = g.push(Node {
9677                op: Op::Copy {
9678                    target: DeviceLocation::Cpu,
9679                },
9680                inputs: vec![x],
9681                shape: Shape::from_dims(&[2, 4]),
9682                dtype: DType::F32,
9683            });
9684            g.set_target_backend(y, BackendId::Cuda); // source backend = Cuda
9685            (x, y)
9686        };
9687
9688        let x_data: Vec<f32> = (0..8).map(|i| i as f32).collect();
9689        let cb =
9690            CudaStorageBytes::from_cpu_bytes(&dev, bytemuck::cast_slice(&x_data)).expect("h2d");
9691        let x_arc = Arc::new(RwLock::new(Storage::new(
9692            BackendStorage::Cuda(cb),
9693            DType::F32,
9694        )));
9695        let mut inputs = StorageCache::new();
9696        inputs.insert(x, x_arc);
9697
9698        let result = PipelinedExecutor::capture_decode(graph, y, inputs, SymEnv::default());
9699        let msg = match result {
9700            Ok(_) => panic!("D2H Op::Copy must be rejected by capture_decode"),
9701            Err(e) => e.to_string(),
9702        };
9703        assert!(
9704            msg.contains("cross-device"),
9705            "error should describe the cross-device rejection: {msg}"
9706        );
9707    }
9708
9709    /// CapturedDecodeSession (Increment 4a): drive the warm→capture→replay
9710    /// orchestration over MANY tokens on a synthetic decode-shaped session —
9711    /// the real per-token decode pattern. Capture once, then per token
9712    /// H2D-update the fixed input buffer IN PLACE + replay, asserting each
9713    /// token's output is bit-exact against an independent uncaptured realize.
9714    /// A kernel-agnostic proof of the state machine + fixed-buffer mechanics
9715    /// (matmul + index_select excluded pending baracuda capture-safe kernels).
9716    #[test]
9717    #[ignore = "requires a live CUDA device"]
9718    #[cfg(feature = "cuda")]
9719    fn captured_decode_session_replays_many_tokens_cuda() {
9720        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
9721        use fuel_graph::registry::{FusedOpParams, FusedOps};
9722        use fuel_ir::Shape;
9723        use fuel_memory::BackendStorage;
9724
9725        let Ok(dev) = CudaDevice::new(0) else {
9726            return fuel_test_support::hardware::skip(
9727                fuel_test_support::hardware::Hardware::Cuda,
9728                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
9729            );
9730        };
9731        const H: usize = 6;
9732        let eps = 1e-5f64;
9733
9734        let build = || -> (Arc<RwLock<Graph>>, NodeId, NodeId) {
9735            let graph = Arc::new(RwLock::new(Graph::new()));
9736            let (x, y) = {
9737                let mut g = graph.write().unwrap();
9738                let mk = |g: &mut Graph, op: Op, ins: Vec<NodeId>, dims: &[usize]| {
9739                    g.push(Node {
9740                        op,
9741                        inputs: ins,
9742                        shape: Shape::from_dims(dims),
9743                        dtype: DType::F32,
9744                    })
9745                };
9746                let rms = || {
9747                    Op::Fused(
9748                        FusedOps::RMS_NORM_LAST_DIM,
9749                        FusedOpParams::RmsNormLastDim { eps },
9750                    )
9751                };
9752                let sm = || Op::Fused(FusedOps::SOFTMAX_LAST_DIM, FusedOpParams::SoftmaxLastDim);
9753                let x = mk(&mut g, Op::Const, vec![], &[1, H]);
9754                let n1 = mk(&mut g, rms(), vec![x], &[1, H]);
9755                let s = mk(&mut g, Op::Silu, vec![n1], &[1, H]);
9756                let p = mk(&mut g, sm(), vec![s], &[1, H]);
9757                let r = mk(&mut g, Op::Add, vec![p, x], &[1, H]);
9758                let n2 = mk(&mut g, rms(), vec![r], &[1, H]);
9759                let y = mk(&mut g, Op::Add, vec![n2, x], &[1, H]);
9760                for id in [n1, s, p, r, n2, y] {
9761                    g.set_target_backend(id, BackendId::Cuda);
9762                }
9763                (x, y)
9764            };
9765            (graph, x, y)
9766        };
9767        let up = |v: &[f32]| -> Arc<RwLock<Storage>> {
9768            let cb = CudaStorageBytes::from_cpu_bytes(&dev, bytemuck::cast_slice(v)).expect("h2d");
9769            Arc::new(RwLock::new(Storage::new(
9770                BackendStorage::Cuda(cb),
9771                DType::F32,
9772            )))
9773        };
9774        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9775            let g = arc.read().unwrap();
9776            let BackendStorage::Cuda(c) = &g.inner else {
9777                panic!("not cuda")
9778            };
9779            bytemuck::cast_slice(&c.to_cpu_bytes().expect("d2h")).to_vec()
9780        };
9781        let realize_ref = |xv: &[f32]| -> Vec<f32> {
9782            let (g, xr, yr) = build();
9783            let mut ins = StorageCache::new();
9784            ins.insert(xr, up(xv));
9785            let (arc, _) = PipelinedExecutor::realize(g, yr, ins).expect("ref realize");
9786            read(&arc)
9787        };
9788
9789        // 5 distinct "tokens" (distinct per-token input value-sets).
9790        let tokens: Vec<Vec<f32>> = (0..5)
9791            .map(|t| {
9792                (0..H)
9793                    .map(|c| 0.1 * (t as f32 + 1.0) * (c as f32 + 1.0))
9794                    .collect()
9795            })
9796            .collect();
9797
9798        // Capture ONCE against token 0's fixed input buffer.
9799        let x_arc = up(&tokens[0]);
9800        let (graph, x, y) = build();
9801        let mut inputs = StorageCache::new();
9802        inputs.insert(x, x_arc.clone());
9803        let session =
9804            CapturedDecodeSession::capture(Arc::clone(&graph), y, inputs, &[x], SymEnv::default())
9805                .expect("capture session");
9806
9807        // Warm result (token 0) already sits in the output buffer.
9808        assert_eq!(
9809            read(session.output()),
9810            realize_ref(&tokens[0]),
9811            "warm token 0"
9812        );
9813
9814        // The decode loop: replay every token (incl. re-replaying token 0) via
9815        // in-place H2D update of the fixed input + one graph launch.
9816        for (t, tok) in tokens.iter().enumerate() {
9817            let out = session
9818                .replay_token(&[(x, bytemuck::cast_slice(tok))])
9819                .expect("replay_token");
9820            assert_eq!(
9821                read(&out),
9822                realize_ref(tok),
9823                "replayed token {t} matches uncaptured realize"
9824            );
9825        }
9826        // Distinct tokens must give distinct outputs (live recompute, not stale).
9827        assert_ne!(
9828            realize_ref(&tokens[0]),
9829            realize_ref(&tokens[1]),
9830            "tokens must differ"
9831        );
9832    }
9833
9834    /// PR-C1 behavior contract: `realize_with_optimized_route` with an
9835    /// **empty** route (the no-pressure / no-telemetry case) is
9836    /// byte-identical to `realize_with_optimized` (arm-0). On a branchless
9837    /// graph the route has no branches to resolve, so both must produce
9838    /// the same bytes — realize is unchanged from Phase B.
9839    #[test]
9840    fn realize_with_optimized_route_empty_equals_arm0() {
9841        use crate::optimize::OptimizedGraph;
9842
9843        let build = || {
9844            let graph = Arc::new(RwLock::new(Graph::new()));
9845            let (lhs_id, rhs_id, add_id) = {
9846                let mut g = graph.write().unwrap();
9847                let lhs_id = g.push(Node {
9848                    op: Op::Const,
9849                    inputs: vec![],
9850                    shape: Shape::from_dims(&[3]),
9851                    dtype: DType::F32,
9852                });
9853                let rhs_id = g.push(Node {
9854                    op: Op::Const,
9855                    inputs: vec![],
9856                    shape: Shape::from_dims(&[3]),
9857                    dtype: DType::F32,
9858                });
9859                let add_id = g.push(Node {
9860                    op: Op::Add,
9861                    inputs: vec![lhs_id, rhs_id],
9862                    shape: Shape::from_dims(&[3]),
9863                    dtype: DType::F32,
9864                });
9865                g.set_target_backend(add_id, BackendId::Cpu);
9866                (lhs_id, rhs_id, add_id)
9867            };
9868            let mut inputs = StorageCache::new();
9869            inputs.insert(
9870                lhs_id,
9871                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9872                    1.0_f32, 2.0, 3.0,
9873                ]))),
9874            );
9875            inputs.insert(
9876                rhs_id,
9877                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9878                    10.0_f32, 20.0, 30.0,
9879                ]))),
9880            );
9881            (graph, add_id, inputs)
9882        };
9883
9884        let read_bytes = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9885            let guard = arc.read().unwrap();
9886            match &guard.inner {
9887                fuel_memory::BackendStorage::Cpu(c) => {
9888                    c.as_slice::<f32>().expect("f32 cast").to_vec()
9889                }
9890                _ => panic!("expected CPU output"),
9891            }
9892        };
9893
9894        // Stamp the fixture with the LIVE topology generation rather than a
9895        // hard-coded 0. The executor's chunk-boundary check compares the plan's
9896        // stamped generation against `topology_generation()`; a real
9897        // `OptimizedGraph` carries the generation snapshotted at optimize time
9898        // (`plan.rs` `compile_plan`, which reads it *after* the bindings table
9899        // is warm), so it already reflects every registered backend. Force
9900        // `global_bindings()` init here so any feature-gated auto-registration
9901        // has run and settled the counter before we read it — otherwise a stale
9902        // read would be bumped out from under us the first time realize warms
9903        // the bindings. Under default features this is 0; under
9904        // `--features vulkan`, `register_derived_gpu_caps` bumps it to 1.
9905        drop(global_bindings());
9906        let live_gen = crate::dispatch::topology_generation();
9907
9908        // Arm-0 path.
9909        let (g_a, add_a, in_a) = build();
9910        let opt_a = OptimizedGraph {
9911            roots: vec![add_a],
9912            generation: live_gen,
9913            placements: None,
9914            eviction: None,
9915        };
9916        let (arm0_arc, _) = PipelinedExecutor::realize_with_optimized(g_a, add_a, in_a, &opt_a)
9917            .expect("arm-0 realize");
9918        let arm0 = read_bytes(&arm0_arc);
9919
9920        // Empty-route path — must match arm-0 exactly.
9921        let (g_r, add_r, in_r) = build();
9922        let opt_r = OptimizedGraph {
9923            roots: vec![add_r],
9924            generation: live_gen,
9925            placements: None,
9926            eviction: None,
9927        };
9928        let empty_route = PickedRoute::new();
9929        let (route_arc, _) =
9930            PipelinedExecutor::realize_with_optimized_route(g_r, add_r, in_r, &opt_r, &empty_route)
9931                .expect("empty-route realize");
9932        let routed = read_bytes(&route_arc);
9933
9934        assert_eq!(arm0, vec![11.0, 22.0, 33.0]);
9935        assert_eq!(
9936            routed, arm0,
9937            "an empty route realizes byte-identically to arm-0 (Phase B contract)",
9938        );
9939    }
9940
9941    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
9942    /// §5): [`PipelinedExecutor::realize_with_optimized_picking_cached_env`]
9943    /// over a shared `order_cache` must (a) realize byte-identically to the
9944    /// uncached arm-0 path, on both the cold (empty cache) and warm
9945    /// (populated cache) call, and (b) actually populate the cache on the
9946    /// first call rather than silently never using it.
9947    #[test]
9948    fn realize_with_optimized_picking_cached_env_matches_arm0_cold_and_warm() {
9949        use crate::optimize::OptimizedGraph;
9950        use std::sync::OnceLock;
9951
9952        let build = || {
9953            let graph = Arc::new(RwLock::new(Graph::new()));
9954            let (lhs_id, rhs_id, add_id) = {
9955                let mut g = graph.write().unwrap();
9956                let lhs_id = g.push(Node {
9957                    op: Op::Const,
9958                    inputs: vec![],
9959                    shape: Shape::from_dims(&[3]),
9960                    dtype: DType::F32,
9961                });
9962                let rhs_id = g.push(Node {
9963                    op: Op::Const,
9964                    inputs: vec![],
9965                    shape: Shape::from_dims(&[3]),
9966                    dtype: DType::F32,
9967                });
9968                let add_id = g.push(Node {
9969                    op: Op::Add,
9970                    inputs: vec![lhs_id, rhs_id],
9971                    shape: Shape::from_dims(&[3]),
9972                    dtype: DType::F32,
9973                });
9974                g.set_target_backend(add_id, BackendId::Cpu);
9975                (lhs_id, rhs_id, add_id)
9976            };
9977            let mut inputs = StorageCache::new();
9978            inputs.insert(
9979                lhs_id,
9980                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9981                    1.0_f32, 2.0, 3.0,
9982                ]))),
9983            );
9984            inputs.insert(
9985                rhs_id,
9986                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9987                    10.0_f32, 20.0, 30.0,
9988                ]))),
9989            );
9990            (graph, add_id, inputs)
9991        };
9992        let read_bytes = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9993            let guard = arc.read().unwrap();
9994            match &guard.inner {
9995                fuel_memory::BackendStorage::Cpu(c) => {
9996                    c.as_slice::<f32>().expect("f32 cast").to_vec()
9997                }
9998                _ => panic!("expected CPU output"),
9999            }
10000        };
10001
10002        drop(global_bindings());
10003        let live_gen = crate::dispatch::topology_generation();
10004
10005        let (g, add, inputs) = build();
10006        let optimized = OptimizedGraph {
10007            roots: vec![add],
10008            generation: live_gen,
10009            placements: None,
10010            eviction: None,
10011        };
10012        let order_cache: OnceLock<Vec<NodeId>> = OnceLock::new();
10013        assert!(order_cache.get().is_none(), "sanity: cache starts empty");
10014
10015        // Cold call: cache miss, must compute AND populate.
10016        let (cold_arc, _) = PipelinedExecutor::realize_with_optimized_picking_cached_env(
10017            g.clone(),
10018            add,
10019            inputs,
10020            &optimized,
10021            &order_cache,
10022            None,
10023            None,
10024            SymEnv::default(),
10025        )
10026        .expect("cold cached realize");
10027        assert_eq!(read_bytes(&cold_arc), vec![11.0, 22.0, 33.0]);
10028        assert!(
10029            order_cache.get().is_some(),
10030            "the cold call must populate order_cache, not leave it empty"
10031        );
10032        let cached_order_after_cold = order_cache.get().unwrap().clone();
10033
10034        // Warm call: cache hit. Fresh inputs (same graph, new values) so the
10035        // realized OUTPUT differs from the cold call while the dispatch
10036        // ORDER (what's cached) must not change.
10037        let mut warm_inputs = StorageCache::new();
10038        warm_inputs.insert(
10039            g.read().unwrap().node(add).inputs[0],
10040            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
10041                100.0_f32, 200.0, 300.0,
10042            ]))),
10043        );
10044        warm_inputs.insert(
10045            g.read().unwrap().node(add).inputs[1],
10046            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
10047                1.0_f32, 2.0, 3.0,
10048            ]))),
10049        );
10050        let (warm_arc, _) = PipelinedExecutor::realize_with_optimized_picking_cached_env(
10051            g,
10052            add,
10053            warm_inputs,
10054            &optimized,
10055            &order_cache,
10056            None,
10057            None,
10058            SymEnv::default(),
10059        )
10060        .expect("warm cached realize");
10061        assert_eq!(
10062            read_bytes(&warm_arc),
10063            vec![101.0, 202.0, 303.0],
10064            "warm call must realize its OWN rebound inputs, not replay stale output",
10065        );
10066        assert_eq!(
10067            order_cache.get().unwrap(),
10068            &cached_order_after_cold,
10069            "the warm call must reuse the SAME cached order, not recompute a different one",
10070        );
10071    }
10072
10073    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
10074    /// §5), PM review question: does `OrderSource::Cached` weaken the
10075    /// existing `TopologyChanged` chunk-boundary check? No — proven at the
10076    /// unit level (not a live topology-bump integration test, deliberately:
10077    /// `bump_topology_generation()` mutates a process-wide atomic shared by
10078    /// every concurrently-running test in this binary, including the cold/
10079    /// warm cache test above, which reads it into a local at the start of
10080    /// ITS OWN body and would flake if another test's bump landed mid-call;
10081    /// introducing that cross-test hazard isn't worth it when the two arms'
10082    /// `generation_for` expressions are provably identical). `generation_for`
10083    /// is private to this module, so it's tested directly here: given the
10084    /// SAME `&OptimizedGraph`, `Cached` and `Optimized` must report the
10085    /// IDENTICAL generation — the chunk-boundary check that compares this
10086    /// value against the LIVE `topology_generation()` fires exactly the
10087    /// same way for both, so caching cannot silently skip or weaken it.
10088    #[test]
10089    fn cached_generation_for_matches_optimized_generation_for() {
10090        let optimized = OptimizedGraph {
10091            roots: vec![NodeId(0)],
10092            generation: 42,
10093            placements: None,
10094            eviction: None,
10095        };
10096        let order_cache: std::sync::OnceLock<Vec<NodeId>> = std::sync::OnceLock::new();
10097
10098        let optimized_gen = generation_for(&OrderSource::Optimized {
10099            optimized: &optimized,
10100            route: None,
10101        });
10102        let cached_gen = generation_for(&OrderSource::Cached {
10103            optimized: &optimized,
10104            order_cache: &order_cache,
10105        });
10106        assert_eq!(
10107            optimized_gen,
10108            Some(42),
10109            "sanity: Optimized reports the OptimizedGraph's own generation",
10110        );
10111        assert_eq!(
10112            cached_gen, optimized_gen,
10113            "Cached must report the SAME generation as Optimized for the same \
10114             OptimizedGraph -- the TopologyChanged check cannot tell the two apart, \
10115             by construction, so caching cannot silently weaken it",
10116        );
10117    }
10118
10119    /// **PR-C3 reorder-invariance gate (CPU, runnable — ORDERING level).**
10120    /// The auto-overlap reorder is a HINT: it changes only *which order*
10121    /// independent device runs dispatch in, never *which* nodes run nor the
10122    /// result. The byte-identical-OUTPUT proof is necessarily LIVE (the
10123    /// reorder fires only on a ≥2-device graph, which needs ≥2 real backends
10124    /// to realize — see `cuda_vulkan_multidevice_realize_live`'s
10125    /// `[22,86,192,340]` oracle, which now flows through this reorder, plus
10126    /// the dual-GPU `cuda_vulkan_overlap_bench_live` arbitrary-graph
10127    /// auto-overlap gate). THIS test proves the ordering-level invariant on a
10128    /// CPU-only path: the C3 reorder of a two-device graph is a valid
10129    /// topological **permutation** of the un-reordered topo order — same node
10130    /// multiset, every node still after its inputs — that genuinely DIFFERS
10131    /// from the un-reordered order (so the reorder fired). Because the
10132    /// executor caches each node's result and every op is deterministic,
10133    /// realizing any valid topological order yields identical bytes; this
10134    /// test guards the precondition (a valid permutation) that makes that so.
10135    #[test]
10136    fn c3_reorder_is_a_valid_topo_permutation() {
10137        // Two INDEPENDENT device sub-chains over distinct consts reconverging
10138        // at a final CUDA add, the Vulkan root bridged to CUDA by an explicit
10139        // Op::Copy (a residency seam = its own run). Reconverge inputs in the
10140        // "wrong" (cuda-first) order, the order the un-reordered topo DFS pops
10141        // CUDA-last — exactly the arbitrary-graph shape the auto-overlap pass
10142        // must fix. The chains are UNARY (Relu) so each stays a single
10143        // contiguous run (no const-re-read fan-in fragmenting them), exactly
10144        // like the live benchmark's `relu(mul·add)` chains; the CUDA chain is
10145        // HEAVIER (4 vs 2) so the critical-path reorder emits it first.
10146        // (Stamps only; not realized here — the ordering proof, CPU-runnable.)
10147        let n = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
10148            g.push(Node {
10149                op,
10150                inputs,
10151                shape: Shape::from_dims(&[3]),
10152                dtype: DType::F32,
10153            })
10154        };
10155        let mut g = Graph::new();
10156        let ca = n(&mut g, Op::Const, vec![]);
10157        let cb = n(&mut g, Op::Const, vec![]);
10158        // CUDA chain — HEAVIER (4 unary stages, one contiguous run).
10159        let mut cprev = ca;
10160        for _ in 0..4 {
10161            cprev = n(&mut g, Op::Relu, vec![cprev]);
10162            g.set_target_backend(cprev, BackendId::Cuda);
10163        }
10164        let c2 = cprev; // CUDA chunk root
10165        // Vulkan chain — lighter (2 unary stages).
10166        let mut vprev = cb;
10167        for _ in 0..2 {
10168            vprev = n(&mut g, Op::Relu, vec![vprev]);
10169            g.set_target_backend(vprev, BackendId::Vulkan);
10170        }
10171        let v2 = vprev; // Vulkan chunk root
10172        // Vulkan -> CUDA copy (residency seam), then reconverge on CUDA with
10173        // inputs [cuda_root, copy] (cuda-first).
10174        let copy = g.push(Node {
10175            op: Op::Copy {
10176                target: DeviceLocation::Cuda { gpu_id: 0 },
10177            },
10178            inputs: vec![v2],
10179            shape: Shape::from_dims(&[3]),
10180            dtype: DType::F32,
10181        });
10182        g.set_target_backend(copy, BackendId::Cuda);
10183        let out = n(&mut g, Op::Add, vec![c2, copy]);
10184        g.set_target_backend(out, BackendId::Cuda);
10185
10186        let unreordered = execution_plan(&g, &[out]);
10187        let reordered = fuel_graph::lower_runs_arm0(&g, &[out]);
10188
10189        // (1) The reorder FIRED — the order changed (else the test is
10190        //     vacuous + auto-overlap did nothing on an arbitrary graph).
10191        assert_ne!(
10192            reordered, unreordered,
10193            "the C3 reorder must change the order on a two-device graph; \
10194             reordered={reordered:?} unreordered={unreordered:?}",
10195        );
10196
10197        // (2) Same node multiset — a permutation, no add/drop.
10198        let mut a = unreordered.clone();
10199        let mut b = reordered.clone();
10200        a.sort();
10201        b.sort();
10202        assert_eq!(a, b, "the reorder is a permutation of the same node set");
10203
10204        // (3) The reordered order is a VALID topological order: every node
10205        //     appears after all of its inputs that are in the order.
10206        let pos: std::collections::HashMap<NodeId, usize> = reordered
10207            .iter()
10208            .enumerate()
10209            .map(|(i, &node)| (node, i))
10210            .collect();
10211        for (i, &node) in reordered.iter().enumerate() {
10212            for &inp in &g.node(node).inputs {
10213                if let Some(&j) = pos.get(&inp) {
10214                    assert!(
10215                        j < i,
10216                        "input {inp:?} of {node:?} must precede it in the reordered \
10217                         order; reordered={reordered:?}",
10218                    );
10219                }
10220            }
10221        }
10222
10223        // (4) The overlap-relevant property: BOTH device producer chunks
10224        //     (the CUDA root c2, the Vulkan root v2) are emitted BEFORE the
10225        //     host-blocking cross-device copy — the A4b overlap topology the
10226        //     un-reordered cuda-last DFS violates — AND the HEAVIER CUDA chunk
10227        //     is emitted first (critical-path: the auto-submit device runs
10228        //     earliest, the live-overlap regression guard).
10229        let p = |node: NodeId| pos[&node];
10230        assert!(p(c2) < p(copy), "CUDA chunk before the cross-device copy");
10231        assert!(p(v2) < p(copy), "Vulkan chunk before the cross-device copy");
10232        assert!(
10233            p(c2) < p(v2),
10234            "the heavier CUDA chunk is emitted before the lighter Vulkan chunk \
10235             (critical-path heavy-first); reordered={reordered:?}",
10236        );
10237    }
10238
10239    /// **C3 follow-on — the OPERAND-ORDER-INVARIANCE gate (CPU, runnable —
10240    /// the reliable operand-independence proof).** The residual the live
10241    /// `cuda_vulkan_overlap_bench_live` benchmark targets is whether the
10242    /// reconverge OPERAND order (`xc.add(&xv)` vs `xv.add(&xc)`) changes the
10243    /// wall-clock overlap. Wall-clock is thermally noisy on a heterogeneous
10244    /// dev box; the DETERMINISTIC root guarantee is this: the C3-reordered
10245    /// dispatch order the executor consumes is **byte-identical for both
10246    /// operand orders**. If the lowered order is the same, the executor
10247    /// processes the SAME WorkItem stream with the SAME cross-device
10248    /// submit/wait timing, so overlap cannot depend on the operand order.
10249    ///
10250    /// This builds the SAME two-device reconverge as
10251    /// `c3_reorder_is_a_valid_topo_permutation` but TWICE — once cuda-first
10252    /// (`add(cuda_root, copy)`), once vulkan-first (`add(copy, cuda_root)`)
10253    /// — over structurally identical graphs (same node ids, only the
10254    /// reconverge's two inputs swapped) and asserts `lower_runs_arm0` emits
10255    /// the identical op/device run sequence. The live executor trace confirms
10256    /// the same: both operand orders produce the identical WorkItem stream
10257    /// (the eager-submit/drain/wait sequence at every cross-device copy is the
10258    /// same, and the CUDA chunk is enqueued first in both).
10259    #[test]
10260    fn c3_reorder_is_operand_order_invariant() {
10261        // Build the two-device reconverge with the reconverge inputs in the
10262        // given order; return (graph, out) over a FRESH graph so node ids line
10263        // up 1:1 between the two builds (only the add's input order differs).
10264        let build = |cuda_first: bool| -> (Graph, NodeId) {
10265            let n = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
10266                g.push(Node {
10267                    op,
10268                    inputs,
10269                    shape: Shape::from_dims(&[3]),
10270                    dtype: DType::F32,
10271                })
10272            };
10273            let mut g = Graph::new();
10274            let ca = n(&mut g, Op::Const, vec![]);
10275            let cb = n(&mut g, Op::Const, vec![]);
10276            let mut cprev = ca;
10277            for _ in 0..4 {
10278                cprev = n(&mut g, Op::Relu, vec![cprev]);
10279                g.set_target_backend(cprev, BackendId::Cuda);
10280            }
10281            let c2 = cprev;
10282            let mut vprev = cb;
10283            for _ in 0..2 {
10284                vprev = n(&mut g, Op::Relu, vec![vprev]);
10285                g.set_target_backend(vprev, BackendId::Vulkan);
10286            }
10287            let v2 = vprev;
10288            let copy = g.push(Node {
10289                op: Op::Copy {
10290                    target: DeviceLocation::Cuda { gpu_id: 0 },
10291                },
10292                inputs: vec![v2],
10293                shape: Shape::from_dims(&[3]),
10294                dtype: DType::F32,
10295            });
10296            g.set_target_backend(copy, BackendId::Cuda);
10297            // The ONE knob: the reconverge's two inputs, swapped.
10298            let inputs = if cuda_first {
10299                vec![c2, copy]
10300            } else {
10301                vec![copy, c2]
10302            };
10303            let out = n(&mut g, Op::Add, inputs);
10304            g.set_target_backend(out, BackendId::Cuda);
10305            (g, out)
10306        };
10307
10308        let (g_cf, out_cf) = build(true);
10309        let (g_vf, out_vf) = build(false);
10310
10311        // Lower both via the production path (dispatch_order → lower_runs_arm0
10312        // → device_alternating_order, the C3 reorder).
10313        let order_cf = fuel_graph::lower_runs_arm0(&g_cf, &[out_cf]);
10314        let order_vf = fuel_graph::lower_runs_arm0(&g_vf, &[out_vf]);
10315
10316        // The decisive guarantee: the lowered dispatch order — as an
10317        // (op, device) sequence — is IDENTICAL for both operand orders. (Node
10318        // ids can differ if the build assigned them differently, but here the
10319        // builds are structurally identical so even the ids match; compare the
10320        // op/device sequence to be robust + descriptive on failure.)
10321        let tag = |g: &Graph, ids: &[NodeId]| -> Vec<(String, Option<BackendId>)> {
10322            ids.iter()
10323                .map(|&id| (format!("{:?}", g.node(id).op), g.target_backend(id)))
10324                .collect()
10325        };
10326        let seq_cf = tag(&g_cf, &order_cf);
10327        let seq_vf = tag(&g_vf, &order_vf);
10328        assert_eq!(
10329            seq_cf, seq_vf,
10330            "the C3-reordered dispatch order MUST be identical for both \
10331             reconverge operand orders (operand-order-invariance — the \
10332             executor then sees the same WorkItem stream regardless of \
10333             operand order, so overlap is operand-insensitive).\n\
10334             cuda-first = {seq_cf:?}\nvulkan-first = {seq_vf:?}",
10335        );
10336    }
10337
10338    /// A selector that always takes the LAST arm (arm 1) so a non-arm-0
10339    /// pick is observable (a `WinnerSelector` picks arm-0 ⇒ empty route).
10340    #[cfg(test)]
10341    #[derive(Debug)]
10342    struct PickLast;
10343    #[cfg(test)]
10344    impl RuntimeSelector for PickLast {
10345        fn select<'a>(
10346            &self,
10347            set: &'a crate::ranker::AlternativeSet,
10348        ) -> Option<&'a crate::ranker::Candidate> {
10349            set.alternatives().last()
10350        }
10351    }
10352
10353    /// Build the 2-arm diamond (mirrors `route_picker::tests::diamond`):
10354    /// arm-0 on CUDA, arm-1 on CPU; the arm exits carry their
10355    /// `target_backend` so the picker reads each arm's placement. Returns
10356    /// `(graph_arc, branch, post)`.
10357    #[cfg(test)]
10358    fn picking_diamond() -> (Arc<RwLock<Graph>>, NodeId, NodeId) {
10359        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
10360            g.push(Node {
10361                op,
10362                inputs,
10363                shape: Shape::from_dims(&[2]),
10364                dtype: DType::F32,
10365            })
10366        };
10367        let mut g = Graph::new();
10368        let pre = node(&mut g, Op::Const, vec![]);
10369        let diverge = node(&mut g, Op::Relu, vec![pre]);
10370        let arm0 = node(&mut g, Op::Silu, vec![diverge]);
10371        let arm1 = node(&mut g, Op::GeluTanh, vec![diverge]);
10372        g.set_target_backend(arm0, BackendId::Cuda);
10373        g.set_target_backend(arm1, BackendId::Cpu);
10374        let reconverge = node(&mut g, Op::Relu, vec![arm0]);
10375        let mut b = g.open_branch(diverge);
10376        b.add_arm(arm0);
10377        b.add_arm(arm1);
10378        let branch = b
10379            .finalize_branches(&mut g, reconverge)
10380            .expect("well-formed 2-arm branch")
10381            .expect("2 arms survive");
10382        let post = node(&mut g, Op::Tanh, vec![reconverge]);
10383        (Arc::new(RwLock::new(g)), branch, post)
10384    }
10385
10386    /// Step E Phase C, PR C1: the streaming picking entry's gate.
10387    /// `streaming_pick_for` (the streaming successor of the old one-shot
10388    /// `pick_route_for`) must (1) return `Some(pick)` when a selector + a
10389    /// branch are present (⇒ the `OrderSource::Streaming` walk), (2) return
10390    /// `None` with no selector (the `runtime_selector_disabled` opt-out ⇒
10391    /// arm-0), and (3) short-circuit to `None` on a branchless graph (the
10392    /// fast-path ⇒ the untouched `dispatch_order` lowering).
10393    #[test]
10394    fn streaming_pick_for_gates() {
10395        let (graph, _branch, post) = picking_diamond();
10396        let _ = post;
10397
10398        // (1) selector + branch ⇒ Some(pick).
10399        let sel: Arc<dyn RuntimeSelector> = Arc::new(PickLast);
10400        assert!(
10401            PipelinedExecutor::streaming_pick_for(&graph, Some(sel.clone()), None)
10402                .expect("ok")
10403                .is_some(),
10404            "selector + branch ⇒ a streaming pick",
10405        );
10406
10407        // (2) no selector ⇒ None (arm-0 lowering).
10408        assert!(
10409            PipelinedExecutor::streaming_pick_for(&graph, None, None)
10410                .expect("ok")
10411                .is_none(),
10412            "no selector ⇒ no streaming pick (arm-0 lowering)",
10413        );
10414
10415        // (3) branchless graph + selector ⇒ None (the fast-path).
10416        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
10417            g.push(Node {
10418                op,
10419                inputs,
10420                shape: Shape::from_dims(&[2]),
10421                dtype: DType::F32,
10422            })
10423        };
10424        let bl_graph = {
10425            let mut g = Graph::new();
10426            let c1 = node(&mut g, Op::Const, vec![]);
10427            let c2 = node(&mut g, Op::Const, vec![]);
10428            let add = node(&mut g, Op::Add, vec![c1, c2]);
10429            g.set_target_backend(add, BackendId::Cpu);
10430            Arc::new(RwLock::new(g))
10431        };
10432        assert!(
10433            PipelinedExecutor::streaming_pick_for(&bl_graph, Some(sel), None)
10434                .expect("ok")
10435                .is_none(),
10436            "branchless graph ⇒ no branches ⇒ no streaming pick (fast-path)",
10437        );
10438    }
10439
10440    /// **C1 byte-identity gate (executor layer).** The STREAMED dispatch
10441    /// order — produced by the compiler thread's lazy per-branch resolution
10442    /// (`walk_picked_route_streaming` over `resolve_branch`, the same path
10443    /// `order_for(OrderSource::Streaming)` collects) — equals the ONE-SHOT
10444    /// order (`lower_picked_route` over the route the eager `pick_route`
10445    /// resolves) on the branched diamond, for both arm-0 (WinnerSelector)
10446    /// and arm-1 (PickLast). This is the proof that C1 changes *when* a
10447    /// branch resolves, not *which* arm — the same selector, the same
10448    /// `resolve_branch`, the same emitted order.
10449    #[test]
10450    fn streamed_order_equals_one_shot() {
10451        let (graph, _branch, post) = picking_diamond();
10452        let g = graph.read().unwrap();
10453        let bindings = global_bindings();
10454
10455        for sel in [
10456            Arc::new(crate::ranker::WinnerSelector) as Arc<dyn RuntimeSelector>,
10457            Arc::new(PickLast) as Arc<dyn RuntimeSelector>,
10458        ] {
10459            // One-shot: resolve the whole route, then lower.
10460            let one_shot_route = pick_route(&g, &[post], &bindings, sel.as_ref(), None);
10461            let one_shot = fuel_graph::lower_picked_route(&g, &[post], &one_shot_route);
10462
10463            // Streamed: resolve each branch lazily at the frontier via the
10464            // SAME `resolve_branch` the compiler thread uses.
10465            let streamed = fuel_graph::lower_picked_route_streaming(&g, &[post], |branch| {
10466                resolve_branch(&g, branch, &bindings, sel.as_ref())
10467            });
10468
10469            assert_eq!(
10470                streamed, one_shot,
10471                "streamed order must equal one-shot for selector {sel:?}",
10472            );
10473        }
10474    }
10475
10476    /// ROW 157 / GAP-385: with ONE branch in the graph, the executor realizes a PICKED multi-node arm to the
10477    /// same numbers as arm 0. This is NOT shown for chained branches: with two or more in a row it failed
10478    /// (`input ... not realized`) until the lowering-order fix of 2026-11-17 (ROADMAP row 158); see
10479    /// `chained_branches_realize_equal_to_arm_zero_for_every_combination_of_arms_on_cpu`.
10480    ///
10481    /// A residual block on the host: `c1 -> relu -> silu -> tanh -> add(c1, .)`. The branch is built by
10482    /// the pathfinder's own `record_branch` (so the clone logic under test is the shipped code) with
10483    /// the alternative backend set to `Cpu`, which lets arm 1 run on this box. The route `{branch: 1}`
10484    /// makes the executor run the cloned three-node stretch; the result must equal the arm-0 result.
10485    ///
10486    /// What this does NOT show: a cross-device arm (the real alternative is another backend, with
10487    /// copies at its entry and exit), nor which arm a live selector picks. The same-backend arms mean
10488    /// the selector cannot map back to arm 1, so the route is given explicitly.
10489    #[test]
10490    fn a_single_picked_multi_node_arm_realizes_equal_to_arm_zero_on_cpu() {
10491        let (arm0, arm1) = realize_residual_block_both_arms(false);
10492        assert_eq!(
10493            arm1, arm0,
10494            "the cloned stretch computes what arm 0 computes"
10495        );
10496        assert_eq!(arm0.len(), 3);
10497        assert!(arm0.iter().all(|v| v.is_finite()));
10498    }
10499
10500    /// POSITIVE CONTROL for the test above (one branch): when the cloned stretch computes something else
10501    /// (Gelu in place of Silu, built by hand), the picked-arm result DIFFERS from arm 0. Without this the
10502    /// equality could pass by the executor ignoring the route and running arm 0 both times.
10503    #[test]
10504    fn a_picked_multi_node_arm_that_differs_changes_the_result() {
10505        let (arm0, arm1) = realize_residual_block_both_arms(true);
10506        assert_ne!(arm1, arm0, "the route must really run the cloned arm");
10507    }
10508
10509    /// Realize `c1 -> relu -> silu -> tanh -> add(c1, .)` through arm 0 and through arm 1. Arm 1 is the
10510    /// clone `record_branch` makes, or, when `control` is set, a hand-built clone whose middle node is
10511    /// Gelu instead of Silu.
10512    #[cfg(test)]
10513    fn realize_residual_block_both_arms(control: bool) -> (Vec<f32>, Vec<f32>) {
10514        use crate::optimize::OptimizedGraph;
10515        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
10516            match &arc.read().unwrap().inner {
10517                fuel_memory::BackendStorage::Cpu(c) => c.as_slice::<f32>().expect("f32").to_vec(),
10518                _ => panic!("expected CPU output"),
10519            }
10520        };
10521        let build = || {
10522            let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
10523                let id = g.push(Node {
10524                    op,
10525                    inputs,
10526                    shape: Shape::from_dims(&[3]),
10527                    dtype: DType::F32,
10528                });
10529                g.set_target_backend(id, BackendId::Cpu);
10530                id
10531            };
10532            let mut g = Graph::new();
10533            let c1 = node(&mut g, Op::Const, vec![]);
10534            let r = node(&mut g, Op::Relu, vec![c1]);
10535            let s = node(&mut g, Op::Silu, vec![r]);
10536            let t = node(&mut g, Op::Tanh, vec![s]);
10537            let res = node(&mut g, Op::Add, vec![c1, t]);
10538            let branch = if control {
10539                let r2 = node(&mut g, Op::Relu, vec![c1]);
10540                let s2 = node(&mut g, Op::GeluTanh, vec![r2]);
10541                let t2 = node(&mut g, Op::Tanh, vec![s2]);
10542                let mut b = g.open_branch(c1);
10543                b.add_arm(t);
10544                b.add_arm(t2);
10545                b.finalize_branches(&mut g, res)
10546                    .expect("well-formed")
10547                    .expect("2 arms")
10548            } else {
10549                crate::region_pathfinder::record_branch(
10550                    &mut g,
10551                    c1,
10552                    res,
10553                    &[r, s, t],
10554                    t,
10555                    BackendId::Cpu,
10556                )
10557                .expect("the region records a 2-arm branch")
10558            };
10559            let mut inputs = StorageCache::new();
10560            inputs.insert(
10561                c1,
10562                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
10563                    -1.0_f32, 0.5, 2.0,
10564                ]))),
10565            );
10566            (Arc::new(RwLock::new(g)), res, branch, inputs)
10567        };
10568
10569        drop(global_bindings());
10570        let run = |pick_arm1: bool| -> Vec<f32> {
10571            // Another test registering a backend or kernels bumps the process-wide topology generation
10572            // (`bump_topology_generation`, shared by every concurrently running test), and the executor
10573            // then returns `TopologyChanged` ("rebuild and retry") for a plan stamped before the bump.
10574            // Measured: 1 in ~55 full-suite runs at 17 threads, 6 in 110, every one the message
10575            // "generation N ... generation M"; it is not arm choice. Follow the error's own contract
10576            // with a bounded rebuild, and fail loudly on anything else or on 20 stale stamps in a row.
10577            for _attempt in 0..20 {
10578                let (graph, res, branch, inputs) = build();
10579                let opt = OptimizedGraph {
10580                    roots: vec![res],
10581                    generation: crate::dispatch::topology_generation(),
10582                    placements: None,
10583                    eviction: None,
10584                };
10585                let mut route = PickedRoute::new();
10586                if pick_arm1 {
10587                    route.insert(branch, 1);
10588                }
10589                match PipelinedExecutor::realize_with_optimized_route(
10590                    graph, res, inputs, &opt, &route,
10591                ) {
10592                    Ok((arc, _)) => return read(&arc),
10593                    Err(e) if format!("{e}").contains("topology generation") => continue,
10594                    Err(e) => panic!("realize: {e}"),
10595                }
10596            }
10597            panic!("realize: topology generation changed on 20 consecutive attempts")
10598        };
10599        (run(false), run(true))
10600    }
10601
10602    // ===== Row 158: chained region branches with a NON-ZERO arm chosen. The first real run of arm 1 on a
10603    //        GPU failed with "reshape input NodeId(2) of NodeId(3) not realized"; it reproduces on CPU
10604    //        and was a lowering-order bug (`fuel-graph/src/run.rs`): the chosen arm's run was emitted
10605    //        after the reconverge that reads it whenever two or more branches were chained. =====
10606
10607    /// `ids, table -> IndexSelect -> Reshape -> block*` where each block is the residual stretch
10608    /// `relu -> silu -> tanh -> add(x, .)` recorded as a 2-arm branch (arm 1 = the clone), so block `i`'s
10609    /// reconverge is block `i + 1`'s diverge (the shape of the toy Llama graph). Returns
10610    /// `(graph, root, branches, ids_const, table_const, head nodes)`.
10611    #[cfg(test)]
10612    fn head_then_region_chain(
10613        blocks: usize,
10614    ) -> (Graph, NodeId, Vec<NodeId>, NodeId, NodeId, Vec<NodeId>) {
10615        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>, dims: &[usize], dt: DType| {
10616            let id = g.push(Node {
10617                op,
10618                inputs,
10619                shape: Shape::from_dims(dims),
10620                dtype: dt,
10621            });
10622            g.set_target_backend(id, BackendId::Cpu);
10623            id
10624        };
10625        let mut g = Graph::new();
10626        let ids = node(&mut g, Op::Const, vec![], &[3], DType::U32);
10627        let table = node(&mut g, Op::Const, vec![], &[8, 4], DType::F32);
10628        let gathered = node(
10629            &mut g,
10630            Op::IndexSelect { dim: 0 },
10631            vec![table, ids],
10632            &[3, 4],
10633            DType::F32,
10634        );
10635        let mut x = node(
10636            &mut g,
10637            Op::Reshape(Shape::from_dims(&[1, 3, 4])),
10638            vec![gathered],
10639            &[1, 3, 4],
10640            DType::F32,
10641        );
10642        let head = vec![gathered, x];
10643        let mut branches = Vec::new();
10644        for _ in 0..blocks {
10645            let r = node(&mut g, Op::Relu, vec![x], &[1, 3, 4], DType::F32);
10646            let s = node(&mut g, Op::Silu, vec![r], &[1, 3, 4], DType::F32);
10647            let t = node(&mut g, Op::Tanh, vec![s], &[1, 3, 4], DType::F32);
10648            let res = node(&mut g, Op::Add, vec![x, t], &[1, 3, 4], DType::F32);
10649            let branch = crate::region_pathfinder::record_branch(
10650                &mut g,
10651                x,
10652                res,
10653                &[r, s, t],
10654                t,
10655                BackendId::Cpu,
10656            )
10657            .expect("the block records a 2-arm branch");
10658            branches.push(branch);
10659            x = res;
10660        }
10661        (g, x, branches, ids, table, head)
10662    }
10663
10664    /// The route that sends branch `i` to arm 1 iff bit `i` of `mask` is set.
10665    #[cfg(test)]
10666    fn route_from_mask(branches: &[NodeId], mask: usize) -> PickedRoute {
10667        let mut route = PickedRoute::new();
10668        for (i, &b) in branches.iter().enumerate() {
10669            if mask >> i & 1 == 1 {
10670                route.insert(b, 1);
10671            }
10672        }
10673        route
10674    }
10675
10676    /// Why `order` is not a valid dispatch order for the route `mask`, or `None` when it is. Valid: every
10677    /// emitted node's inputs are emitted earlier, are leaves, or are an arm-0 exit whose branch chose
10678    /// arm 1 and whose arm-1 exit was emitted earlier (the alias the compiler thread inserts); the chosen
10679    /// arm's exit is emitted and the other arm's is not.
10680    #[cfg(test)]
10681    fn why_invalid_order(
10682        g: &Graph,
10683        branches: &[NodeId],
10684        mask: usize,
10685        order: &[NodeId],
10686    ) -> Option<String> {
10687        let mut alias: HashMap<NodeId, NodeId> = HashMap::new();
10688        for (i, &b) in branches.iter().enumerate() {
10689            if mask >> i & 1 == 1 {
10690                alias.insert(g.node(b).inputs[0], g.node(b).inputs[1]);
10691            }
10692        }
10693        let mut emitted: HashSet<NodeId> = HashSet::new();
10694        for &n in order {
10695            for &inp in &g.node(n).inputs {
10696                let ok = emitted.contains(&inp)
10697                    || matches!(g.node(inp).op, Op::Const)
10698                    || alias.get(&inp).is_some_and(|a| emitted.contains(a));
10699                if !ok {
10700                    return Some(format!(
10701                        "node {n:?} ({:?}) is emitted before its input {inp:?} ({:?})",
10702                        g.node(n).op,
10703                        g.node(inp).op
10704                    ));
10705                }
10706            }
10707            emitted.insert(n);
10708        }
10709        for (i, &b) in branches.iter().enumerate() {
10710            let arms = &g.node(b).inputs;
10711            let (chosen, other) = if mask >> i & 1 == 1 {
10712                (arms[1], arms[0])
10713            } else {
10714                (arms[0], arms[1])
10715            };
10716            if !emitted.contains(&chosen) {
10717                return Some(format!(
10718                    "branch {i}: the chosen arm exit {chosen:?} is not emitted"
10719                ));
10720            }
10721            if emitted.contains(&other) {
10722                return Some(format!(
10723                    "branch {i}: the other arm exit {other:?} is emitted"
10724                ));
10725            }
10726        }
10727        None
10728    }
10729
10730    /// LOWERING level (no executor): for 1 to 4 chained branches and EVERY combination of arms (not only
10731    /// all arm 1), the frozen and the streaming lowering each emit a valid order, and the two orders are
10732    /// identical for the same picks. Before the fix N=1 passed and every N >= 2 with an arm 1 failed.
10733    #[test]
10734    fn chained_branches_lower_to_a_valid_order_for_every_combination_of_arms() {
10735        for blocks in 1..=4usize {
10736            let (g, root, branches, _ids, _table, head) = head_then_region_chain(blocks);
10737            for mask in 0..(1usize << blocks) {
10738                let route = route_from_mask(&branches, mask);
10739                let frozen = fuel_graph::lower_picked_route(&g, &[root], &route);
10740                let streaming = fuel_graph::lower_picked_route_streaming(&g, &[root], |b| {
10741                    route.get(&b).copied().unwrap_or(0)
10742                });
10743                for (name, order) in [("frozen", &frozen), ("streaming", &streaming)] {
10744                    assert_eq!(
10745                        why_invalid_order(&g, &branches, mask, order),
10746                        None,
10747                        "{name} lowering, blocks={blocks} mask={mask:#b}: order={order:?}"
10748                    );
10749                    assert!(
10750                        head.iter().all(|h| order.contains(h)),
10751                        "{name}, blocks={blocks} mask={mask:#b}: the head must be emitted"
10752                    );
10753                }
10754                assert_eq!(
10755                    frozen, streaming,
10756                    "blocks={blocks} mask={mask:#b}: frozen and streaming differ"
10757                );
10758            }
10759        }
10760    }
10761
10762    /// ROW 158: a chain of CROSS-DEVICE region branches. Block `i` is `e = relu(x); d = silu(e);
10763    /// a = add(d, e); t = tanh(a); res = add(d, t)`, the stretch `a, t` is recorded with its alternative on
10764    /// `Cuda { gpu_id: 0 }` (arm 1) and its exit brought back to the host, and the residency pass inserts
10765    /// the inbound copies of BOTH external inputs (`d` and `e`) of the clone. `res` is the next block's `x`.
10766    /// Returns `(graph, root, branches)`.
10767    #[cfg(test)]
10768    fn cross_device_chain(blocks: usize) -> (Graph, NodeId, Vec<NodeId>) {
10769        use crate::region_pathfinder::try_record_branch;
10770        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
10771        let mut g = Graph::new();
10772        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
10773            let id = g.push(Node {
10774                op,
10775                inputs,
10776                shape: Shape::from_dims(&[4]),
10777                dtype: DType::F32,
10778            });
10779            g.set_placement(id, DeviceLocation::Cpu);
10780            g.set_target_backend(id, BackendId::Cpu);
10781            id
10782        };
10783        let mut x = node(&mut g, Op::Const, vec![]);
10784        let mut branches = Vec::new();
10785        for _ in 0..blocks {
10786            let e = node(&mut g, Op::Relu, vec![x]);
10787            let d = node(&mut g, Op::Silu, vec![e]);
10788            let a = node(&mut g, Op::Add, vec![d, e]);
10789            let t = node(&mut g, Op::Tanh, vec![a]);
10790            let res = node(&mut g, Op::Add, vec![d, t]);
10791            let branch = try_record_branch(
10792                &mut g,
10793                d,
10794                res,
10795                &[a, t],
10796                t,
10797                BackendId::Cuda,
10798                cuda0,
10799                DeviceLocation::Cpu,
10800            )
10801            .expect("well-formed branch")
10802            .expect("two arms");
10803            branches.push(branch);
10804            x = res;
10805        }
10806        crate::optimize::insert_residency_copies(
10807            &mut g,
10808            &[x],
10809            &crate::plan::ExecutionPlan::empty(),
10810            DeviceLocation::Cpu,
10811            None,
10812        );
10813        (g, x, branches)
10814    }
10815
10816    /// LOWERING level: the cross-device chain (inbound copies, exit copies, two external inputs per arm)
10817    /// lowers to a valid order for 1 to 4 blocks and EVERY combination of arms, frozen and streaming
10818    /// identical. Found on a GPU run: with the chosen arm's runs moved to the slot of the first run that
10819    /// opens an arm, an inbound `Copy` ran before the main-chain node it reads (`Copy input NodeId(130) of
10820    /// NodeId(255) not realized`).
10821    #[test]
10822    fn cross_device_chains_lower_to_a_valid_order_for_every_combination_of_arms() {
10823        for blocks in 1..=4usize {
10824            let (g, root, branches) = cross_device_chain(blocks);
10825            for mask in 0..(1usize << blocks) {
10826                let route = route_from_mask(&branches, mask);
10827                let frozen = fuel_graph::lower_picked_route(&g, &[root], &route);
10828                let streaming = fuel_graph::lower_picked_route_streaming(&g, &[root], |b| {
10829                    route.get(&b).copied().unwrap_or(0)
10830                });
10831                for (name, order) in [("frozen", &frozen), ("streaming", &streaming)] {
10832                    assert_eq!(
10833                        why_invalid_order(&g, &branches, mask, order),
10834                        None,
10835                        "{name} lowering, blocks={blocks} mask={mask:#b}: order={order:?}"
10836                    );
10837                }
10838                assert_eq!(
10839                    frozen, streaming,
10840                    "blocks={blocks} mask={mask:#b}: frozen and streaming differ"
10841                );
10842            }
10843        }
10844    }
10845
10846    /// A chain of cross-device region branches whose stretch reads a SHARED EARLY value `h` (computed once,
10847    /// before any diverge) as well as its diverge `d`: `fillers` nodes sit between the previous block and
10848    /// `d`, and `h` enters the stretch at its first node (`second_in_middle == false`) or its second.
10849    /// The residency pass inserts ONE inbound copy of `h` onto the alternative device and CSEs it between
10850    /// every block's arm 1, so that copy is in branch 1's arm 1 and in branch 2's arm 1 at once.
10851    #[cfg(test)]
10852    fn shared_early_input_chain(
10853        blocks: usize,
10854        fillers: usize,
10855        second_in_middle: bool,
10856    ) -> (Graph, NodeId, Vec<NodeId>) {
10857        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
10858        let mut g = Graph::new();
10859        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
10860            let id = g.push(Node {
10861                op,
10862                inputs,
10863                shape: Shape::from_dims(&[4]),
10864                dtype: DType::F32,
10865            });
10866            g.set_placement(id, DeviceLocation::Cpu);
10867            g.set_target_backend(id, BackendId::Cpu);
10868            id
10869        };
10870        let c1 = node(&mut g, Op::Const, vec![]);
10871        // The early value: NOT downstream of any diverge, so it is outside every stretch.
10872        let h = node(&mut g, Op::Relu, vec![c1]);
10873        let mut x = node(&mut g, Op::Const, vec![]);
10874        let mut branches = Vec::new();
10875        for _ in 0..blocks {
10876            let mut d = x;
10877            for _ in 0..fillers {
10878                d = node(&mut g, Op::Silu, vec![d]);
10879            }
10880            let (a, t) = if second_in_middle {
10881                let s1 = node(&mut g, Op::Tanh, vec![d]);
10882                let s2 = node(&mut g, Op::Add, vec![s1, h]);
10883                (s1, s2)
10884            } else {
10885                let s1 = node(&mut g, Op::Add, vec![d, h]);
10886                let s2 = node(&mut g, Op::Tanh, vec![s1]);
10887                (s1, s2)
10888            };
10889            let res = node(&mut g, Op::Add, vec![d, t]);
10890            let branch = crate::region_pathfinder::try_record_branch(
10891                &mut g,
10892                d,
10893                res,
10894                &[a, t],
10895                t,
10896                BackendId::Cuda,
10897                cuda0,
10898                DeviceLocation::Cpu,
10899            )
10900            .expect("well-formed branch")
10901            .expect("two arms");
10902            branches.push(branch);
10903            x = res;
10904        }
10905
10906        crate::optimize::insert_residency_copies(
10907            &mut g,
10908            &[x],
10909            &crate::plan::ExecutionPlan::empty(),
10910            DeviceLocation::Cpu,
10911            None,
10912        );
10913        (g, x, branches)
10914    }
10915
10916    /// LOWERING level, 140 shapes (1 to 3 blocks x 0 to 4 fillers x both entry positions x EVERY
10917    /// combination of arms; the frozen and the streaming order may differ here, as they may on any multi-device
10918    /// graph, but BOTH must be valid): a shared inbound copy must run when ANY branch's chosen arm reads it, and the
10919    /// chosen arm's runs must come before the reconverge. Under the first-slot relocation with per-branch
10920    /// skip sets, 80 of the 140 (a node emitted before its input) were invalid; this is the CPU form of the
10921    /// GPU failures `Copy input NodeId(130) of NodeId(255) not realized` and `cpu kernel wrapper called
10922    /// with non-CPU input` (ROADMAP row 158).
10923    #[test]
10924    fn cross_device_chains_with_a_shared_early_input_lower_to_a_valid_order_for_every_combination_of_arms()
10925     {
10926        let mut shapes = 0;
10927        for blocks in 1..=3usize {
10928            for fillers in 0..=4usize {
10929                for second_in_middle in [false, true] {
10930                    let (g, root, branches) =
10931                        shared_early_input_chain(blocks, fillers, second_in_middle);
10932                    for mask in 0..(1usize << blocks) {
10933                        shapes += 1;
10934                        let route = route_from_mask(&branches, mask);
10935                        let frozen = fuel_graph::lower_picked_route(&g, &[root], &route);
10936                        let streaming =
10937                            fuel_graph::lower_picked_route_streaming(&g, &[root], |b| {
10938                                route.get(&b).copied().unwrap_or(0)
10939                            });
10940                        for (name, order) in [("frozen", &frozen), ("streaming", &streaming)] {
10941                            assert_eq!(
10942                                why_invalid_order(&g, &branches, mask, order),
10943                                None,
10944                                "{name} lowering, blocks={blocks} fillers={fillers} second_in_middle={second_in_middle} mask={mask:#b}: order={order:?}"
10945                            );
10946                        }
10947                    }
10948                }
10949            }
10950        }
10951        assert_eq!(shapes, 140, "the family size changed: re-pin it");
10952    }
10953
10954    /// A chain of cross-device region branches whose stretch reads EXTERNAL values besides its diverge.
10955    /// `ext[i]` is what block `i`'s stretch reads: 0 = the shared early value `h`, 1 = the value two blocks
10956    /// back (a skip connection), 2 = both. `entry` is the stretch node that reads them (0 = the first, 1 =
10957    /// the second); `fillers` nodes sit between the previous block and the diverge. The residency pass
10958    /// inserts one inbound copy per (value, device) and CSEs it between regions, so a copy can sit in
10959    /// several branches' arm 1 at once and its natural position in the base order is set by whichever
10960    /// branch reaches it first. Lowering only: the ops are structural (an `Add` may have three inputs).
10961    #[cfg(test)]
10962    fn pattern_chain(ext: &[u8], entry: usize, fillers: usize) -> (Graph, NodeId, Vec<NodeId>) {
10963        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
10964        let mut g = Graph::new();
10965        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
10966            let id = g.push(Node {
10967                op,
10968                inputs,
10969                shape: Shape::from_dims(&[4]),
10970                dtype: DType::F32,
10971            });
10972            g.set_placement(id, DeviceLocation::Cpu);
10973            g.set_target_backend(id, BackendId::Cpu);
10974            id
10975        };
10976        let c1 = node(&mut g, Op::Const, vec![]);
10977        let h = node(&mut g, Op::Relu, vec![c1]);
10978        let mut two_back = node(&mut g, Op::Const, vec![]);
10979        let mut x = node(&mut g, Op::Const, vec![]);
10980        let mut one_back = x;
10981        let mut branches = Vec::new();
10982        for &kind in ext {
10983            let mut d = x;
10984            for _ in 0..fillers {
10985                d = node(&mut g, Op::Silu, vec![d]);
10986            }
10987            let externals: Vec<NodeId> = match kind {
10988                0 => vec![h],
10989                1 => vec![two_back],
10990                _ => vec![h, two_back],
10991            };
10992            let (first, last) = if entry == 0 {
10993                let mut inputs = vec![d];
10994                inputs.extend(externals);
10995                let a = node(&mut g, Op::Add, inputs);
10996                let t = node(&mut g, Op::Tanh, vec![a]);
10997                (a, t)
10998            } else {
10999                let a = node(&mut g, Op::Tanh, vec![d]);
11000                let mut inputs = vec![a];
11001                inputs.extend(externals);
11002                let t = node(&mut g, Op::Add, inputs);
11003                (a, t)
11004            };
11005            let res = node(&mut g, Op::Add, vec![d, last]);
11006            let branch = crate::region_pathfinder::try_record_branch(
11007                &mut g,
11008                d,
11009                res,
11010                &[first, last],
11011                last,
11012                BackendId::Cuda,
11013                cuda0,
11014                DeviceLocation::Cpu,
11015            )
11016            .expect("well-formed branch")
11017            .expect("two arms");
11018            branches.push(branch);
11019            two_back = one_back;
11020            one_back = x;
11021            x = res;
11022        }
11023        crate::optimize::insert_residency_copies(
11024            &mut g,
11025            &[x],
11026            &crate::plan::ExecutionPlan::empty(),
11027            DeviceLocation::Cpu,
11028            None,
11029        );
11030        (g, x, branches)
11031    }
11032
11033    /// LOWERING level, 1548 (shape, arm combination) cases: 1 to 3 chained cross-device branches, every
11034    /// per-block external-input pattern (`h`, a skip connection, both), both entry positions, 0 to 2
11035    /// fillers, EVERY combination of arms; frozen and streaming lowering each valid. With the chosen arm's
11036    /// late runs moved to the FIRST arm slot, 644 checks failed with `Copy (onto Cuda) is emitted before
11037    /// its input`, the CPU form of the GPU failure `Copy input NodeId(130) of NodeId(255) not realized`:
11038    /// the first run opening an arm of the branch was an arm-1 inbound copy shared with another region and
11039    /// positioned early, and the other arm-1 runs were moved there, before the node they read.
11040    #[test]
11041    fn cross_device_chains_with_shared_and_skip_inputs_lower_to_a_valid_order_for_every_combination_of_arms()
11042     {
11043        let mut cases = 0;
11044        for blocks in 1..=3usize {
11045            for code in 0..3usize.pow(blocks as u32) {
11046                let ext: Vec<u8> = (0..blocks)
11047                    .map(|i| ((code / 3usize.pow(i as u32)) % 3) as u8)
11048                    .collect();
11049                for entry in 0..2usize {
11050                    for fillers in 0..=2usize {
11051                        let (g, root, branches) = pattern_chain(&ext, entry, fillers);
11052                        for mask in 0..(1usize << blocks) {
11053                            cases += 1;
11054                            let route = route_from_mask(&branches, mask);
11055                            let frozen = fuel_graph::lower_picked_route(&g, &[root], &route);
11056                            let streaming =
11057                                fuel_graph::lower_picked_route_streaming(&g, &[root], |b| {
11058                                    route.get(&b).copied().unwrap_or(0)
11059                                });
11060                            for (name, order) in [("frozen", &frozen), ("streaming", &streaming)] {
11061                                assert_eq!(
11062                                    why_invalid_order(&g, &branches, mask, order),
11063                                    None,
11064                                    "{name} lowering, ext={ext:?} entry={entry} fillers={fillers} mask={mask:#b}: order={order:?}"
11065                                );
11066                            }
11067                        }
11068                    }
11069                }
11070            }
11071        }
11072        assert_eq!(cases, 1548, "the family size changed: re-pin it");
11073    }
11074
11075    /// EXECUTOR level on CPU: the chain realized for every combination of arms (2 and 3 blocks, every
11076    /// mask, arm 1 = the clone on the same backend) equals arm 0. Before the fix any chain of two or more
11077    /// with an arm 1 failed with "input ... not realized".
11078    #[test]
11079    fn chained_branches_realize_equal_to_arm_zero_for_every_combination_of_arms_on_cpu() {
11080        use crate::optimize::OptimizedGraph;
11081        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
11082            match &arc.read().unwrap().inner {
11083                fuel_memory::BackendStorage::Cpu(c) => c.as_slice::<f32>().expect("f32").to_vec(),
11084                _ => panic!("expected CPU output"),
11085            }
11086        };
11087        drop(global_bindings());
11088        // Hold the generation still between building the stamp and realizing (ROADMAP row 165).
11089        let _gate = crate::dispatch::TOPOLOGY_TEST_GATE
11090            .write()
11091            .unwrap_or_else(|p| p.into_inner());
11092        let run = |blocks: usize, mask: usize| -> Vec<f32> {
11093            let (g, root, branches, ids, table, _head) = head_then_region_chain(blocks);
11094            let mut inputs = StorageCache::new();
11095            inputs.insert(
11096                ids,
11097                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[1_u32, 4, 6]))),
11098            );
11099            let table_vals: Vec<f32> = (0..32).map(|i| (i as f32 - 16.0) / 8.0).collect();
11100            inputs.insert(
11101                table,
11102                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&table_vals))),
11103            );
11104            let opt = OptimizedGraph {
11105                roots: vec![root],
11106                generation: crate::dispatch::topology_generation(),
11107                placements: None,
11108                eviction: None,
11109            };
11110            let route = route_from_mask(&branches, mask);
11111            let (arc, _) = PipelinedExecutor::realize_with_optimized_route(
11112                Arc::new(RwLock::new(g)),
11113                root,
11114                inputs,
11115                &opt,
11116                &route,
11117            )
11118            .unwrap_or_else(|e| panic!("realize (blocks={blocks}, mask={mask:#b}): {e}"));
11119            read(&arc)
11120        };
11121        for blocks in 1..=3usize {
11122            let arm0 = run(blocks, 0);
11123            assert_eq!(arm0.len(), 12);
11124            assert!(arm0.iter().all(|v| v.is_finite()));
11125            for mask in 1..(1usize << blocks) {
11126                assert_eq!(
11127                    run(blocks, mask),
11128                    arm0,
11129                    "blocks={blocks} mask={mask:#b}: a cloned stretch computes what arm 0 computes"
11130                );
11131            }
11132        }
11133    }
11134
11135    /// Realizing a node whose target_backend isn't set surfaces a
11136    /// typed error (no panic).
11137    #[test]
11138    fn pipelined_errors_on_unset_target_backend() {
11139        let graph = Arc::new(RwLock::new(Graph::new()));
11140        let (lhs_id, rhs_id, add_id) = {
11141            let mut g = graph.write().unwrap();
11142            let lhs = g.push(Node {
11143                op: Op::Const,
11144                inputs: vec![],
11145                shape: Shape::from_dims(&[2]),
11146                dtype: DType::F32,
11147            });
11148            let rhs = g.push(Node {
11149                op: Op::Const,
11150                inputs: vec![],
11151                shape: Shape::from_dims(&[2]),
11152                dtype: DType::F32,
11153            });
11154            // Deliberately do NOT call set_target_backend on the Add.
11155            let add = g.push(Node {
11156                op: Op::Add,
11157                inputs: vec![lhs, rhs],
11158                shape: Shape::from_dims(&[2]),
11159                dtype: DType::F32,
11160            });
11161            (lhs, rhs, add)
11162        };
11163
11164        let mut inputs = StorageCache::new();
11165        inputs.insert(
11166            lhs_id,
11167            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]))),
11168        );
11169        inputs.insert(
11170            rhs_id,
11171            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[3.0_f32, 4.0]))),
11172        );
11173
11174        let result = PipelinedExecutor::realize(graph, add_id, inputs);
11175        assert!(result.is_err(), "missing target_backend must error");
11176        let msg = result.unwrap_err().to_string();
11177        assert!(
11178            msg.contains("target_backend"),
11179            "error names the unmet precondition: {msg}"
11180        );
11181    }
11182
11183    /// Realizing a Const-only graph adopts the pre-seeded input
11184    /// without calling any kernel.
11185    #[test]
11186    fn pipelined_realize_const_only() {
11187        let storage = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0, 7.0]);
11188
11189        let graph = Arc::new(RwLock::new(Graph::new()));
11190        let const_id = {
11191            let mut g = graph.write().unwrap();
11192            g.push(Node {
11193                op: Op::Const,
11194                inputs: vec![],
11195                shape: Shape::from_dims(&[3]),
11196                dtype: DType::F32,
11197            })
11198        };
11199
11200        let mut inputs = StorageCache::new();
11201        inputs.insert(const_id, Arc::new(RwLock::new(storage)));
11202
11203        let (result_arc, _) =
11204            PipelinedExecutor::realize(graph, const_id, inputs).expect("realize const");
11205        let guard = result_arc.read().unwrap();
11206        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
11207            let typed: &[f32] = c.as_slice().unwrap();
11208            assert_eq!(typed, &[5.0, 6.0, 7.0]);
11209        }
11210    }
11211
11212    /// Missing input-cache entry for a Const surfaces a typed error.
11213    #[test]
11214    fn pipelined_errors_on_missing_const_input() {
11215        let graph = Arc::new(RwLock::new(Graph::new()));
11216        let const_id = {
11217            let mut g = graph.write().unwrap();
11218            g.push(Node {
11219                op: Op::Const,
11220                inputs: vec![],
11221                shape: Shape::from_dims(&[2]),
11222                dtype: DType::F32,
11223            })
11224        };
11225        // Deliberately empty input cache.
11226        let inputs = StorageCache::new();
11227        let result = PipelinedExecutor::realize(graph, const_id, inputs);
11228        assert!(result.is_err());
11229    }
11230
11231    /// E2E: 2-node graph (Const + Relu) — exercises the unary
11232    /// dispatch wrapper + kernel through the pipelined executor.
11233    #[test]
11234    fn pipelined_realize_const_relu() {
11235        let storage = fuel_memory::from_slice_cpu(&[-1.0_f32, 0.0, 0.5, -3.5, 7.25]);
11236        let graph = Arc::new(RwLock::new(Graph::new()));
11237        let (in_id, relu_id) = {
11238            let mut g = graph.write().unwrap();
11239            let in_id = g.push(Node {
11240                op: Op::Const,
11241                inputs: vec![],
11242                shape: Shape::from_dims(&[5]),
11243                dtype: DType::F32,
11244            });
11245            let relu_id = g.push(Node {
11246                op: Op::Relu,
11247                inputs: vec![in_id],
11248                shape: Shape::from_dims(&[5]),
11249                dtype: DType::F32,
11250            });
11251            g.set_target_backend(relu_id, BackendId::Cpu);
11252            (in_id, relu_id)
11253        };
11254        let mut inputs = StorageCache::new();
11255        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11256
11257        let (result_arc, _) = PipelinedExecutor::realize(graph, relu_id, inputs).expect("realize");
11258        let guard = result_arc.read().unwrap();
11259        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
11260            let typed: &[f32] = c.as_slice().expect("f32 cast");
11261            assert_eq!(typed, &[0.0, 0.0, 0.5, 0.0, 7.25]);
11262        }
11263    }
11264
11265    /// E2E: Const + Const + Sub + Mul + Div — exercises three more
11266    /// of the freshly-migrated binary kernels in one graph. Verifies
11267    /// that intermediates flow through the cache as expected.
11268    #[test]
11269    fn pipelined_realize_chained_binary_ops() {
11270        let a_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
11271        let b_storage = fuel_memory::from_slice_cpu(&[3.0_f32, 5.0]);
11272        let c_storage = fuel_memory::from_slice_cpu(&[2.0_f32, 4.0]);
11273
11274        let graph = Arc::new(RwLock::new(Graph::new()));
11275        let (a_id, b_id, c_id, sub_id, mul_id, div_id) = {
11276            let mut g = graph.write().unwrap();
11277            let a = g.push(Node {
11278                op: Op::Const,
11279                inputs: vec![],
11280                shape: Shape::from_dims(&[2]),
11281                dtype: DType::F32,
11282            });
11283            let b = g.push(Node {
11284                op: Op::Const,
11285                inputs: vec![],
11286                shape: Shape::from_dims(&[2]),
11287                dtype: DType::F32,
11288            });
11289            let c = g.push(Node {
11290                op: Op::Const,
11291                inputs: vec![],
11292                shape: Shape::from_dims(&[2]),
11293                dtype: DType::F32,
11294            });
11295            // (a - b)         = [7, 15]
11296            let sub = g.push(Node {
11297                op: Op::Sub,
11298                inputs: vec![a, b],
11299                shape: Shape::from_dims(&[2]),
11300                dtype: DType::F32,
11301            });
11302            // (a - b) * c     = [14, 60]
11303            let mul = g.push(Node {
11304                op: Op::Mul,
11305                inputs: vec![sub, c],
11306                shape: Shape::from_dims(&[2]),
11307                dtype: DType::F32,
11308            });
11309            // ((a-b)*c) / b   = [14/3, 12]
11310            let div = g.push(Node {
11311                op: Op::Div,
11312                inputs: vec![mul, b],
11313                shape: Shape::from_dims(&[2]),
11314                dtype: DType::F32,
11315            });
11316            g.set_target_backend(sub, BackendId::Cpu);
11317            g.set_target_backend(mul, BackendId::Cpu);
11318            g.set_target_backend(div, BackendId::Cpu);
11319            (a, b, c, sub, mul, div)
11320        };
11321
11322        let _ = (sub_id, mul_id);
11323        let mut inputs = StorageCache::new();
11324        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
11325        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
11326        inputs.insert(c_id, Arc::new(RwLock::new(c_storage)));
11327
11328        let (result_arc, _) = PipelinedExecutor::realize(graph, div_id, inputs).expect("realize");
11329        let guard = result_arc.read().unwrap();
11330        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
11331            let typed: &[f32] = c.as_slice().unwrap();
11332            assert!((typed[0] - (14.0_f32 / 3.0)).abs() < 1e-6);
11333            assert!((typed[1] - 12.0).abs() < 1e-6);
11334        }
11335    }
11336
11337    /// E2E: Const + Transpose — verifies metadata-only view ops
11338    /// share the input's Storage Arc and produce a strided Layout.
11339    /// Stage 3 of Layout-on-Node.
11340    #[test]
11341    fn pipelined_realize_transpose_is_metadata_only() {
11342        // shape [2, 3]; transpose → shape [3, 2], strided
11343        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
11344        let graph = Arc::new(RwLock::new(Graph::new()));
11345        let (in_id, t_id) = {
11346            let mut g = graph.write().unwrap();
11347            let in_id = g.push(Node {
11348                op: Op::Const,
11349                inputs: vec![],
11350                shape: Shape::from_dims(&[2, 3]),
11351                dtype: DType::F32,
11352            });
11353            let t_id = g.push(Node {
11354                op: Op::Transpose,
11355                inputs: vec![in_id],
11356                shape: Shape::from_dims(&[3, 2]),
11357                dtype: DType::F32,
11358            });
11359            // Note: NO set_target_backend — transpose is metadata-only
11360            // and doesn't run on a backend.
11361            (in_id, t_id)
11362        };
11363        let mut inputs = StorageCache::new();
11364        let in_arc = Arc::new(RwLock::new(storage));
11365        inputs.insert(in_id, Arc::clone(&in_arc));
11366
11367        let (result_arc, result_layout) =
11368            PipelinedExecutor::realize(graph, t_id, inputs).expect("realize");
11369
11370        // The output Storage Arc is the SAME Arc as the input —
11371        // metadata-only adoption shares bytes.
11372        assert!(
11373            Arc::ptr_eq(&result_arc, &in_arc),
11374            "transpose must share input bytes"
11375        );
11376
11377        // The output Layout is the transposed view.
11378        assert_eq!(result_layout.shape().dims(), &[3, 2]);
11379        assert_eq!(result_layout.stride(), &[1, 3]);
11380        assert!(!result_layout.is_contiguous());
11381    }
11382
11383    /// E2E: Const + Flip(dim=0) — verifies Op::Flip is metadata-only.
11384    /// The output Storage Arc must be the SAME Arc (no copy);
11385    /// the output Layout has a negated stride at dim 0 and a
11386    /// shifted start_offset.
11387    #[test]
11388    fn pipelined_realize_flip_is_metadata_only() {
11389        // shape [3, 4]; flip dim 0 → shape [3, 4], stride [-4, 1], offset 8.
11390        let data: Vec<f32> = (1..=12).map(|x| x as f32).collect();
11391        let storage = fuel_memory::from_slice_cpu(&data);
11392        let graph = Arc::new(RwLock::new(Graph::new()));
11393        let (in_id, f_id) = {
11394            let mut g = graph.write().unwrap();
11395            let in_id = g.push(Node {
11396                op: Op::Const,
11397                inputs: vec![],
11398                shape: Shape::from_dims(&[3, 4]),
11399                dtype: DType::F32,
11400            });
11401            let f_id = g.push(Node {
11402                op: Op::Flip { dim: 0 },
11403                inputs: vec![in_id],
11404                shape: Shape::from_dims(&[3, 4]),
11405                dtype: DType::F32,
11406            });
11407            (in_id, f_id)
11408        };
11409        let mut inputs = StorageCache::new();
11410        let in_arc = Arc::new(RwLock::new(storage));
11411        inputs.insert(in_id, Arc::clone(&in_arc));
11412
11413        let (result_arc, result_layout) =
11414            PipelinedExecutor::realize(graph, f_id, inputs).expect("realize");
11415
11416        assert!(
11417            Arc::ptr_eq(&result_arc, &in_arc),
11418            "flip must share input bytes"
11419        );
11420        assert_eq!(result_layout.shape().dims(), &[3, 4]);
11421        assert_eq!(result_layout.stride(), &[-4_isize, 1]);
11422        assert_eq!(result_layout.start_offset(), 8);
11423        assert!(!result_layout.is_contiguous());
11424    }
11425
11426    /// E2E: Const + Permute(rank-3 axes [2, 0, 1]) — verifies the
11427    /// general permute path through metadata-only adoption.
11428    #[test]
11429    fn pipelined_realize_permute_is_metadata_only() {
11430        // shape [2, 3, 4]; permute axes [2, 0, 1] → shape [4, 2, 3]
11431        let data: Vec<f32> = (1..=24).map(|x| x as f32).collect();
11432        let storage = fuel_memory::from_slice_cpu(&data);
11433        let graph = Arc::new(RwLock::new(Graph::new()));
11434        let (in_id, p_id) = {
11435            let mut g = graph.write().unwrap();
11436            let in_id = g.push(Node {
11437                op: Op::Const,
11438                inputs: vec![],
11439                shape: Shape::from_dims(&[2, 3, 4]),
11440                dtype: DType::F32,
11441            });
11442            let p_id = g.push(Node {
11443                op: Op::Permute(vec![2, 0, 1]),
11444                inputs: vec![in_id],
11445                shape: Shape::from_dims(&[4, 2, 3]),
11446                dtype: DType::F32,
11447            });
11448            (in_id, p_id)
11449        };
11450        let mut inputs = StorageCache::new();
11451        let in_arc = Arc::new(RwLock::new(storage));
11452        inputs.insert(in_id, Arc::clone(&in_arc));
11453
11454        let (result_arc, result_layout) =
11455            PipelinedExecutor::realize(graph, p_id, inputs).expect("realize");
11456
11457        assert!(Arc::ptr_eq(&result_arc, &in_arc));
11458        assert_eq!(result_layout.shape().dims(), &[4, 2, 3]);
11459        // Original strides for shape [2, 3, 4] are [12, 4, 1].
11460        // After permute axes [2, 0, 1]: [strides[2], strides[0], strides[1]] = [1, 12, 4].
11461        assert_eq!(result_layout.stride(), &[1, 12, 4]);
11462    }
11463
11464    /// E2E: Const + Cast(f32→f64) — verifies cast through the
11465    /// pipelined executor. Output Storage has the target dtype;
11466    /// bytes encode the widened values.
11467    #[test]
11468    fn pipelined_realize_cast_f32_to_f64() {
11469        let storage = fuel_memory::from_slice_cpu(&[1.5_f32, -2.25, 100.0]);
11470        let graph = Arc::new(RwLock::new(Graph::new()));
11471        let (in_id, c_id) = {
11472            let mut g = graph.write().unwrap();
11473            let in_id = g.push(Node {
11474                op: Op::Const,
11475                inputs: vec![],
11476                shape: Shape::from_dims(&[3]),
11477                dtype: DType::F32,
11478            });
11479            let c_id = g.push(Node {
11480                op: Op::Cast(DType::F64),
11481                inputs: vec![in_id],
11482                shape: Shape::from_dims(&[3]),
11483                dtype: DType::F64,
11484            });
11485            g.set_target_backend(c_id, BackendId::Cpu);
11486            (in_id, c_id)
11487        };
11488        let mut inputs = StorageCache::new();
11489        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11490
11491        let (result_arc, result_layout) =
11492            PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
11493        assert_eq!(result_layout.shape().dims(), &[3]);
11494
11495        let guard = result_arc.read().unwrap();
11496        assert_eq!(guard.dtype, DType::F64);
11497        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11498            panic!("expected Cpu storage");
11499        };
11500        assert_eq!(c.as_slice::<f64>().unwrap(), &[1.5_f64, -2.25, 100.0]);
11501    }
11502
11503    /// E2E: Const + Cast(f32→bf16) + Cast(bf16→f32) — round trip
11504    /// through bf16; verifies the Cast wrapper's source-dtype
11505    /// dispatch (different sources hit different match arms).
11506    /// Inputs chosen to round-trip exactly through bf16.
11507    #[test]
11508    fn pipelined_realize_cast_round_trip_via_bf16() {
11509        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, -3.0, 0.5]);
11510        let graph = Arc::new(RwLock::new(Graph::new()));
11511        let (in_id, c1_id, c2_id) = {
11512            let mut g = graph.write().unwrap();
11513            let in_id = g.push(Node {
11514                op: Op::Const,
11515                inputs: vec![],
11516                shape: Shape::from_dims(&[4]),
11517                dtype: DType::F32,
11518            });
11519            let c1_id = g.push(Node {
11520                op: Op::Cast(DType::BF16),
11521                inputs: vec![in_id],
11522                shape: Shape::from_dims(&[4]),
11523                dtype: DType::BF16,
11524            });
11525            let c2_id = g.push(Node {
11526                op: Op::Cast(DType::F32),
11527                inputs: vec![c1_id],
11528                shape: Shape::from_dims(&[4]),
11529                dtype: DType::F32,
11530            });
11531            g.set_target_backend(c1_id, BackendId::Cpu);
11532            g.set_target_backend(c2_id, BackendId::Cpu);
11533            (in_id, c1_id, c2_id)
11534        };
11535        let _ = c1_id;
11536        let mut inputs = StorageCache::new();
11537        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11538
11539        let (result_arc, _) = PipelinedExecutor::realize(graph, c2_id, inputs).expect("realize");
11540        let guard = result_arc.read().unwrap();
11541        assert_eq!(guard.dtype, DType::F32);
11542        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11543            panic!("expected Cpu storage");
11544        };
11545        assert_eq!(c.as_slice::<f32>().unwrap(), &[1.0_f32, 2.0, -3.0, 0.5]);
11546    }
11547
11548    /// E2E: Const + Slice — slice is metadata-only; the output Arc
11549    /// shares bytes with the input, and the Layout's start_offset
11550    /// + narrowed shape reflect the slice. Stage 3 of Layout-on-Node
11551    ///
11552    /// extended to cover Op::Slice via Layout::narrow.
11553    #[test]
11554    fn pipelined_realize_slice_is_metadata_only() {
11555        // shape [5]; slice dim 0 from index 1 with len 3 → shape [3]
11556        // Source: [10, 20, 30, 40, 50]; slice → [20, 30, 40]
11557        let storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0]);
11558        let graph = Arc::new(RwLock::new(Graph::new()));
11559        let (in_id, s_id) = {
11560            let mut g = graph.write().unwrap();
11561            let in_id = g.push(Node {
11562                op: Op::Const,
11563                inputs: vec![],
11564                shape: Shape::from_dims(&[5]),
11565                dtype: DType::F32,
11566            });
11567            let s_id = g.push(Node {
11568                op: Op::Slice {
11569                    dim: 0,
11570                    start: 1,
11571                    len: 3,
11572                },
11573                inputs: vec![in_id],
11574                shape: Shape::from_dims(&[3]),
11575                dtype: DType::F32,
11576            });
11577            (in_id, s_id)
11578        };
11579        let mut inputs = StorageCache::new();
11580        let in_arc = Arc::new(RwLock::new(storage));
11581        inputs.insert(in_id, Arc::clone(&in_arc));
11582
11583        let (result_arc, result_layout) =
11584            PipelinedExecutor::realize(graph, s_id, inputs).expect("realize");
11585
11586        // Bytes shared with the input.
11587        assert!(Arc::ptr_eq(&result_arc, &in_arc));
11588        assert_eq!(result_layout.shape().dims(), &[3]);
11589        // Slice into a contiguous source: the resulting layout has
11590        // start_offset = original_stride[0] * start = 1 * 1 = 1,
11591        // and stride [1] (still contiguous within the narrowed dim).
11592        assert_eq!(result_layout.start_offset(), 1);
11593        assert_eq!(result_layout.stride(), &[1]);
11594    }
11595
11596    /// E2E: Const + Slice + SumAll — slice is metadata-only, but
11597    /// sum needs contiguous bytes, so auto-Contiguize materializes
11598    /// the slice before reduce. Tests the stage 3+4 integration
11599    /// through Op::Slice. Sum of `[20, 30, 40]` is 90.
11600    #[test]
11601    fn pipelined_realize_slice_then_sum_all() {
11602        let storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0]);
11603        let graph = Arc::new(RwLock::new(Graph::new()));
11604        let (in_id, s_id, sum_id) = {
11605            let mut g = graph.write().unwrap();
11606            let in_id = g.push(Node {
11607                op: Op::Const,
11608                inputs: vec![],
11609                shape: Shape::from_dims(&[5]),
11610                dtype: DType::F32,
11611            });
11612            let s_id = g.push(Node {
11613                op: Op::Slice {
11614                    dim: 0,
11615                    start: 1,
11616                    len: 3,
11617                },
11618                inputs: vec![in_id],
11619                shape: Shape::from_dims(&[3]),
11620                dtype: DType::F32,
11621            });
11622            let sum_id = g.push(Node {
11623                op: Op::SumAll,
11624                inputs: vec![s_id],
11625                shape: Shape::from_dims(&[]),
11626                dtype: DType::F32,
11627            });
11628            g.set_target_backend(sum_id, BackendId::Cpu);
11629            (in_id, s_id, sum_id)
11630        };
11631        let _ = s_id;
11632        let mut inputs = StorageCache::new();
11633        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11634
11635        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
11636        let guard = result_arc.read().unwrap();
11637        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11638            panic!("expected Cpu storage");
11639        };
11640        assert_eq!(c.as_slice::<f32>().unwrap(), &[90.0]);
11641    }
11642
11643    /// E2E: Const + Flip + ReluElementwise — Flip is metadata-only,
11644    /// then a kernel that doesn't yet handle negative strides forces
11645    /// auto-Contiguize to materialize through StridedIndex (which
11646    /// handles signed strides natively). Verifies the post-flip
11647    /// data ordering ([4, 3, 2, 1]) is correctly seen by the kernel.
11648    #[test]
11649    fn pipelined_realize_flip_then_relu_materializes_in_reverse() {
11650        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
11651        let graph = Arc::new(RwLock::new(Graph::new()));
11652        let (in_id, _f_id, r_id) = {
11653            let mut g = graph.write().unwrap();
11654            let in_id = g.push(Node {
11655                op: Op::Const,
11656                inputs: vec![],
11657                shape: Shape::from_dims(&[4]),
11658                dtype: DType::F32,
11659            });
11660            let f_id = g.push(Node {
11661                op: Op::Flip { dim: 0 },
11662                inputs: vec![in_id],
11663                shape: Shape::from_dims(&[4]),
11664                dtype: DType::F32,
11665            });
11666            let r_id = g.push(Node {
11667                op: Op::Relu,
11668                inputs: vec![f_id],
11669                shape: Shape::from_dims(&[4]),
11670                dtype: DType::F32,
11671            });
11672            g.set_target_backend(r_id, BackendId::Cpu);
11673            (in_id, f_id, r_id)
11674        };
11675        let mut inputs = StorageCache::new();
11676        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11677
11678        let (result_arc, result_layout) =
11679            PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
11680        let guard = result_arc.read().unwrap();
11681        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11682            panic!("expected Cpu storage");
11683        };
11684        assert_eq!(c.as_slice::<f32>().unwrap(), &[4.0, 3.0, 2.0, 1.0]);
11685        assert_eq!(result_layout.shape().dims(), &[4]);
11686        assert!(result_layout.is_contiguous(), "relu output is contiguous");
11687    }
11688
11689    /// E2E: Const + BroadcastTo — verifies that broadcast layouts
11690    /// have stride 0 on the broadcast dim while sharing the input's
11691    /// bytes. Stage 3 of Layout-on-Node.
11692    #[test]
11693    fn pipelined_realize_broadcast_is_metadata_only() {
11694        // shape [3]; broadcast to [4, 3] — leading dim is 0-stride
11695        let storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
11696        let graph = Arc::new(RwLock::new(Graph::new()));
11697        let (in_id, b_id) = {
11698            let mut g = graph.write().unwrap();
11699            let in_id = g.push(Node {
11700                op: Op::Const,
11701                inputs: vec![],
11702                shape: Shape::from_dims(&[3]),
11703                dtype: DType::F32,
11704            });
11705            let b_id = g.push(Node {
11706                op: Op::BroadcastTo(Shape::from_dims(&[4, 3])),
11707                inputs: vec![in_id],
11708                shape: Shape::from_dims(&[4, 3]),
11709                dtype: DType::F32,
11710            });
11711            (in_id, b_id)
11712        };
11713        let mut inputs = StorageCache::new();
11714        let in_arc = Arc::new(RwLock::new(storage));
11715        inputs.insert(in_id, Arc::clone(&in_arc));
11716
11717        let (result_arc, result_layout) =
11718            PipelinedExecutor::realize(graph, b_id, inputs).expect("realize");
11719
11720        assert!(Arc::ptr_eq(&result_arc, &in_arc));
11721        assert_eq!(result_layout.shape().dims(), &[4, 3]);
11722        // Broadcasted leading dim has stride 0.
11723        assert_eq!(result_layout.stride(), &[0, 1]);
11724    }
11725
11726    /// E2E: Const + Const + MatMul — exercises rank-2 matmul
11727    /// through the pipelined executor. Inputs are contiguous (no
11728    /// auto-Contiguize needed); the kernel walks them via the
11729    /// (m, n, k) carried in OpParams::Matmul.
11730    #[test]
11731    fn pipelined_realize_matmul_2x3_times_3x2() {
11732        // [[1, 2, 3], [4, 5, 6]] @ [[7, 8], [9, 10], [11, 12]]
11733        //   = [[58, 64], [139, 154]]
11734        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
11735        let rhs_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0, 9.0, 10.0, 11.0, 12.0]);
11736
11737        let graph = Arc::new(RwLock::new(Graph::new()));
11738        let (lhs_id, rhs_id, mm_id) = {
11739            let mut g = graph.write().unwrap();
11740            let lhs = g.push(Node {
11741                op: Op::Const,
11742                inputs: vec![],
11743                shape: Shape::from_dims(&[2, 3]),
11744                dtype: DType::F32,
11745            });
11746            let rhs = g.push(Node {
11747                op: Op::Const,
11748                inputs: vec![],
11749                shape: Shape::from_dims(&[3, 2]),
11750                dtype: DType::F32,
11751            });
11752            let mm = g.push(Node {
11753                op: Op::MatMul,
11754                inputs: vec![lhs, rhs],
11755                shape: Shape::from_dims(&[2, 2]),
11756                dtype: DType::F32,
11757            });
11758            g.set_target_backend(mm, BackendId::Cpu);
11759            (lhs, rhs, mm)
11760        };
11761        let mut inputs = StorageCache::new();
11762        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
11763        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
11764
11765        let (result_arc, result_layout) =
11766            PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11767        assert_eq!(result_layout.shape().dims(), &[2, 2]);
11768        assert!(result_layout.is_contiguous());
11769
11770        let guard = result_arc.read().unwrap();
11771        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11772            panic!("expected Cpu storage");
11773        };
11774        assert_eq!(c.as_slice::<f32>().unwrap(), &[58.0, 64.0, 139.0, 154.0]);
11775    }
11776
11777    /// E2E: batched matmul through the pipelined executor. Two
11778    /// batches of [2, 2] @ [2, 2]; the kernel iterates over
11779    /// `batch_count` and produces concatenated outputs.
11780    #[test]
11781    fn pipelined_realize_matmul_batched_2x_2x2_times_2x2() {
11782        let lhs_storage = fuel_memory::from_slice_cpu(&[
11783            1.0_f32, 2.0, 3.0, 4.0, // batch 0
11784            1.0, 0.0, 0.0, 1.0, // batch 1 (identity)
11785        ]);
11786        let rhs_storage = fuel_memory::from_slice_cpu(&[
11787            5.0_f32, 6.0, 7.0, 8.0, // batch 0
11788            10.0, 20.0, 30.0, 40.0, // batch 1
11789        ]);
11790
11791        let graph = Arc::new(RwLock::new(Graph::new()));
11792        let (lhs_id, rhs_id, mm_id) = {
11793            let mut g = graph.write().unwrap();
11794            let lhs = g.push(Node {
11795                op: Op::Const,
11796                inputs: vec![],
11797                shape: Shape::from_dims(&[2, 2, 2]),
11798                dtype: DType::F32,
11799            });
11800            let rhs = g.push(Node {
11801                op: Op::Const,
11802                inputs: vec![],
11803                shape: Shape::from_dims(&[2, 2, 2]),
11804                dtype: DType::F32,
11805            });
11806            let mm = g.push(Node {
11807                op: Op::MatMul,
11808                inputs: vec![lhs, rhs],
11809                shape: Shape::from_dims(&[2, 2, 2]),
11810                dtype: DType::F32,
11811            });
11812            g.set_target_backend(mm, BackendId::Cpu);
11813            (lhs, rhs, mm)
11814        };
11815        let mut inputs = StorageCache::new();
11816        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
11817        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
11818
11819        let (result_arc, result_layout) =
11820            PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11821        assert_eq!(result_layout.shape().dims(), &[2, 2, 2]);
11822        assert!(result_layout.is_contiguous());
11823
11824        let guard = result_arc.read().unwrap();
11825        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11826            panic!("expected Cpu storage");
11827        };
11828        // batch 0: [[1,2],[3,4]] @ [[5,6],[7,8]] = [[19,22],[43,50]]
11829        // batch 1: identity @ [[10,20],[30,40]]   = [[10,20],[30,40]]
11830        assert_eq!(
11831            c.as_slice::<f32>().unwrap(),
11832            &[19.0, 22.0, 43.0, 50.0, 10.0, 20.0, 30.0, 40.0]
11833        );
11834    }
11835
11836    /// E2E: F64 elementwise add through the pipelined executor.
11837    /// Verifies that capability-driven dispatch correctly routes
11838    /// (AddElementwise, F64) to the f64 wrapper/kernel.
11839    #[test]
11840    fn pipelined_realize_add_f64() {
11841        let lhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0]);
11842        let rhs = fuel_memory::from_slice_cpu(&[10.0_f64, 20.0, 30.0]);
11843        let graph = Arc::new(RwLock::new(Graph::new()));
11844        let (l_id, r_id, op_id) = {
11845            let mut g = graph.write().unwrap();
11846            let l = g.push(Node {
11847                op: Op::Const,
11848                inputs: vec![],
11849                shape: Shape::from_dims(&[3]),
11850                dtype: DType::F64,
11851            });
11852            let r = g.push(Node {
11853                op: Op::Const,
11854                inputs: vec![],
11855                shape: Shape::from_dims(&[3]),
11856                dtype: DType::F64,
11857            });
11858            let op = g.push(Node {
11859                op: Op::Add,
11860                inputs: vec![l, r],
11861                shape: Shape::from_dims(&[3]),
11862                dtype: DType::F64,
11863            });
11864            g.set_target_backend(op, BackendId::Cpu);
11865            (l, r, op)
11866        };
11867        let mut inputs = StorageCache::new();
11868        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11869        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11870        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
11871        let guard = result_arc.read().unwrap();
11872        assert_eq!(guard.dtype, DType::F64);
11873        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11874            panic!("expected Cpu storage");
11875        };
11876        assert_eq!(c.as_slice::<f64>().unwrap(), &[11.0_f64, 22.0, 33.0]);
11877    }
11878
11879    /// E2E: Op::Equal F32 → Bool mask through the pipelined executor (GAP-168c).
11880    /// Verifies (a) the binding-table key `(EqualElementwise, [F32, F32, U8],
11881    /// Cpu)` resolves, (b) the executor allocates a U8-sized output
11882    /// buffer (1 byte per element, not 4), (c) the kernel writes the
11883    /// expected mask bits including IEEE-754 NaN handling
11884    /// (`NaN == NaN` is false).
11885    #[test]
11886    fn pipelined_realize_eq_f32_to_bool_mask() {
11887        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, f32::NAN, 0.0]);
11888        let rhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -0.0]);
11889        let graph = Arc::new(RwLock::new(Graph::new()));
11890        let (l_id, r_id, eq_id) = {
11891            let mut g = graph.write().unwrap();
11892            let l = g.push(Node {
11893                op: Op::Const,
11894                inputs: vec![],
11895                shape: Shape::from_dims(&[5]),
11896                dtype: DType::F32,
11897            });
11898            let r = g.push(Node {
11899                op: Op::Const,
11900                inputs: vec![],
11901                shape: Shape::from_dims(&[5]),
11902                dtype: DType::F32,
11903            });
11904            let eq = g.push(Node {
11905                op: Op::Equal,
11906                inputs: vec![l, r],
11907                shape: Shape::from_dims(&[5]),
11908                dtype: DType::Bool,
11909            });
11910            g.set_target_backend(eq, BackendId::Cpu);
11911            (l, r, eq)
11912        };
11913        let mut inputs = StorageCache::new();
11914        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11915        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11916        let (result_arc, _) = PipelinedExecutor::realize(graph, eq_id, inputs).expect("realize");
11917        let guard = result_arc.read().unwrap();
11918        assert_eq!(guard.dtype, DType::Bool);
11919        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11920            panic!("expected Cpu storage");
11921        };
11922        let mask: &[u8] = c.as_slice().expect("u8 view");
11923        // Index 0: 1.0 == 1.0 → 1.
11924        // Index 1: 2.0 != 5.0 → 0.
11925        // Index 2: 3.0 == 3.0 → 1.
11926        // Index 3: NaN == NaN → 0 (IEEE-754).
11927        // Index 4: 0.0 == -0.0 → 1 (IEEE-754 zero equality).
11928        assert_eq!(mask, &[1, 0, 1, 0, 1]);
11929    }
11930
11931    /// E2E: Op::Ne F32 → Bool mask. Mirrors the Eq F32 test with
11932    /// inverted predicate; NaN-vs-NaN slot now yields `1` (since
11933    /// `NaN != NaN` per IEEE-754).
11934    #[test]
11935    fn pipelined_realize_ne_f32_to_bool_mask() {
11936        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, f32::NAN, 0.0]);
11937        let rhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -0.0]);
11938        let graph = Arc::new(RwLock::new(Graph::new()));
11939        let (l_id, r_id, ne_id) = {
11940            let mut g = graph.write().unwrap();
11941            let l = g.push(Node {
11942                op: Op::Const,
11943                inputs: vec![],
11944                shape: Shape::from_dims(&[5]),
11945                dtype: DType::F32,
11946            });
11947            let r = g.push(Node {
11948                op: Op::Const,
11949                inputs: vec![],
11950                shape: Shape::from_dims(&[5]),
11951                dtype: DType::F32,
11952            });
11953            let ne = g.push(Node {
11954                op: Op::Ne,
11955                inputs: vec![l, r],
11956                shape: Shape::from_dims(&[5]),
11957                dtype: DType::Bool,
11958            });
11959            g.set_target_backend(ne, BackendId::Cpu);
11960            (l, r, ne)
11961        };
11962        let mut inputs = StorageCache::new();
11963        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11964        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11965        let (result_arc, _) = PipelinedExecutor::realize(graph, ne_id, inputs).expect("realize");
11966        let guard = result_arc.read().unwrap();
11967        assert_eq!(guard.dtype, DType::Bool);
11968        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11969            panic!("expected Cpu storage");
11970        };
11971        let mask: &[u8] = c.as_slice().expect("u8 view");
11972        // Inverse of the Eq test:
11973        // 1.0 != 1.0 → 0;  2.0 != 5.0 → 1;  3.0 != 3.0 → 0;
11974        // NaN != NaN → 1 (IEEE-754);  0.0 != -0.0 → 0 (IEEE-754).
11975        assert_eq!(mask, &[0, 1, 0, 1, 0]);
11976    }
11977
11978    /// E2E: Op::Lt F32 → Bool mask. Confirms strict-less-than semantics
11979    /// + IEEE-754 NaN handling (any comparison with NaN is unordered →
11980    ///
11981    /// `0`).
11982    #[test]
11983    fn pipelined_realize_lt_f32_to_bool_mask() {
11984        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -1.0]);
11985        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 3.0, 0.0, 0.0]);
11986        let graph = Arc::new(RwLock::new(Graph::new()));
11987        let (l_id, r_id, lt_id) = {
11988            let mut g = graph.write().unwrap();
11989            let l = g.push(Node {
11990                op: Op::Const,
11991                inputs: vec![],
11992                shape: Shape::from_dims(&[5]),
11993                dtype: DType::F32,
11994            });
11995            let r = g.push(Node {
11996                op: Op::Const,
11997                inputs: vec![],
11998                shape: Shape::from_dims(&[5]),
11999                dtype: DType::F32,
12000            });
12001            let lt = g.push(Node {
12002                op: Op::Lt,
12003                inputs: vec![l, r],
12004                shape: Shape::from_dims(&[5]),
12005                dtype: DType::Bool,
12006            });
12007            g.set_target_backend(lt, BackendId::Cpu);
12008            (l, r, lt)
12009        };
12010        let mut inputs = StorageCache::new();
12011        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
12012        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
12013        let (result_arc, _) = PipelinedExecutor::realize(graph, lt_id, inputs).expect("realize");
12014        let guard = result_arc.read().unwrap();
12015        assert_eq!(guard.dtype, DType::Bool);
12016        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12017            panic!("expected Cpu storage");
12018        };
12019        let mask: &[u8] = c.as_slice().expect("u8 view");
12020        // 1.0 < 2.0 → 1;  5.0 < 5.0 → 0 (strict);  3.0 < 3.0 → 0;
12021        // NaN < 0.0 → 0 (unordered);  -1.0 < 0.0 → 1.
12022        assert_eq!(mask, &[1, 0, 0, 0, 1]);
12023    }
12024
12025    /// E2E: Op::Le F32 → Bool mask. Distinct from Lt at the equal slot
12026    /// (`5.0 <= 5.0` = 1, vs Lt's `5.0 < 5.0` = 0). NaN unordered → 0.
12027    #[test]
12028    fn pipelined_realize_le_f32_to_bool_mask() {
12029        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -1.0]);
12030        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 2.0, 0.0, 0.0]);
12031        let graph = Arc::new(RwLock::new(Graph::new()));
12032        let (l_id, r_id, le_id) = {
12033            let mut g = graph.write().unwrap();
12034            let l = g.push(Node {
12035                op: Op::Const,
12036                inputs: vec![],
12037                shape: Shape::from_dims(&[5]),
12038                dtype: DType::F32,
12039            });
12040            let r = g.push(Node {
12041                op: Op::Const,
12042                inputs: vec![],
12043                shape: Shape::from_dims(&[5]),
12044                dtype: DType::F32,
12045            });
12046            let le = g.push(Node {
12047                op: Op::Le,
12048                inputs: vec![l, r],
12049                shape: Shape::from_dims(&[5]),
12050                dtype: DType::Bool,
12051            });
12052            g.set_target_backend(le, BackendId::Cpu);
12053            (l, r, le)
12054        };
12055        let mut inputs = StorageCache::new();
12056        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
12057        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
12058        let (result_arc, _) = PipelinedExecutor::realize(graph, le_id, inputs).expect("realize");
12059        let guard = result_arc.read().unwrap();
12060        assert_eq!(guard.dtype, DType::Bool);
12061        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12062            panic!("expected Cpu storage");
12063        };
12064        let mask: &[u8] = c.as_slice().expect("u8 view");
12065        // 1.0 <= 2.0 → 1;  5.0 <= 5.0 → 1 (key Lt difference);
12066        // 3.0 <= 2.0 → 0;  NaN <= 0.0 → 0 (unordered);  -1.0 <= 0.0 → 1.
12067        assert_eq!(mask, &[1, 1, 0, 0, 1]);
12068    }
12069
12070    /// E2E: Op::Gt F32 → Bool mask. Strict-greater: equality slot is
12071    /// `0`. NaN unordered → `0`.
12072    #[test]
12073    fn pipelined_realize_gt_f32_to_bool_mask() {
12074        let lhs = fuel_memory::from_slice_cpu(&[3.0_f32, 5.0, 2.0, f32::NAN, 1.0]);
12075        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 3.0, 0.0, 0.0]);
12076        let graph = Arc::new(RwLock::new(Graph::new()));
12077        let (l_id, r_id, gt_id) = {
12078            let mut g = graph.write().unwrap();
12079            let l = g.push(Node {
12080                op: Op::Const,
12081                inputs: vec![],
12082                shape: Shape::from_dims(&[5]),
12083                dtype: DType::F32,
12084            });
12085            let r = g.push(Node {
12086                op: Op::Const,
12087                inputs: vec![],
12088                shape: Shape::from_dims(&[5]),
12089                dtype: DType::F32,
12090            });
12091            let gt = g.push(Node {
12092                op: Op::Gt,
12093                inputs: vec![l, r],
12094                shape: Shape::from_dims(&[5]),
12095                dtype: DType::Bool,
12096            });
12097            g.set_target_backend(gt, BackendId::Cpu);
12098            (l, r, gt)
12099        };
12100        let mut inputs = StorageCache::new();
12101        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
12102        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
12103        let (result_arc, _) = PipelinedExecutor::realize(graph, gt_id, inputs).expect("realize");
12104        let guard = result_arc.read().unwrap();
12105        assert_eq!(guard.dtype, DType::Bool);
12106        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12107            panic!("expected Cpu storage");
12108        };
12109        let mask: &[u8] = c.as_slice().expect("u8 view");
12110        // 3.0 > 2.0 → 1;  5.0 > 5.0 → 0 (strict);  2.0 > 3.0 → 0;
12111        // NaN > 0.0 → 0 (unordered);  1.0 > 0.0 → 1.
12112        assert_eq!(mask, &[1, 0, 0, 0, 1]);
12113    }
12114
12115    /// E2E: Op::Ge F32 → Bool mask. Greater-or-equal: equality slot
12116    /// is `1` (distinguishes from Gt). NaN unordered → `0`. Closes
12117    /// the comparison family with full `[Eq, Ne, Lt, Le, Gt, Ge]`
12118    /// coverage.
12119    #[test]
12120    fn pipelined_realize_ge_f32_to_bool_mask() {
12121        let lhs = fuel_memory::from_slice_cpu(&[3.0_f32, 5.0, 2.0, f32::NAN, 0.0]);
12122        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 3.0, 0.0, 0.0]);
12123        let graph = Arc::new(RwLock::new(Graph::new()));
12124        let (l_id, r_id, ge_id) = {
12125            let mut g = graph.write().unwrap();
12126            let l = g.push(Node {
12127                op: Op::Const,
12128                inputs: vec![],
12129                shape: Shape::from_dims(&[5]),
12130                dtype: DType::F32,
12131            });
12132            let r = g.push(Node {
12133                op: Op::Const,
12134                inputs: vec![],
12135                shape: Shape::from_dims(&[5]),
12136                dtype: DType::F32,
12137            });
12138            let ge = g.push(Node {
12139                op: Op::Ge,
12140                inputs: vec![l, r],
12141                shape: Shape::from_dims(&[5]),
12142                dtype: DType::Bool,
12143            });
12144            g.set_target_backend(ge, BackendId::Cpu);
12145            (l, r, ge)
12146        };
12147        let mut inputs = StorageCache::new();
12148        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
12149        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
12150        let (result_arc, _) = PipelinedExecutor::realize(graph, ge_id, inputs).expect("realize");
12151        let guard = result_arc.read().unwrap();
12152        assert_eq!(guard.dtype, DType::Bool);
12153        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12154            panic!("expected Cpu storage");
12155        };
12156        let mask: &[u8] = c.as_slice().expect("u8 view");
12157        // 3.0 >= 2.0 → 1;  5.0 >= 5.0 → 1 (key Gt difference);
12158        // 2.0 >= 3.0 → 0;  NaN >= 0.0 → 0 (unordered);  0.0 >= 0.0 → 1.
12159        assert_eq!(mask, &[1, 1, 0, 0, 1]);
12160    }
12161
12162    /// E2E: Op::Equal F64 → Bool mask. Confirms the F64 wrapper is
12163    /// independently registered and routed (binding-table key
12164    /// `(EqualElementwise, [F64, F64, U8], Cpu)`).
12165    #[test]
12166    fn pipelined_realize_eq_f64_to_bool_mask() {
12167        let lhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0]);
12168        let rhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 4.0]);
12169        let graph = Arc::new(RwLock::new(Graph::new()));
12170        let (l_id, r_id, eq_id) = {
12171            let mut g = graph.write().unwrap();
12172            let l = g.push(Node {
12173                op: Op::Const,
12174                inputs: vec![],
12175                shape: Shape::from_dims(&[3]),
12176                dtype: DType::F64,
12177            });
12178            let r = g.push(Node {
12179                op: Op::Const,
12180                inputs: vec![],
12181                shape: Shape::from_dims(&[3]),
12182                dtype: DType::F64,
12183            });
12184            let eq = g.push(Node {
12185                op: Op::Equal,
12186                inputs: vec![l, r],
12187                shape: Shape::from_dims(&[3]),
12188                dtype: DType::Bool,
12189            });
12190            g.set_target_backend(eq, BackendId::Cpu);
12191            (l, r, eq)
12192        };
12193        let mut inputs = StorageCache::new();
12194        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
12195        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
12196        let (result_arc, _) = PipelinedExecutor::realize(graph, eq_id, inputs).expect("realize");
12197        let guard = result_arc.read().unwrap();
12198        assert_eq!(guard.dtype, DType::Bool);
12199        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12200            panic!("expected Cpu storage");
12201        };
12202        let mask: &[u8] = c.as_slice().expect("u8 view");
12203        assert_eq!(mask, &[1, 1, 0]);
12204    }
12205
12206    /// E2E: Op::Where ternary select — `out[i] = if cond[i] != 0 { a[i] } else { b[i] }`.
12207    /// Validates (a) the binding-table key `(Where, [Bool, F32, F32, F32], Cpu)`
12208    /// resolves to the where_f32 wrapper, (b) the Bool cond input drives
12209    /// the per-slot pick, (c) outputs preserve the input dtype.
12210    ///
12211    /// GAP-168(c): the cond STORAGE is tagged Bool, not merely the graph node.
12212    /// Bool and U8 are byte-identical, so leaving the storage U8 under a Bool
12213    /// node is exactly the mismatch this cut exists to make visible.
12214    #[test]
12215    fn pipelined_realize_where_f32_picks_per_slot_from_bool_mask() {
12216        // cond = [1, 0, 1, 0, 1]; a = [1, 2, 3, 4, 5]; b = [10, 20, 30, 40, 50]
12217        // expected = [1, 20, 3, 40, 5]
12218        let mut cond_storage = fuel_memory::from_slice_cpu(&[1u8, 0, 1, 0, 1]);
12219        cond_storage.dtype = DType::Bool; // GAP-168(c): a Bool mask, not U8 bytes
12220        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0]);
12221        let b_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0]);
12222        let graph = Arc::new(RwLock::new(Graph::new()));
12223        let (cond_id, a_id, b_id, where_id) = {
12224            let mut g = graph.write().unwrap();
12225            let cond = g.push(Node {
12226                op: Op::Const,
12227                inputs: vec![],
12228                shape: Shape::from_dims(&[5]),
12229                dtype: DType::Bool,
12230            });
12231            let a = g.push(Node {
12232                op: Op::Const,
12233                inputs: vec![],
12234                shape: Shape::from_dims(&[5]),
12235                dtype: DType::F32,
12236            });
12237            let b = g.push(Node {
12238                op: Op::Const,
12239                inputs: vec![],
12240                shape: Shape::from_dims(&[5]),
12241                dtype: DType::F32,
12242            });
12243            let w = g.push(Node {
12244                op: Op::Where,
12245                inputs: vec![cond, a, b],
12246                shape: Shape::from_dims(&[5]),
12247                dtype: DType::F32,
12248            });
12249            g.set_target_backend(w, BackendId::Cpu);
12250            (cond, a, b, w)
12251        };
12252        let mut inputs = StorageCache::new();
12253        inputs.insert(cond_id, Arc::new(RwLock::new(cond_storage)));
12254        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
12255        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
12256        let (result_arc, _) = PipelinedExecutor::realize(graph, where_id, inputs).expect("realize");
12257        let guard = result_arc.read().unwrap();
12258        assert_eq!(guard.dtype, DType::F32);
12259        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12260            panic!("expected Cpu storage");
12261        };
12262        let out: &[f32] = c.as_slice().expect("f32 view");
12263        assert_eq!(out, &[1.0, 20.0, 3.0, 40.0, 5.0]);
12264    }
12265
12266    /// E2E: full chain `eq → where`. Compares two f32 vectors, then
12267    /// uses the resulting Bool mask to pick from a third tensor (or a
12268    /// fallback). Validates the comparison-family + Where ops compose
12269    /// end-to-end.
12270    #[test]
12271    fn pipelined_realize_eq_then_where_full_chain() {
12272        // a = [1, 2, 3]; b = [1, 5, 3] → eq = [1, 0, 1]
12273        // pick = [10, 20, 30]; fallback = [99, 99, 99]
12274        // result = [10, 99, 30]
12275        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
12276        let b_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0]);
12277        let pick_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
12278        let fb_storage = fuel_memory::from_slice_cpu(&[99.0_f32, 99.0, 99.0]);
12279        let graph = Arc::new(RwLock::new(Graph::new()));
12280        let (a_id, b_id, pick_id, fb_id, where_id) = {
12281            let mut g = graph.write().unwrap();
12282            let a = g.push(Node {
12283                op: Op::Const,
12284                inputs: vec![],
12285                shape: Shape::from_dims(&[3]),
12286                dtype: DType::F32,
12287            });
12288            let b = g.push(Node {
12289                op: Op::Const,
12290                inputs: vec![],
12291                shape: Shape::from_dims(&[3]),
12292                dtype: DType::F32,
12293            });
12294            let pick = g.push(Node {
12295                op: Op::Const,
12296                inputs: vec![],
12297                shape: Shape::from_dims(&[3]),
12298                dtype: DType::F32,
12299            });
12300            let fb = g.push(Node {
12301                op: Op::Const,
12302                inputs: vec![],
12303                shape: Shape::from_dims(&[3]),
12304                dtype: DType::F32,
12305            });
12306            let eq = g.push(Node {
12307                op: Op::Equal,
12308                inputs: vec![a, b],
12309                shape: Shape::from_dims(&[3]),
12310                dtype: DType::Bool,
12311            });
12312            let w = g.push(Node {
12313                op: Op::Where,
12314                inputs: vec![eq, pick, fb],
12315                shape: Shape::from_dims(&[3]),
12316                dtype: DType::F32,
12317            });
12318            g.set_target_backend(eq, BackendId::Cpu);
12319            g.set_target_backend(w, BackendId::Cpu);
12320            (a, b, pick, fb, w)
12321        };
12322        let mut inputs = StorageCache::new();
12323        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
12324        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
12325        inputs.insert(pick_id, Arc::new(RwLock::new(pick_storage)));
12326        inputs.insert(fb_id, Arc::new(RwLock::new(fb_storage)));
12327        let (result_arc, _) = PipelinedExecutor::realize(graph, where_id, inputs).expect("realize");
12328        let guard = result_arc.read().unwrap();
12329        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12330            panic!("expected Cpu storage");
12331        };
12332        let out: &[f32] = c.as_slice().expect("f32 view");
12333        assert_eq!(out, &[10.0, 99.0, 30.0]);
12334    }
12335
12336    /// E2E: Q4_0 QMatMul through the pipelined executor — proves
12337    /// quantized weights can flow into the unified path. Activations
12338    /// are F32, weights are U32-typed (raw block bytes).
12339    /// Construct a Q4_0 weight tensor where every weight = 1.0
12340    /// (d=1.0, every nibble=9 → 1*(9-8)=1), so A @ W^T computes
12341    /// the per-row sum of activations.
12342    #[test]
12343    fn pipelined_realize_qmatmul_q4_0_unit_weight_sums_activations() {
12344        use fuel_graph::QuantType;
12345        use half::f16;
12346        let block_size = std::mem::size_of::<fuel_quantized::BlockQ4_0>();
12347        let mut w_bytes = vec![0u8; 2 * block_size];
12348        for block_idx in 0..2 {
12349            let off = block_idx * block_size;
12350            let d_bytes = f16::from_f32(1.0).to_le_bytes();
12351            w_bytes[off..off + 2].copy_from_slice(&d_bytes);
12352            for i in 0..16 {
12353                w_bytes[off + 2 + i] = 0x99;
12354            }
12355        }
12356        // Weight tensor is U32-typed (rank-1, length = bytes/4)
12357        let w_storage = fuel_memory::Storage::new(
12358            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
12359                &w_bytes,
12360            )),
12361            DType::U32,
12362        );
12363
12364        let act_vec: Vec<f32> = (1..=32).map(|x| x as f32).collect();
12365        let act_storage = fuel_memory::from_slice_cpu(&act_vec);
12366
12367        let graph = Arc::new(RwLock::new(Graph::new()));
12368        let (act_id, w_id, mm_id) = {
12369            let mut g = graph.write().unwrap();
12370            let act = g.push(Node {
12371                op: Op::Const,
12372                inputs: vec![],
12373                shape: Shape::from_dims(&[1, 32]),
12374                dtype: DType::F32,
12375            });
12376            let w = g.push(Node {
12377                op: Op::Const,
12378                inputs: vec![],
12379                shape: Shape::from_dims(&[w_bytes.len() / 4]),
12380                dtype: DType::U32,
12381            });
12382            let mm = g.push(Node {
12383                op: Op::Fused(
12384                    fuel_graph::registry::FusedOps::QMATMUL,
12385                    fuel_graph::registry::FusedOpParams::QMatMul {
12386                        quant_type: QuantType::Q4_0,
12387                        k: 32,
12388                        n: 2,
12389                    },
12390                ),
12391                inputs: vec![act, w],
12392                shape: Shape::from_dims(&[1, 2]),
12393                dtype: DType::F32,
12394            });
12395            g.set_target_backend(mm, BackendId::Cpu);
12396            (act, w, mm)
12397        };
12398        let mut inputs = StorageCache::new();
12399        inputs.insert(act_id, Arc::new(RwLock::new(act_storage)));
12400        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12401        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
12402        let guard = result_arc.read().unwrap();
12403        assert_eq!(guard.dtype, DType::F32);
12404        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12405            panic!("expected Cpu storage");
12406        };
12407        let r: &[f32] = c.as_slice().unwrap();
12408        // Both rows = sum(1..=32) = 528, within Q8_1 round-trip
12409        // tolerance.
12410        assert!((r[0] - 528.0).abs() < 0.5, "got {}, want 528", r[0]);
12411        assert!((r[1] - 528.0).abs() < 0.5, "got {}, want 528", r[1]);
12412    }
12413
12414    /// E2E: QMatMul with Q5_0 weights — verifies the new quant
12415    /// dispatch arm picks `qmatmul_q5_0_f32`. We build weights by
12416    /// quantizing all-ones via `BlockQ5_0::from_float`, then
12417    /// compare pipelined output against the direct fuel_quantized
12418    /// matmul on the same blocks.
12419    #[test]
12420    fn pipelined_realize_qmatmul_q5_0_against_reference() {
12421        use fuel_graph::QuantType;
12422        use fuel_quantized::{BlockQ5_0, GgmlType};
12423        let n = 2;
12424        let k = 64; // 2 blocks per row
12425        // Quantize an all-ones [n, k] weight matrix.
12426        let w_f32 = vec![1.0_f32; n * k];
12427        let blocks_per_row = k / BlockQ5_0::BLCK_SIZE;
12428        let mut w_blocks = vec![BlockQ5_0::zeros(); n * blocks_per_row];
12429        BlockQ5_0::from_float(&w_f32, &mut w_blocks);
12430        // Reinterpret block slice as bytes (BlockQ5_0 is #[repr(C)]).
12431        let bytes_per_block = std::mem::size_of::<BlockQ5_0>();
12432        let w_bytes: Vec<u8> = unsafe {
12433            std::slice::from_raw_parts(
12434                w_blocks.as_ptr() as *const u8,
12435                w_blocks.len() * bytes_per_block,
12436            )
12437        }
12438        .to_vec();
12439        let w_storage = fuel_memory::Storage::new(
12440            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
12441                &w_bytes,
12442            )),
12443            DType::U32,
12444        );
12445        let act_vec: Vec<f32> = (1..=k).map(|x| x as f32).collect();
12446        let act_storage = fuel_memory::from_slice_cpu(&act_vec);
12447        // Reference: direct matmul through fuel_quantized.
12448        let mut ref_out = vec![0.0_f32; n];
12449        fuel_quantized::matmul::<BlockQ5_0>((1, k, n), &act_vec, &w_blocks, &mut ref_out)
12450            .expect("ref matmul");
12451
12452        let graph = Arc::new(RwLock::new(Graph::new()));
12453        let (act_id, w_id, mm_id) = {
12454            let mut g = graph.write().unwrap();
12455            let act = g.push(Node {
12456                op: Op::Const,
12457                inputs: vec![],
12458                shape: Shape::from_dims(&[1, k]),
12459                dtype: DType::F32,
12460            });
12461            let w = g.push(Node {
12462                op: Op::Const,
12463                inputs: vec![],
12464                shape: Shape::from_dims(&[w_bytes.len() / 4]),
12465                dtype: DType::U32,
12466            });
12467            let mm = g.push(Node {
12468                op: Op::Fused(
12469                    fuel_graph::registry::FusedOps::QMATMUL,
12470                    fuel_graph::registry::FusedOpParams::QMatMul {
12471                        quant_type: QuantType::Q5_0,
12472                        k,
12473                        n,
12474                    },
12475                ),
12476                inputs: vec![act, w],
12477                shape: Shape::from_dims(&[1, n]),
12478                dtype: DType::F32,
12479            });
12480            g.set_target_backend(mm, BackendId::Cpu);
12481            (act, w, mm)
12482        };
12483        let mut inputs = StorageCache::new();
12484        inputs.insert(act_id, Arc::new(RwLock::new(act_storage)));
12485        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12486        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
12487        let guard = result_arc.read().unwrap();
12488        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12489            panic!("expected Cpu storage");
12490        };
12491        let r: &[f32] = c.as_slice().unwrap();
12492        // Bit-exact against same kernel via the trait, since both
12493        // paths run fuel_quantized::matmul<BlockQ5_0>.
12494        assert_eq!(
12495            r,
12496            ref_out.as_slice(),
12497            "pipelined Q5_0 differs from reference: got {r:?}, want {ref_out:?}"
12498        );
12499    }
12500
12501    /// E2E: QMatMul with Q6K (256-element super-block k-quant).
12502    /// Same idea as the Q5_0 test — bit-exact against the
12503    /// reference fuel_quantized::matmul<BlockQ6K>. Confirms the
12504    /// dispatch arm wires `qmatmul_q6k_f32` correctly.
12505    #[test]
12506    fn pipelined_realize_qmatmul_q6k_against_reference() {
12507        use fuel_graph::QuantType;
12508        use fuel_quantized::{BlockQ6K, GgmlType};
12509        let n = 2;
12510        let k = 256; // 1 super-block per row
12511        let w_f32 = vec![1.0_f32; n * k];
12512        let blocks_per_row = k / BlockQ6K::BLCK_SIZE;
12513        let mut w_blocks = vec![BlockQ6K::zeros(); n * blocks_per_row];
12514        BlockQ6K::from_float(&w_f32, &mut w_blocks);
12515        let bytes_per_block = std::mem::size_of::<BlockQ6K>();
12516        let w_bytes: Vec<u8> = unsafe {
12517            std::slice::from_raw_parts(
12518                w_blocks.as_ptr() as *const u8,
12519                w_blocks.len() * bytes_per_block,
12520            )
12521        }
12522        .to_vec();
12523        let w_storage = fuel_memory::Storage::new(
12524            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
12525                &w_bytes,
12526            )),
12527            DType::U32,
12528        );
12529        let act_vec: Vec<f32> = (1..=k).map(|x| x as f32 / 100.0).collect();
12530        let act_storage = fuel_memory::from_slice_cpu(&act_vec);
12531        let mut ref_out = vec![0.0_f32; n];
12532        fuel_quantized::matmul::<BlockQ6K>((1, k, n), &act_vec, &w_blocks, &mut ref_out)
12533            .expect("ref matmul");
12534
12535        let graph = Arc::new(RwLock::new(Graph::new()));
12536        let (act_id, w_id, mm_id) = {
12537            let mut g = graph.write().unwrap();
12538            let act = g.push(Node {
12539                op: Op::Const,
12540                inputs: vec![],
12541                shape: Shape::from_dims(&[1, k]),
12542                dtype: DType::F32,
12543            });
12544            let w = g.push(Node {
12545                op: Op::Const,
12546                inputs: vec![],
12547                shape: Shape::from_dims(&[w_bytes.len() / 4]),
12548                dtype: DType::U32,
12549            });
12550            let mm = g.push(Node {
12551                op: Op::Fused(
12552                    fuel_graph::registry::FusedOps::QMATMUL,
12553                    fuel_graph::registry::FusedOpParams::QMatMul {
12554                        quant_type: QuantType::Q6K,
12555                        k,
12556                        n,
12557                    },
12558                ),
12559                inputs: vec![act, w],
12560                shape: Shape::from_dims(&[1, n]),
12561                dtype: DType::F32,
12562            });
12563            g.set_target_backend(mm, BackendId::Cpu);
12564            (act, w, mm)
12565        };
12566        let mut inputs = StorageCache::new();
12567        inputs.insert(act_id, Arc::new(RwLock::new(act_storage)));
12568        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12569        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
12570        let guard = result_arc.read().unwrap();
12571        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12572            panic!("expected Cpu storage");
12573        };
12574        let r: &[f32] = c.as_slice().unwrap();
12575        assert_eq!(
12576            r,
12577            ref_out.as_slice(),
12578            "pipelined Q6K differs from reference: got {r:?}, want {ref_out:?}"
12579        );
12580    }
12581
12582    /// E2E: `QMatMul` through the pipelined executor for the formats added with the float route
12583    /// (Q3_K, Q5_K, IQ4_NL, IQ4_XS, IQ3_S; board 307: dequantized tile by tile, multiplied in
12584    /// float). The weights are the type's own blocks from random bytes (a small finite `d`), the
12585    /// reference is `fuel_quantized::matmul`, and the dispatch arm must be the one for that type:
12586    /// a wrong `quant_type` arm decodes the same bytes differently and is far from the reference.
12587    fn qmatmul_e2e_random_blocks<T: fuel_quantized::GgmlType>(quant_type: fuel_graph::QuantType) {
12588        let (m, n, k) = (3, 5, 512);
12589        let size = std::mem::size_of::<T>();
12590        let count = n * k / T::BLCK_SIZE;
12591        let mut seed = 0x9E37_79B9_u32;
12592        let mut w_bytes: Vec<u8> = (0..count * size)
12593            .map(|_| {
12594                seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
12595                (seed >> 24) as u8
12596            })
12597            .collect();
12598        let d = half::f16::from_f32(0.02).to_le_bytes();
12599        for b in 0..count {
12600            w_bytes[b * size..b * size + 2].copy_from_slice(&d);
12601        }
12602        let mut w_blocks = vec![T::zeros(); count];
12603        bytemuck::cast_slice_mut::<T, u8>(&mut w_blocks).copy_from_slice(&w_bytes);
12604        let act_vec: Vec<f32> = (0..m * k).map(|x| ((x % 17) as f32 - 8.0) / 8.0).collect();
12605        let mut ref_out = vec![0.0_f32; m * n];
12606        fuel_quantized::matmul::<T>((m, k, n), &act_vec, &w_blocks, &mut ref_out).expect("ref");
12607
12608        let w_storage = fuel_memory::Storage::new(
12609            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
12610                &w_bytes,
12611            )),
12612            DType::U32,
12613        );
12614        let graph = Arc::new(RwLock::new(Graph::new()));
12615        let (act_id, w_id, mm_id) = {
12616            let mut g = graph.write().unwrap();
12617            let act = g.push(Node {
12618                op: Op::Const,
12619                inputs: vec![],
12620                shape: Shape::from_dims(&[m, k]),
12621                dtype: DType::F32,
12622            });
12623            let w = g.push(Node {
12624                op: Op::Const,
12625                inputs: vec![],
12626                shape: Shape::from_dims(&[w_bytes.len() / 4]),
12627                dtype: DType::U32,
12628            });
12629            let mm = g.push(Node {
12630                op: Op::Fused(
12631                    fuel_graph::registry::FusedOps::QMATMUL,
12632                    fuel_graph::registry::FusedOpParams::QMatMul { quant_type, k, n },
12633                ),
12634                inputs: vec![act, w],
12635                shape: Shape::from_dims(&[m, n]),
12636                dtype: DType::F32,
12637            });
12638            g.set_target_backend(mm, BackendId::Cpu);
12639            (act, w, mm)
12640        };
12641        let mut inputs = StorageCache::new();
12642        inputs.insert(
12643            act_id,
12644            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&act_vec))),
12645        );
12646        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12647        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
12648        let guard = result_arc.read().unwrap();
12649        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12650            panic!("expected Cpu storage");
12651        };
12652        let r: &[f32] = c.as_slice().unwrap();
12653        let scale = ref_out.iter().fold(1e-6_f32, |a, v| a.max(v.abs()));
12654        let worst = r
12655            .iter()
12656            .zip(&ref_out)
12657            .fold(0.0_f32, |a, (x, y)| a.max((x - y).abs()));
12658        assert!(
12659            worst <= 1e-5 * scale,
12660            "{quant_type:?}: pipelined differs from the reference by {worst} (scale {scale})"
12661        );
12662        assert!(
12663            scale > 1e-3,
12664            "{quant_type:?}: the product is all zeros, the test is vacuous"
12665        );
12666    }
12667
12668    #[test]
12669    fn pipelined_realize_qmatmul_float_route_formats_against_reference() {
12670        use fuel_graph::QuantType;
12671        use fuel_quantized::iq_grid_types::BlockIq3S;
12672        use fuel_quantized::iq4::{BlockIq4Nl, BlockIq4Xs};
12673        use fuel_quantized::{BlockQ3K, BlockQ5K};
12674        qmatmul_e2e_random_blocks::<BlockQ3K>(QuantType::Q3K);
12675        qmatmul_e2e_random_blocks::<BlockQ5K>(QuantType::Q5K);
12676        qmatmul_e2e_random_blocks::<BlockIq4Nl>(QuantType::Iq4Nl);
12677        qmatmul_e2e_random_blocks::<BlockIq4Xs>(QuantType::Iq4Xs);
12678        qmatmul_e2e_random_blocks::<BlockIq3S>(QuantType::Iq3S);
12679    }
12680
12681    /// E2E: BF16 RmsNormLastDim through the pipelined executor.
12682    /// Verifies that capability-driven dispatch routes the
12683    /// half-float norm op to the bf16-specific kernel (which
12684    /// accumulates in f32 internally).
12685    #[test]
12686    fn pipelined_realize_rms_norm_bf16() {
12687        let v: Vec<half::bf16> = [3.0_f32, 4.0]
12688            .iter()
12689            .map(|&x| half::bf16::from_f32(x))
12690            .collect();
12691        let storage = fuel_memory::from_slice_cpu(&v);
12692        let graph = Arc::new(RwLock::new(Graph::new()));
12693        let (in_id, op_id) = {
12694            let mut g = graph.write().unwrap();
12695            let in_id = g.push(Node {
12696                op: Op::Const,
12697                inputs: vec![],
12698                shape: Shape::from_dims(&[1, 2]),
12699                dtype: DType::BF16,
12700            });
12701            let op_id = g.push(Node {
12702                op: Op::Fused(
12703                    fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM,
12704                    fuel_graph::registry::FusedOpParams::RmsNormLastDim { eps: 0.0 },
12705                ),
12706                inputs: vec![in_id],
12707                shape: Shape::from_dims(&[1, 2]),
12708                dtype: DType::BF16,
12709            });
12710            g.set_target_backend(op_id, BackendId::Cpu);
12711            (in_id, op_id)
12712        };
12713        let mut inputs = StorageCache::new();
12714        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12715        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12716        let guard = result_arc.read().unwrap();
12717        assert_eq!(guard.dtype, DType::BF16);
12718        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12719            panic!("expected Cpu storage");
12720        };
12721        let r: &[half::bf16] = c.as_slice().unwrap();
12722        let rms = (12.5_f32).sqrt();
12723        // bf16's ~3-digit mantissa absorbs the divisor; allow ~5%.
12724        assert!((r[0].to_f32() - 3.0 / rms).abs() < 0.05);
12725        assert!((r[1].to_f32() - 4.0 / rms).abs() < 0.05);
12726    }
12727
12728    /// E2E: BF16 matmul through the pipelined executor — proves
12729    /// the LLM forward-pass blocker (every transformer layer
12730    /// is dominated by matmul). Identity matmul on bf16 round-
12731    /// trips small integers exactly.
12732    #[test]
12733    fn pipelined_realize_matmul_bf16_identity() {
12734        let lhs_v: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0]
12735            .iter()
12736            .map(|&x| half::bf16::from_f32(x))
12737            .collect();
12738        let rhs_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0]
12739            .iter()
12740            .map(|&x| half::bf16::from_f32(x))
12741            .collect();
12742        let lhs = fuel_memory::from_slice_cpu(&lhs_v);
12743        let rhs = fuel_memory::from_slice_cpu(&rhs_v);
12744        let graph = Arc::new(RwLock::new(Graph::new()));
12745        let (l_id, r_id, mm_id) = {
12746            let mut g = graph.write().unwrap();
12747            let l = g.push(Node {
12748                op: Op::Const,
12749                inputs: vec![],
12750                shape: Shape::from_dims(&[2, 2]),
12751                dtype: DType::BF16,
12752            });
12753            let r = g.push(Node {
12754                op: Op::Const,
12755                inputs: vec![],
12756                shape: Shape::from_dims(&[2, 2]),
12757                dtype: DType::BF16,
12758            });
12759            let mm = g.push(Node {
12760                op: Op::MatMul,
12761                inputs: vec![l, r],
12762                shape: Shape::from_dims(&[2, 2]),
12763                dtype: DType::BF16,
12764            });
12765            g.set_target_backend(mm, BackendId::Cpu);
12766            (l, r, mm)
12767        };
12768        let mut inputs = StorageCache::new();
12769        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
12770        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
12771        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
12772        let guard = result_arc.read().unwrap();
12773        assert_eq!(guard.dtype, DType::BF16);
12774        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12775            panic!("expected Cpu storage");
12776        };
12777        let r: &[half::bf16] = c.as_slice().unwrap();
12778        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
12779        assert_eq!(result_f32, vec![1.0, 2.0, 3.0, 4.0]);
12780    }
12781
12782    /// E2E (ROADMAP row 34): a mixed `[F32, W, F32]` matmul (f32 activation, half weight) runs on
12783    /// the CPU through the NATIVE kernel, with the weight left half-width: the output is f32 and
12784    /// equals the f64 matmul over the widened weights to f32 accumulation error. The weight is
12785    /// rounded to its stored half type first.
12786    fn mixed_cpu_matmul_matches_f64(weight_dtype: DType) {
12787        let (m, n, k) = (3_usize, 5_usize, 7_usize);
12788        let a: Vec<f32> = (0..m * k)
12789            .map(|i| ((i * 37 % 19) as f32 - 9.0) / 8.0)
12790            .collect();
12791        let w_f32: Vec<f32> = (0..k * n)
12792            .map(|i| ((i * 53 % 23) as f32 - 11.0) / 10.0)
12793            .collect();
12794        let (w_storage, widened): (_, Vec<f32>) = if weight_dtype == DType::BF16 {
12795            let h: Vec<half::bf16> = w_f32.iter().map(|&x| half::bf16::from_f32(x)).collect();
12796            let wide = h.iter().map(|x| x.to_f32()).collect();
12797            (fuel_memory::from_slice_cpu(&h), wide)
12798        } else {
12799            let h: Vec<half::f16> = w_f32.iter().map(|&x| half::f16::from_f32(x)).collect();
12800            let wide = h.iter().map(|x| x.to_f32()).collect();
12801            (fuel_memory::from_slice_cpu(&h), wide)
12802        };
12803        let graph = Arc::new(RwLock::new(Graph::new()));
12804        let (l_id, r_id, mm_id) = {
12805            let mut g = graph.write().unwrap();
12806            let l = g.push(Node {
12807                op: Op::Const,
12808                inputs: vec![],
12809                shape: Shape::from_dims(&[m, k]),
12810                dtype: DType::F32,
12811            });
12812            let r = g.push(Node {
12813                op: Op::Const,
12814                inputs: vec![],
12815                shape: Shape::from_dims(&[k, n]),
12816                dtype: weight_dtype,
12817            });
12818            let mm = g.push(Node {
12819                op: Op::MatMul,
12820                inputs: vec![l, r],
12821                shape: Shape::from_dims(&[m, n]),
12822                dtype: DType::F32,
12823            });
12824            g.set_target_backend(mm, BackendId::Cpu);
12825            (l, r, mm)
12826        };
12827        let mut inputs = StorageCache::new();
12828        inputs.insert(l_id, Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&a))));
12829        inputs.insert(r_id, Arc::new(RwLock::new(w_storage)));
12830        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
12831        let guard = result_arc.read().unwrap();
12832        assert_eq!(guard.dtype, DType::F32);
12833        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12834            panic!("expected Cpu storage");
12835        };
12836        let got: &[f32] = c.as_slice().unwrap();
12837        for i in 0..m {
12838            for j in 0..n {
12839                let want: f64 = (0..k)
12840                    .map(|kk| a[i * k + kk] as f64 * widened[kk * n + j] as f64)
12841                    .sum();
12842                let err = (got[i * n + j] as f64 - want).abs();
12843                assert!(
12844                    err < 1e-5,
12845                    "{weight_dtype:?} [{i},{j}]: got {}, want {want}",
12846                    got[i * n + j]
12847                );
12848            }
12849        }
12850    }
12851
12852    #[test]
12853    fn pipelined_realize_mixed_f32_bf16_matmul_is_native_on_cpu() {
12854        mixed_cpu_matmul_matches_f64(DType::BF16);
12855    }
12856
12857    #[test]
12858    fn pipelined_realize_mixed_f32_f16_matmul_is_native_on_cpu() {
12859        mixed_cpu_matmul_matches_f64(DType::F16);
12860    }
12861
12862    /// E2E: F16 sum-reduce — verifies bf16/f16 reduction dispatch
12863    /// works through the executor.
12864    #[test]
12865    fn pipelined_realize_sum_dim_f16() {
12866        let v: Vec<half::f16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]
12867            .iter()
12868            .map(|&x| half::f16::from_f32(x))
12869            .collect();
12870        let storage = fuel_memory::from_slice_cpu(&v);
12871        let graph = Arc::new(RwLock::new(Graph::new()));
12872        let (in_id, sum_id) = {
12873            let mut g = graph.write().unwrap();
12874            let in_id = g.push(Node {
12875                op: Op::Const,
12876                inputs: vec![],
12877                shape: Shape::from_dims(&[2, 3]),
12878                dtype: DType::F16,
12879            });
12880            let sum_id = g.push(Node {
12881                op: Op::SumDim(1),
12882                inputs: vec![in_id],
12883                shape: Shape::from_dims(&[2]),
12884                dtype: DType::F16,
12885            });
12886            g.set_target_backend(sum_id, BackendId::Cpu);
12887            (in_id, sum_id)
12888        };
12889        let mut inputs = StorageCache::new();
12890        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12891        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
12892        let guard = result_arc.read().unwrap();
12893        assert_eq!(guard.dtype, DType::F16);
12894        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12895            panic!("expected Cpu storage");
12896        };
12897        let r: &[half::f16] = c.as_slice().unwrap();
12898        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
12899        assert_eq!(result_f32, vec![6.0, 15.0]);
12900    }
12901
12902    /// E2E: BF16 elementwise add through the pipelined executor.
12903    #[test]
12904    fn pipelined_realize_add_bf16() {
12905        let lhs_vec: Vec<half::bf16> = [1.0_f32, 2.0, 3.0]
12906            .iter()
12907            .map(|&x| half::bf16::from_f32(x))
12908            .collect();
12909        let rhs_vec: Vec<half::bf16> = [10.0_f32, 20.0, 30.0]
12910            .iter()
12911            .map(|&x| half::bf16::from_f32(x))
12912            .collect();
12913        let lhs = fuel_memory::from_slice_cpu(&lhs_vec);
12914        let rhs = fuel_memory::from_slice_cpu(&rhs_vec);
12915        let graph = Arc::new(RwLock::new(Graph::new()));
12916        let (l_id, r_id, op_id) = {
12917            let mut g = graph.write().unwrap();
12918            let l = g.push(Node {
12919                op: Op::Const,
12920                inputs: vec![],
12921                shape: Shape::from_dims(&[3]),
12922                dtype: DType::BF16,
12923            });
12924            let r = g.push(Node {
12925                op: Op::Const,
12926                inputs: vec![],
12927                shape: Shape::from_dims(&[3]),
12928                dtype: DType::BF16,
12929            });
12930            let op = g.push(Node {
12931                op: Op::Add,
12932                inputs: vec![l, r],
12933                shape: Shape::from_dims(&[3]),
12934                dtype: DType::BF16,
12935            });
12936            g.set_target_backend(op, BackendId::Cpu);
12937            (l, r, op)
12938        };
12939        let mut inputs = StorageCache::new();
12940        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
12941        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
12942        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12943        let guard = result_arc.read().unwrap();
12944        assert_eq!(guard.dtype, DType::BF16);
12945        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12946            panic!("expected Cpu storage");
12947        };
12948        let r: &[half::bf16] = c.as_slice().unwrap();
12949        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
12950        assert_eq!(result_f32, vec![11.0, 22.0, 33.0]);
12951    }
12952
12953    /// E2E: F16 unary chain — Const + Sqr + Sqrt — verifies F16
12954    /// dispatch works and the via-f32 round-trip kernels behave
12955    /// correctly through the executor.
12956    #[test]
12957    fn pipelined_realize_sqr_then_sqrt_f16() {
12958        let v: Vec<half::f16> = [1.0_f32, 4.0, 9.0]
12959            .iter()
12960            .map(|&x| half::f16::from_f32(x))
12961            .collect();
12962        let storage = fuel_memory::from_slice_cpu(&v);
12963        let graph = Arc::new(RwLock::new(Graph::new()));
12964        let (in_id, sqrt_id) = {
12965            let mut g = graph.write().unwrap();
12966            let in_id = g.push(Node {
12967                op: Op::Const,
12968                inputs: vec![],
12969                shape: Shape::from_dims(&[3]),
12970                dtype: DType::F16,
12971            });
12972            let sqr_id = g.push(Node {
12973                op: Op::Sqr,
12974                inputs: vec![in_id],
12975                shape: Shape::from_dims(&[3]),
12976                dtype: DType::F16,
12977            });
12978            let sqrt_id = g.push(Node {
12979                op: Op::Sqrt,
12980                inputs: vec![sqr_id],
12981                shape: Shape::from_dims(&[3]),
12982                dtype: DType::F16,
12983            });
12984            g.set_target_backend(sqr_id, BackendId::Cpu);
12985            g.set_target_backend(sqrt_id, BackendId::Cpu);
12986            (in_id, sqrt_id)
12987        };
12988        let mut inputs = StorageCache::new();
12989        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12990        let (result_arc, _) = PipelinedExecutor::realize(graph, sqrt_id, inputs).expect("realize");
12991        let guard = result_arc.read().unwrap();
12992        assert_eq!(guard.dtype, DType::F16);
12993        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12994            panic!("expected Cpu storage");
12995        };
12996        let r: &[half::f16] = c.as_slice().unwrap();
12997        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
12998        // f16 has ~3 decimal digits; sqrt(sqr(x)) = |x| within rounding.
12999        for (got, want) in result_f32.iter().zip(&[1.0_f32, 4.0, 9.0]) {
13000            assert!((got - want).abs() < 0.05, "got {got}, want {want}");
13001        }
13002    }
13003
13004    /// E2E: F64 sum-reduce along one dim through the pipelined
13005    /// executor.
13006    #[test]
13007    fn pipelined_realize_sum_dim_f64() {
13008        let storage = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
13009        let graph = Arc::new(RwLock::new(Graph::new()));
13010        let (in_id, sum_id) = {
13011            let mut g = graph.write().unwrap();
13012            let in_id = g.push(Node {
13013                op: Op::Const,
13014                inputs: vec![],
13015                shape: Shape::from_dims(&[2, 3]),
13016                dtype: DType::F64,
13017            });
13018            let sum_id = g.push(Node {
13019                op: Op::SumDim(1),
13020                inputs: vec![in_id],
13021                shape: Shape::from_dims(&[2]),
13022                dtype: DType::F64,
13023            });
13024            g.set_target_backend(sum_id, BackendId::Cpu);
13025            (in_id, sum_id)
13026        };
13027        let mut inputs = StorageCache::new();
13028        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
13029        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
13030        let guard = result_arc.read().unwrap();
13031        assert_eq!(guard.dtype, DType::F64);
13032        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13033            panic!("expected Cpu storage");
13034        };
13035        assert_eq!(c.as_slice::<f64>().unwrap(), &[6.0_f64, 15.0]);
13036    }
13037
13038    /// E2E: F64 matmul through the pipelined executor.
13039    #[test]
13040    fn pipelined_realize_matmul_2x3_times_3x2_f64() {
13041        let lhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
13042        let rhs = fuel_memory::from_slice_cpu(&[7.0_f64, 8.0, 9.0, 10.0, 11.0, 12.0]);
13043        let graph = Arc::new(RwLock::new(Graph::new()));
13044        let (l_id, r_id, mm_id) = {
13045            let mut g = graph.write().unwrap();
13046            let l = g.push(Node {
13047                op: Op::Const,
13048                inputs: vec![],
13049                shape: Shape::from_dims(&[2, 3]),
13050                dtype: DType::F64,
13051            });
13052            let r = g.push(Node {
13053                op: Op::Const,
13054                inputs: vec![],
13055                shape: Shape::from_dims(&[3, 2]),
13056                dtype: DType::F64,
13057            });
13058            let mm = g.push(Node {
13059                op: Op::MatMul,
13060                inputs: vec![l, r],
13061                shape: Shape::from_dims(&[2, 2]),
13062                dtype: DType::F64,
13063            });
13064            g.set_target_backend(mm, BackendId::Cpu);
13065            (l, r, mm)
13066        };
13067        let mut inputs = StorageCache::new();
13068        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
13069        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
13070        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
13071        let guard = result_arc.read().unwrap();
13072        assert_eq!(guard.dtype, DType::F64);
13073        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13074            panic!("expected Cpu storage");
13075        };
13076        assert_eq!(
13077            c.as_slice::<f64>().unwrap(),
13078            &[58.0_f64, 64.0, 139.0, 154.0]
13079        );
13080    }
13081
13082    /// E2E: F64 unary chain — Const + Sqr + Sqrt — verifies that
13083    /// the kernel-binding lookup picks the f64 entries when the
13084    /// graph nodes carry DType::F64.
13085    #[test]
13086    fn pipelined_realize_sqr_then_sqrt_f64() {
13087        let storage = fuel_memory::from_slice_cpu(&[1.0_f64, 4.0, 9.0]);
13088        let graph = Arc::new(RwLock::new(Graph::new()));
13089        let (in_id, sqrt_id) = {
13090            let mut g = graph.write().unwrap();
13091            let in_id = g.push(Node {
13092                op: Op::Const,
13093                inputs: vec![],
13094                shape: Shape::from_dims(&[3]),
13095                dtype: DType::F64,
13096            });
13097            let sqr_id = g.push(Node {
13098                op: Op::Sqr,
13099                inputs: vec![in_id],
13100                shape: Shape::from_dims(&[3]),
13101                dtype: DType::F64,
13102            });
13103            let sqrt_id = g.push(Node {
13104                op: Op::Sqrt,
13105                inputs: vec![sqr_id],
13106                shape: Shape::from_dims(&[3]),
13107                dtype: DType::F64,
13108            });
13109            g.set_target_backend(sqr_id, BackendId::Cpu);
13110            g.set_target_backend(sqrt_id, BackendId::Cpu);
13111            (in_id, sqrt_id)
13112        };
13113        let mut inputs = StorageCache::new();
13114        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
13115        let (result_arc, _) = PipelinedExecutor::realize(graph, sqrt_id, inputs).expect("realize");
13116        let guard = result_arc.read().unwrap();
13117        assert_eq!(guard.dtype, DType::F64);
13118        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13119            panic!("expected Cpu storage");
13120        };
13121        assert_eq!(c.as_slice::<f64>().unwrap(), &[1.0_f64, 4.0, 9.0]);
13122    }
13123
13124    /// E2E: ArgMaxDim — produces U32 output indices.
13125    #[test]
13126    fn pipelined_realize_argmax_dim() {
13127        // input [2, 3] = [[1, 5, 2], [9, 0, 4]]
13128        // argmax dim=1 → [1, 0]
13129        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 2.0, 9.0, 0.0, 4.0]);
13130        let graph = Arc::new(RwLock::new(Graph::new()));
13131        let (in_id, op_id) = {
13132            let mut g = graph.write().unwrap();
13133            let in_id = g.push(Node {
13134                op: Op::Const,
13135                inputs: vec![],
13136                shape: Shape::from_dims(&[2, 3]),
13137                dtype: DType::F32,
13138            });
13139            let op_id = g.push(Node {
13140                op: Op::ArgMaxDim(1),
13141                inputs: vec![in_id],
13142                shape: Shape::from_dims(&[2]),
13143                dtype: DType::U32,
13144            });
13145            g.set_target_backend(op_id, BackendId::Cpu);
13146            (in_id, op_id)
13147        };
13148        let mut inputs = StorageCache::new();
13149        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
13150        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13151        let guard = result_arc.read().unwrap();
13152        assert_eq!(guard.dtype, DType::U32);
13153        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13154            panic!("expected Cpu storage");
13155        };
13156        assert_eq!(c.as_slice::<u32>().unwrap(), &[1u32, 0]);
13157    }
13158
13159    /// E2E: IndexAdd along outer dim — accumulate updates into a
13160    /// rank-1 base tensor at indexed positions.
13161    #[test]
13162    fn pipelined_realize_index_add_simple() {
13163        let base = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
13164        let indices = fuel_memory::from_slice_cpu(&[0u32, 0]);
13165        let src = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
13166        let graph = Arc::new(RwLock::new(Graph::new()));
13167        let (b_id, i_id, s_id, op_id) = {
13168            let mut g = graph.write().unwrap();
13169            let b = g.push(Node {
13170                op: Op::Const,
13171                inputs: vec![],
13172                shape: Shape::from_dims(&[3]),
13173                dtype: DType::F32,
13174            });
13175            let i = g.push(Node {
13176                op: Op::Const,
13177                inputs: vec![],
13178                shape: Shape::from_dims(&[2]),
13179                dtype: DType::U32,
13180            });
13181            let s = g.push(Node {
13182                op: Op::Const,
13183                inputs: vec![],
13184                shape: Shape::from_dims(&[2]),
13185                dtype: DType::F32,
13186            });
13187            let op = g.push(Node {
13188                op: Op::IndexAdd { dim: 0 },
13189                inputs: vec![b, i, s],
13190                shape: Shape::from_dims(&[3]),
13191                dtype: DType::F32,
13192            });
13193            g.set_target_backend(op, BackendId::Cpu);
13194            (b, i, s, op)
13195        };
13196        let mut inputs = StorageCache::new();
13197        inputs.insert(b_id, Arc::new(RwLock::new(base)));
13198        inputs.insert(i_id, Arc::new(RwLock::new(indices)));
13199        inputs.insert(s_id, Arc::new(RwLock::new(src)));
13200        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13201        let guard = result_arc.read().unwrap();
13202        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13203            panic!("expected Cpu storage");
13204        };
13205        // 10 + 1 + 2 = 13; 20 untouched; 30 untouched.
13206        assert_eq!(c.as_slice::<f32>().unwrap(), &[13.0, 20.0, 30.0]);
13207    }
13208
13209    /// E2E: ScatterAdd along outer dim — same-rank indices, base
13210    /// starts as zeros, src adds values at scatter positions.
13211    #[test]
13212    fn pipelined_realize_scatter_add_outer_dim() {
13213        // base [3, 2] = zeros; indices [2, 2] = [[0, 1], [2, 0]];
13214        // src [2, 2] = [[1, 2], [3, 4]]; dim=0
13215        // → out = [[1, 4], [0, 2], [3, 0]]
13216        let base = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
13217        let indices = fuel_memory::from_slice_cpu(&[0u32, 1, 2, 0]);
13218        let src = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
13219        let graph = Arc::new(RwLock::new(Graph::new()));
13220        let (b_id, i_id, s_id, op_id) = {
13221            let mut g = graph.write().unwrap();
13222            let b = g.push(Node {
13223                op: Op::Const,
13224                inputs: vec![],
13225                shape: Shape::from_dims(&[3, 2]),
13226                dtype: DType::F32,
13227            });
13228            let i = g.push(Node {
13229                op: Op::Const,
13230                inputs: vec![],
13231                shape: Shape::from_dims(&[2, 2]),
13232                dtype: DType::U32,
13233            });
13234            let s = g.push(Node {
13235                op: Op::Const,
13236                inputs: vec![],
13237                shape: Shape::from_dims(&[2, 2]),
13238                dtype: DType::F32,
13239            });
13240            let op = g.push(Node {
13241                op: Op::ScatterAdd { dim: 0 },
13242                inputs: vec![b, i, s],
13243                shape: Shape::from_dims(&[3, 2]),
13244                dtype: DType::F32,
13245            });
13246            g.set_target_backend(op, BackendId::Cpu);
13247            (b, i, s, op)
13248        };
13249        let mut inputs = StorageCache::new();
13250        inputs.insert(b_id, Arc::new(RwLock::new(base)));
13251        inputs.insert(i_id, Arc::new(RwLock::new(indices)));
13252        inputs.insert(s_id, Arc::new(RwLock::new(src)));
13253        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13254        let guard = result_arc.read().unwrap();
13255        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13256            panic!("expected Cpu storage");
13257        };
13258        assert_eq!(
13259            c.as_slice::<f32>().unwrap(),
13260            &[1.0, 4.0, 0.0, 2.0, 3.0, 0.0]
13261        );
13262    }
13263
13264    /// E2E: Rope through the pipelined executor. cos=0, sin=1
13265    /// rotates the head_dim halves with sign per the rotate_half
13266    /// convention.
13267    #[test]
13268    fn pipelined_realize_rope_pi_over_two() {
13269        // x [1, 1, 4] = [1, 2, 3, 4]. cos=[0,0,0,0], sin=[1,1,1,1].
13270        // Expected: [-3, -4, 1, 2].
13271        let x = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
13272        let cos = fuel_memory::from_slice_cpu(&[0.0_f32, 0.0, 0.0, 0.0]);
13273        let sin = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
13274        let graph = Arc::new(RwLock::new(Graph::new()));
13275        let (x_id, cos_id, sin_id, r_id) = {
13276            let mut g = graph.write().unwrap();
13277            let x = g.push(Node {
13278                op: Op::Const,
13279                inputs: vec![],
13280                shape: Shape::from_dims(&[1, 1, 4]),
13281                dtype: DType::F32,
13282            });
13283            let c = g.push(Node {
13284                op: Op::Const,
13285                inputs: vec![],
13286                shape: Shape::from_dims(&[1, 4]),
13287                dtype: DType::F32,
13288            });
13289            let s = g.push(Node {
13290                op: Op::Const,
13291                inputs: vec![],
13292                shape: Shape::from_dims(&[1, 4]),
13293                dtype: DType::F32,
13294            });
13295            let r = g.push(Node {
13296                op: Op::Fused(
13297                    fuel_graph::registry::FusedOps::ROPE,
13298                    fuel_graph::registry::FusedOpParams::Rope,
13299                ),
13300                inputs: vec![x, c, s],
13301                shape: Shape::from_dims(&[1, 1, 4]),
13302                dtype: DType::F32,
13303            });
13304            g.set_target_backend(r, BackendId::Cpu);
13305            (x, c, s, r)
13306        };
13307        let mut inputs = StorageCache::new();
13308        inputs.insert(x_id, Arc::new(RwLock::new(x)));
13309        inputs.insert(cos_id, Arc::new(RwLock::new(cos)));
13310        inputs.insert(sin_id, Arc::new(RwLock::new(sin)));
13311        let (result_arc, _) = PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
13312        let guard = result_arc.read().unwrap();
13313        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13314            panic!("expected Cpu storage");
13315        };
13316        assert_eq!(c.as_slice::<f32>().unwrap(), &[-3.0, -4.0, 1.0, 2.0]);
13317    }
13318
13319    /// E2E: Gather along inner dim. Source [2, 4]; indices [2, 3];
13320    /// output [2, 3] = picks from each row by per-row indices.
13321    #[test]
13322    fn pipelined_realize_gather_inner_dim() {
13323        let source =
13324            fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0]);
13325        let indices = fuel_memory::from_slice_cpu(&[0u32, 2, 1, 3, 0, 0]);
13326        let graph = Arc::new(RwLock::new(Graph::new()));
13327        let (src_id, idx_id, g_id) = {
13328            let mut g = graph.write().unwrap();
13329            let s = g.push(Node {
13330                op: Op::Const,
13331                inputs: vec![],
13332                shape: Shape::from_dims(&[2, 4]),
13333                dtype: DType::F32,
13334            });
13335            let i = g.push(Node {
13336                op: Op::Const,
13337                inputs: vec![],
13338                shape: Shape::from_dims(&[2, 3]),
13339                dtype: DType::U32,
13340            });
13341            let g_id = g.push(Node {
13342                op: Op::Gather { dim: 1 },
13343                inputs: vec![s, i],
13344                shape: Shape::from_dims(&[2, 3]),
13345                dtype: DType::F32,
13346            });
13347            g.set_target_backend(g_id, BackendId::Cpu);
13348            (s, i, g_id)
13349        };
13350        let mut inputs = StorageCache::new();
13351        inputs.insert(src_id, Arc::new(RwLock::new(source)));
13352        inputs.insert(idx_id, Arc::new(RwLock::new(indices)));
13353        let (result_arc, _) = PipelinedExecutor::realize(graph, g_id, inputs).expect("realize");
13354        let guard = result_arc.read().unwrap();
13355        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13356            panic!("expected Cpu storage");
13357        };
13358        assert_eq!(
13359            c.as_slice::<f32>().unwrap(),
13360            &[10.0, 30.0, 20.0, 80.0, 50.0, 50.0]
13361        );
13362    }
13363
13364    /// E2E: IndexSelect — embedding-table lookup. Source is a
13365    /// `[vocab=4, d_model=3]` table; indices are token IDs;
13366    /// output is `[seq=3, d_model=3]` with the picked rows.
13367    #[test]
13368    fn pipelined_realize_index_select_embedding_lookup() {
13369        let table = fuel_memory::from_slice_cpu(&[
13370            10.0_f32, 11.0, 12.0, // row 0
13371            20.0, 21.0, 22.0, // row 1
13372            30.0, 31.0, 32.0, // row 2
13373            40.0, 41.0, 42.0, // row 3
13374        ]);
13375        let indices = fuel_memory::from_slice_cpu(&[2u32, 0, 2]);
13376        let graph = Arc::new(RwLock::new(Graph::new()));
13377        let (table_id, idx_id, sel_id) = {
13378            let mut g = graph.write().unwrap();
13379            let t = g.push(Node {
13380                op: Op::Const,
13381                inputs: vec![],
13382                shape: Shape::from_dims(&[4, 3]),
13383                dtype: DType::F32,
13384            });
13385            let i = g.push(Node {
13386                op: Op::Const,
13387                inputs: vec![],
13388                shape: Shape::from_dims(&[3]),
13389                dtype: DType::U32,
13390            });
13391            let s = g.push(Node {
13392                op: Op::IndexSelect { dim: 0 },
13393                inputs: vec![t, i],
13394                shape: Shape::from_dims(&[3, 3]),
13395                dtype: DType::F32,
13396            });
13397            g.set_target_backend(s, BackendId::Cpu);
13398            (t, i, s)
13399        };
13400        let mut inputs = StorageCache::new();
13401        inputs.insert(table_id, Arc::new(RwLock::new(table)));
13402        inputs.insert(idx_id, Arc::new(RwLock::new(indices)));
13403        let (result_arc, result_layout) =
13404            PipelinedExecutor::realize(graph, sel_id, inputs).expect("realize");
13405        assert_eq!(result_layout.shape().dims(), &[3, 3]);
13406        let guard = result_arc.read().unwrap();
13407        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13408            panic!("expected Cpu storage");
13409        };
13410        assert_eq!(
13411            c.as_slice::<f32>().unwrap(),
13412            &[30.0, 31.0, 32.0, 10.0, 11.0, 12.0, 30.0, 31.0, 32.0]
13413        );
13414    }
13415
13416    /// E2E: RmsNormLastDim on a 2-row input. Each row's output
13417    /// has unit RMS up to the eps-induced bias.
13418    #[test]
13419    fn pipelined_realize_rms_norm_last_dim() {
13420        let storage = fuel_memory::from_slice_cpu(&[
13421            3.0_f32, 4.0, // row 0: rms = sqrt(12.5)
13422            6.0, 8.0, // row 1: rms = sqrt(50.0) = 5*sqrt(2)
13423        ]);
13424        let graph = Arc::new(RwLock::new(Graph::new()));
13425        let (in_id, op_id) = {
13426            let mut g = graph.write().unwrap();
13427            let in_id = g.push(Node {
13428                op: Op::Const,
13429                inputs: vec![],
13430                shape: Shape::from_dims(&[2, 2]),
13431                dtype: DType::F32,
13432            });
13433            let op_id = g.push(Node {
13434                op: Op::Fused(
13435                    fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM,
13436                    fuel_graph::registry::FusedOpParams::RmsNormLastDim { eps: 0.0 },
13437                ),
13438                inputs: vec![in_id],
13439                shape: Shape::from_dims(&[2, 2]),
13440                dtype: DType::F32,
13441            });
13442            g.set_target_backend(op_id, BackendId::Cpu);
13443            (in_id, op_id)
13444        };
13445        let mut inputs = StorageCache::new();
13446        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
13447        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13448        let guard = result_arc.read().unwrap();
13449        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13450            panic!("expected Cpu storage");
13451        };
13452        let result: &[f32] = c.as_slice().unwrap();
13453        // Row 0: rms = sqrt(12.5). Output = [3, 4] / sqrt(12.5).
13454        let rms0 = (12.5_f32).sqrt();
13455        assert!((result[0] - 3.0 / rms0).abs() < 1e-6);
13456        assert!((result[1] - 4.0 / rms0).abs() < 1e-6);
13457        // Row 1: rms = sqrt(50). Output = [6, 8] / sqrt(50).
13458        let rms1 = (50.0_f32).sqrt();
13459        assert!((result[2] - 6.0 / rms1).abs() < 1e-6);
13460        assert!((result[3] - 8.0 / rms1).abs() < 1e-6);
13461    }
13462
13463    /// E2E: LayerNormLastDim — each row's output has zero mean and
13464    /// unit variance.
13465    #[test]
13466    fn pipelined_realize_layer_norm_last_dim() {
13467        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 10.0, 20.0, 30.0]);
13468        let graph = Arc::new(RwLock::new(Graph::new()));
13469        let (in_id, op_id) = {
13470            let mut g = graph.write().unwrap();
13471            let in_id = g.push(Node {
13472                op: Op::Const,
13473                inputs: vec![],
13474                shape: Shape::from_dims(&[2, 3]),
13475                dtype: DType::F32,
13476            });
13477            let op_id = g.push(Node {
13478                op: Op::Fused(
13479                    fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM,
13480                    fuel_graph::registry::FusedOpParams::LayerNormLastDim { eps: 0.0 },
13481                ),
13482                inputs: vec![in_id],
13483                shape: Shape::from_dims(&[2, 3]),
13484                dtype: DType::F32,
13485            });
13486            g.set_target_backend(op_id, BackendId::Cpu);
13487            (in_id, op_id)
13488        };
13489        let mut inputs = StorageCache::new();
13490        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
13491        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13492        let guard = result_arc.read().unwrap();
13493        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13494            panic!("expected Cpu storage");
13495        };
13496        let result: &[f32] = c.as_slice().unwrap();
13497        // Each row should have mean ~0 and var ~1.
13498        for row in 0..2 {
13499            let off = row * 3;
13500            let sum: f32 = result[off..off + 3].iter().sum();
13501            let mean = sum / 3.0;
13502            assert!(mean.abs() < 1e-6, "row {row} mean should be 0, got {mean}");
13503            let var: f32 = result[off..off + 3]
13504                .iter()
13505                .map(|v| (v - mean).powi(2))
13506                .sum::<f32>()
13507                / 3.0;
13508            assert!(
13509                (var - 1.0).abs() < 1e-6,
13510                "row {row} var should be 1, got {var}"
13511            );
13512        }
13513    }
13514
13515    /// E2E: SoftmaxLastDim on a 2-row input. Each row should sum
13516    /// to 1; uniform row gives uniform output.
13517    #[test]
13518    fn pipelined_realize_softmax_last_dim() {
13519        // Row 0: [1, 1, 1, 1] → uniform 0.25 each
13520        // Row 1: [0, 0, 0, 100] → effectively a one-hot at position 3
13521        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 100.0]);
13522        let graph = Arc::new(RwLock::new(Graph::new()));
13523        let (in_id, op_id) = {
13524            let mut g = graph.write().unwrap();
13525            let in_id = g.push(Node {
13526                op: Op::Const,
13527                inputs: vec![],
13528                shape: Shape::from_dims(&[2, 4]),
13529                dtype: DType::F32,
13530            });
13531            let op_id = g.push(Node {
13532                op: Op::Fused(
13533                    fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM,
13534                    fuel_graph::registry::FusedOpParams::SoftmaxLastDim,
13535                ),
13536                inputs: vec![in_id],
13537                shape: Shape::from_dims(&[2, 4]),
13538                dtype: DType::F32,
13539            });
13540            g.set_target_backend(op_id, BackendId::Cpu);
13541            (in_id, op_id)
13542        };
13543        let mut inputs = StorageCache::new();
13544        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
13545        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13546        let guard = result_arc.read().unwrap();
13547        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13548            panic!("expected Cpu storage");
13549        };
13550        let result: &[f32] = c.as_slice().unwrap();
13551
13552        // Row 0: uniform 0.25
13553        for v in &result[..4] {
13554            assert!((v - 0.25).abs() < 1e-7);
13555        }
13556        // Row 1: positions 0..3 ≈ 0, position 4 (= last column) ≈ 1
13557        // (e^100 dominates).
13558        for v in &result[4..7] {
13559            assert!(
13560                *v < 1e-30,
13561                "row-1 leading positions should be near 0, got {v}"
13562            );
13563        }
13564        assert!(
13565            result[7] > 0.999,
13566            "row-1 last position should dominate, got {}",
13567            result[7]
13568        );
13569        // Each row sums to 1.
13570        let row0_sum: f32 = result[..4].iter().sum();
13571        let row1_sum: f32 = result[4..].iter().sum();
13572        assert!((row0_sum - 1.0).abs() < 1e-6);
13573        assert!((row1_sum - 1.0).abs() < 1e-6);
13574    }
13575
13576    /// E2E: Concat along inner dim — two [2, 3] tensors → [2, 6].
13577    #[test]
13578    fn pipelined_realize_concat_inner_dim() {
13579        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
13580        let b = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0, 9.0, 10.0, 11.0, 12.0]);
13581        let graph = Arc::new(RwLock::new(Graph::new()));
13582        let (a_id, b_id, c_id) = {
13583            let mut g = graph.write().unwrap();
13584            let a = g.push(Node {
13585                op: Op::Const,
13586                inputs: vec![],
13587                shape: Shape::from_dims(&[2, 3]),
13588                dtype: DType::F32,
13589            });
13590            let b = g.push(Node {
13591                op: Op::Const,
13592                inputs: vec![],
13593                shape: Shape::from_dims(&[2, 3]),
13594                dtype: DType::F32,
13595            });
13596            let c = g.push(Node {
13597                op: Op::Concat { dim: 1 },
13598                inputs: vec![a, b],
13599                shape: Shape::from_dims(&[2, 6]),
13600                dtype: DType::F32,
13601            });
13602            g.set_target_backend(c, BackendId::Cpu);
13603            (a, b, c)
13604        };
13605        let mut inputs = StorageCache::new();
13606        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13607        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13608        let (result_arc, result_layout) =
13609            PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
13610        assert_eq!(result_layout.shape().dims(), &[2, 6]);
13611        let guard = result_arc.read().unwrap();
13612        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13613            panic!("expected Cpu storage");
13614        };
13615        assert_eq!(
13616            c.as_slice::<f32>().unwrap(),
13617            &[
13618                1.0, 2.0, 3.0, 7.0, 8.0, 9.0, 4.0, 5.0, 6.0, 10.0, 11.0, 12.0
13619            ]
13620        );
13621    }
13622
13623    /// E2E: Concat with three inputs along outer dim — verifies
13624    /// variable-arity input handling through the executor.
13625    #[test]
13626    fn pipelined_realize_concat_three_inputs_outer() {
13627        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
13628        let b = fuel_memory::from_slice_cpu(&[3.0_f32, 4.0]);
13629        let c = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0]);
13630        let graph = Arc::new(RwLock::new(Graph::new()));
13631        let (a_id, b_id, c_id, cat_id) = {
13632            let mut g = graph.write().unwrap();
13633            let a = g.push(Node {
13634                op: Op::Const,
13635                inputs: vec![],
13636                shape: Shape::from_dims(&[2]),
13637                dtype: DType::F32,
13638            });
13639            let b = g.push(Node {
13640                op: Op::Const,
13641                inputs: vec![],
13642                shape: Shape::from_dims(&[2]),
13643                dtype: DType::F32,
13644            });
13645            let c = g.push(Node {
13646                op: Op::Const,
13647                inputs: vec![],
13648                shape: Shape::from_dims(&[2]),
13649                dtype: DType::F32,
13650            });
13651            let cat = g.push(Node {
13652                op: Op::Concat { dim: 0 },
13653                inputs: vec![a, b, c],
13654                shape: Shape::from_dims(&[6]),
13655                dtype: DType::F32,
13656            });
13657            g.set_target_backend(cat, BackendId::Cpu);
13658            (a, b, c, cat)
13659        };
13660        let mut inputs = StorageCache::new();
13661        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13662        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13663        inputs.insert(c_id, Arc::new(RwLock::new(c)));
13664        let (result_arc, _) = PipelinedExecutor::realize(graph, cat_id, inputs).expect("realize");
13665        let guard = result_arc.read().unwrap();
13666        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13667            panic!("expected Cpu storage");
13668        };
13669        assert_eq!(
13670            c.as_slice::<f32>().unwrap(),
13671            &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
13672        );
13673    }
13674
13675    /// E2E: AddScalar — graph emits Op::AddScalar; the executor
13676    /// maps it to OpKind::Affine with mul=1, add=c.
13677    #[test]
13678    fn pipelined_realize_add_scalar() {
13679        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
13680        let graph = Arc::new(RwLock::new(Graph::new()));
13681        let (in_id, op_id) = {
13682            let mut g = graph.write().unwrap();
13683            let in_id = g.push(Node {
13684                op: Op::Const,
13685                inputs: vec![],
13686                shape: Shape::from_dims(&[3]),
13687                dtype: DType::F32,
13688            });
13689            let op_id = g.push(Node {
13690                op: Op::AddScalar(10.0),
13691                inputs: vec![in_id],
13692                shape: Shape::from_dims(&[3]),
13693                dtype: DType::F32,
13694            });
13695            g.set_target_backend(op_id, BackendId::Cpu);
13696            (in_id, op_id)
13697        };
13698        let mut inputs = StorageCache::new();
13699        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
13700        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13701        let guard = result_arc.read().unwrap();
13702        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13703            panic!("expected Cpu storage");
13704        };
13705        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 12.0, 13.0]);
13706    }
13707
13708    /// E2E: Clamp — clamp values to [-2, 2].
13709    #[test]
13710    fn pipelined_realize_clamp() {
13711        let storage = fuel_memory::from_slice_cpu(&[-5.0_f32, 0.5, 100.0]);
13712        let graph = Arc::new(RwLock::new(Graph::new()));
13713        let (in_id, op_id) = {
13714            let mut g = graph.write().unwrap();
13715            let in_id = g.push(Node {
13716                op: Op::Const,
13717                inputs: vec![],
13718                shape: Shape::from_dims(&[3]),
13719                dtype: DType::F32,
13720            });
13721            let op_id = g.push(Node {
13722                op: Op::Clamp {
13723                    min: -2.0,
13724                    max: 2.0,
13725                },
13726                inputs: vec![in_id],
13727                shape: Shape::from_dims(&[3]),
13728                dtype: DType::F32,
13729            });
13730            g.set_target_backend(op_id, BackendId::Cpu);
13731            (in_id, op_id)
13732        };
13733        let mut inputs = StorageCache::new();
13734        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
13735        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13736        let guard = result_arc.read().unwrap();
13737        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13738            panic!("expected Cpu storage");
13739        };
13740        assert_eq!(c.as_slice::<f32>().unwrap(), &[-2.0, 0.5, 2.0]);
13741    }
13742
13743    /// E2E: Maximum — elementwise tensor max.
13744    #[test]
13745    fn pipelined_realize_maximum_elementwise() {
13746        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, -3.0]);
13747        let rhs_storage = fuel_memory::from_slice_cpu(&[2.0_f32, 1.0, -1.0]);
13748        let graph = Arc::new(RwLock::new(Graph::new()));
13749        let (lhs_id, rhs_id, op_id) = {
13750            let mut g = graph.write().unwrap();
13751            let lhs = g.push(Node {
13752                op: Op::Const,
13753                inputs: vec![],
13754                shape: Shape::from_dims(&[3]),
13755                dtype: DType::F32,
13756            });
13757            let rhs = g.push(Node {
13758                op: Op::Const,
13759                inputs: vec![],
13760                shape: Shape::from_dims(&[3]),
13761                dtype: DType::F32,
13762            });
13763            let op = g.push(Node {
13764                op: Op::Maximum,
13765                inputs: vec![lhs, rhs],
13766                shape: Shape::from_dims(&[3]),
13767                dtype: DType::F32,
13768            });
13769            g.set_target_backend(op, BackendId::Cpu);
13770            (lhs, rhs, op)
13771        };
13772        let mut inputs = StorageCache::new();
13773        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
13774        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
13775        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13776        let guard = result_arc.read().unwrap();
13777        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13778            panic!("expected Cpu storage");
13779        };
13780        assert_eq!(c.as_slice::<f32>().unwrap(), &[2.0, 5.0, -1.0]);
13781    }
13782
13783    /// E2E: Const + Const + Conv2D — the 2×2 sum-kernel test from
13784    /// byte_kernels driven through the pipelined executor.
13785    #[test]
13786    fn pipelined_realize_conv2d_2x2_sum_kernel() {
13787        // x [1, 1, 3, 3]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
13788        // weight [1, 1, 2, 2]: all-ones
13789        // → out [1, 1, 2, 2]: [[12, 16], [24, 28]]
13790        let x_storage =
13791            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
13792        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
13793
13794        let graph = Arc::new(RwLock::new(Graph::new()));
13795        let (x_id, w_id, c_id) = {
13796            let mut g = graph.write().unwrap();
13797            let x = g.push(Node {
13798                op: Op::Const,
13799                inputs: vec![],
13800                shape: Shape::from_dims(&[1, 1, 3, 3]),
13801                dtype: DType::F32,
13802            });
13803            let w = g.push(Node {
13804                op: Op::Const,
13805                inputs: vec![],
13806                shape: Shape::from_dims(&[1, 1, 2, 2]),
13807                dtype: DType::F32,
13808            });
13809            let c = g.push(Node {
13810                op: Op::Fused(
13811                    fuel_graph::registry::FusedOps::CONV2D,
13812                    fuel_graph::registry::FusedOpParams::Conv2D {
13813                        stride: (1, 1),
13814                        padding: (0, 0),
13815                        groups: 1,
13816                    },
13817                ),
13818                inputs: vec![x, w],
13819                shape: Shape::from_dims(&[1, 1, 2, 2]),
13820                dtype: DType::F32,
13821            });
13822            g.set_target_backend(c, BackendId::Cpu);
13823            (x, w, c)
13824        };
13825        let mut inputs = StorageCache::new();
13826        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
13827        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
13828
13829        let (result_arc, result_layout) =
13830            PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
13831        assert_eq!(result_layout.shape().dims(), &[1, 1, 2, 2]);
13832
13833        let guard = result_arc.read().unwrap();
13834        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13835            panic!("expected Cpu storage");
13836        };
13837        assert_eq!(c.as_slice::<f32>().unwrap(), &[12.0, 16.0, 24.0, 28.0]);
13838    }
13839
13840    /// E2E: Conv2D with bias (3 inputs).
13841    #[test]
13842    fn pipelined_realize_conv2d_with_bias() {
13843        let x_storage =
13844            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
13845        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
13846        let bias_storage = fuel_memory::from_slice_cpu(&[100.0_f32]);
13847
13848        let graph = Arc::new(RwLock::new(Graph::new()));
13849        let (x_id, w_id, b_id, c_id) = {
13850            let mut g = graph.write().unwrap();
13851            let x = g.push(Node {
13852                op: Op::Const,
13853                inputs: vec![],
13854                shape: Shape::from_dims(&[1, 1, 3, 3]),
13855                dtype: DType::F32,
13856            });
13857            let w = g.push(Node {
13858                op: Op::Const,
13859                inputs: vec![],
13860                shape: Shape::from_dims(&[1, 1, 2, 2]),
13861                dtype: DType::F32,
13862            });
13863            let b = g.push(Node {
13864                op: Op::Const,
13865                inputs: vec![],
13866                shape: Shape::from_dims(&[1]),
13867                dtype: DType::F32,
13868            });
13869            let c = g.push(Node {
13870                op: Op::Fused(
13871                    fuel_graph::registry::FusedOps::CONV2D,
13872                    fuel_graph::registry::FusedOpParams::Conv2D {
13873                        stride: (1, 1),
13874                        padding: (0, 0),
13875                        groups: 1,
13876                    },
13877                ),
13878                inputs: vec![x, w, b],
13879                shape: Shape::from_dims(&[1, 1, 2, 2]),
13880                dtype: DType::F32,
13881            });
13882            g.set_target_backend(c, BackendId::Cpu);
13883            (x, w, b, c)
13884        };
13885        let mut inputs = StorageCache::new();
13886        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
13887        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
13888        inputs.insert(b_id, Arc::new(RwLock::new(bias_storage)));
13889
13890        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
13891        let guard = result_arc.read().unwrap();
13892        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13893            panic!("expected Cpu storage");
13894        };
13895        assert_eq!(c.as_slice::<f32>().unwrap(), &[112.0, 116.0, 124.0, 128.0]);
13896    }
13897
13898    /// E2E: Conv2D in F64 — same 2x2 sum-kernel test as F32, on doubles.
13899    #[test]
13900    fn pipelined_realize_conv2d_f64() {
13901        let x_storage =
13902            fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
13903        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f64, 1.0, 1.0, 1.0]);
13904
13905        let graph = Arc::new(RwLock::new(Graph::new()));
13906        let (x_id, w_id, c_id) = {
13907            let mut g = graph.write().unwrap();
13908            let x = g.push(Node {
13909                op: Op::Const,
13910                inputs: vec![],
13911                shape: Shape::from_dims(&[1, 1, 3, 3]),
13912                dtype: DType::F64,
13913            });
13914            let w = g.push(Node {
13915                op: Op::Const,
13916                inputs: vec![],
13917                shape: Shape::from_dims(&[1, 1, 2, 2]),
13918                dtype: DType::F64,
13919            });
13920            let c = g.push(Node {
13921                op: Op::Fused(
13922                    fuel_graph::registry::FusedOps::CONV2D,
13923                    fuel_graph::registry::FusedOpParams::Conv2D {
13924                        stride: (1, 1),
13925                        padding: (0, 0),
13926                        groups: 1,
13927                    },
13928                ),
13929                inputs: vec![x, w],
13930                shape: Shape::from_dims(&[1, 1, 2, 2]),
13931                dtype: DType::F64,
13932            });
13933            g.set_target_backend(c, BackendId::Cpu);
13934            (x, w, c)
13935        };
13936        let mut inputs = StorageCache::new();
13937        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
13938        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
13939        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
13940        let guard = result_arc.read().unwrap();
13941        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13942            panic!("expected Cpu storage");
13943        };
13944        assert_eq!(c.as_slice::<f64>().unwrap(), &[12.0, 16.0, 24.0, 28.0]);
13945    }
13946
13947    /// E2E: Conv2D in BF16 — f32-accumulator path. Tolerant compare.
13948    #[test]
13949    fn pipelined_realize_conv2d_bf16() {
13950        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]
13951            .iter()
13952            .map(|v| half::bf16::from_f32(*v))
13953            .collect();
13954        let w_data: Vec<half::bf16> = [1.0_f32, 1.0, 1.0, 1.0]
13955            .iter()
13956            .map(|v| half::bf16::from_f32(*v))
13957            .collect();
13958        let x_storage = fuel_memory::from_slice_cpu(&x_data);
13959        let w_storage = fuel_memory::from_slice_cpu(&w_data);
13960
13961        let graph = Arc::new(RwLock::new(Graph::new()));
13962        let (x_id, w_id, c_id) = {
13963            let mut g = graph.write().unwrap();
13964            let x = g.push(Node {
13965                op: Op::Const,
13966                inputs: vec![],
13967                shape: Shape::from_dims(&[1, 1, 3, 3]),
13968                dtype: DType::BF16,
13969            });
13970            let w = g.push(Node {
13971                op: Op::Const,
13972                inputs: vec![],
13973                shape: Shape::from_dims(&[1, 1, 2, 2]),
13974                dtype: DType::BF16,
13975            });
13976            let c = g.push(Node {
13977                op: Op::Fused(
13978                    fuel_graph::registry::FusedOps::CONV2D,
13979                    fuel_graph::registry::FusedOpParams::Conv2D {
13980                        stride: (1, 1),
13981                        padding: (0, 0),
13982                        groups: 1,
13983                    },
13984                ),
13985                inputs: vec![x, w],
13986                shape: Shape::from_dims(&[1, 1, 2, 2]),
13987                dtype: DType::BF16,
13988            });
13989            g.set_target_backend(c, BackendId::Cpu);
13990            (x, w, c)
13991        };
13992        let mut inputs = StorageCache::new();
13993        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
13994        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
13995        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
13996        let guard = result_arc.read().unwrap();
13997        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13998            panic!("expected Cpu storage");
13999        };
14000        let got: Vec<f32> = c
14001            .as_slice::<half::bf16>()
14002            .unwrap()
14003            .iter()
14004            .map(|v| v.to_f32())
14005            .collect();
14006        let want = [12.0_f32, 16.0, 24.0, 28.0];
14007        for (g, w) in got.iter().zip(want.iter()) {
14008            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
14009        }
14010    }
14011
14012    /// E2E: Conv2D in F16 — f32-accumulator path. Tolerant compare.
14013    #[test]
14014    fn pipelined_realize_conv2d_f16() {
14015        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]
14016            .iter()
14017            .map(|v| half::f16::from_f32(*v))
14018            .collect();
14019        let w_data: Vec<half::f16> = [1.0_f32, 1.0, 1.0, 1.0]
14020            .iter()
14021            .map(|v| half::f16::from_f32(*v))
14022            .collect();
14023        let x_storage = fuel_memory::from_slice_cpu(&x_data);
14024        let w_storage = fuel_memory::from_slice_cpu(&w_data);
14025
14026        let graph = Arc::new(RwLock::new(Graph::new()));
14027        let (x_id, w_id, c_id) = {
14028            let mut g = graph.write().unwrap();
14029            let x = g.push(Node {
14030                op: Op::Const,
14031                inputs: vec![],
14032                shape: Shape::from_dims(&[1, 1, 3, 3]),
14033                dtype: DType::F16,
14034            });
14035            let w = g.push(Node {
14036                op: Op::Const,
14037                inputs: vec![],
14038                shape: Shape::from_dims(&[1, 1, 2, 2]),
14039                dtype: DType::F16,
14040            });
14041            let c = g.push(Node {
14042                op: Op::Fused(
14043                    fuel_graph::registry::FusedOps::CONV2D,
14044                    fuel_graph::registry::FusedOpParams::Conv2D {
14045                        stride: (1, 1),
14046                        padding: (0, 0),
14047                        groups: 1,
14048                    },
14049                ),
14050                inputs: vec![x, w],
14051                shape: Shape::from_dims(&[1, 1, 2, 2]),
14052                dtype: DType::F16,
14053            });
14054            g.set_target_backend(c, BackendId::Cpu);
14055            (x, w, c)
14056        };
14057        let mut inputs = StorageCache::new();
14058        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
14059        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
14060        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
14061        let guard = result_arc.read().unwrap();
14062        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14063            panic!("expected Cpu storage");
14064        };
14065        let got: Vec<f32> = c
14066            .as_slice::<half::f16>()
14067            .unwrap()
14068            .iter()
14069            .map(|v| v.to_f32())
14070            .collect();
14071        let want = [12.0_f32, 16.0, 24.0, 28.0];
14072        for (g, w) in got.iter().zip(want.iter()) {
14073            assert!((g - w).abs() < 0.05, "got {got:?} want {want:?}");
14074        }
14075    }
14076
14077    /// E2E: Op::PagedAttn — F32, single-head, B=1, Sq=1.
14078    /// Same setup as the FlashAttn smoke test, but the K/V live in a
14079    /// paged cache that we look up via block_table.
14080    /// Layout:
14081    ///   block_size=2, num_blocks=1, max_blocks_per_seq=1.
14082    ///   k_cache shape [1, 2, 1, 2] = num_blocks × block_size × Hkv × D.
14083    ///   k_cache[block 0, slot 0, h 0] = [1, 0]
14084    ///   k_cache[block 0, slot 1, h 0] = [0, 1]
14085    ///   v_cache values: [10, 0] / [0, 10]
14086    ///   block_table[b=0, logical_block 0] = 0 (physical)
14087    ///   context_lens[0] = 2
14088    ///   q[0, 0, 0] = [2, 0]
14089    /// Causal is implicit (q_pos = ctx_len - Sq + sq = 2 - 1 + 0 = 1, both keys admissible).
14090    /// Same softmax math as FlashAttn → ~[8.808, 1.192].
14091    #[test]
14092    fn pipelined_realize_paged_attn_f32() {
14093        let q = fuel_memory::from_slice_cpu(&[2.0_f32, 0.0]);
14094        let k_cache = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
14095        let v_cache = fuel_memory::from_slice_cpu(&[10.0_f32, 0.0, 0.0, 10.0]);
14096        let block_table_u32 = fuel_memory::Storage::new(
14097            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
14098                0_u32,
14099            ])),
14100            DType::U32,
14101        );
14102        let context_lens_u32 = fuel_memory::Storage::new(
14103            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
14104                2_u32,
14105            ])),
14106            DType::U32,
14107        );
14108        let graph = Arc::new(RwLock::new(Graph::new()));
14109        let (q_id, kc_id, vc_id, bt_id, cl_id, op_id) = {
14110            let mut g = graph.write().unwrap();
14111            let q = g.push(Node {
14112                op: Op::Const,
14113                inputs: vec![],
14114                shape: Shape::from_dims(&[1, 1, 1, 2]),
14115                dtype: DType::F32,
14116            });
14117            let kc = g.push(Node {
14118                op: Op::Const,
14119                inputs: vec![],
14120                shape: Shape::from_dims(&[1, 2, 1, 2]),
14121                dtype: DType::F32,
14122            });
14123            let vc = g.push(Node {
14124                op: Op::Const,
14125                inputs: vec![],
14126                shape: Shape::from_dims(&[1, 2, 1, 2]),
14127                dtype: DType::F32,
14128            });
14129            let bt = g.push(Node {
14130                op: Op::Const,
14131                inputs: vec![],
14132                shape: Shape::from_dims(&[1, 1]),
14133                dtype: DType::U32,
14134            });
14135            let cl = g.push(Node {
14136                op: Op::Const,
14137                inputs: vec![],
14138                shape: Shape::from_dims(&[1]),
14139                dtype: DType::U32,
14140            });
14141            let op = g.push(Node {
14142                op: Op::Fused(
14143                    fuel_graph::registry::FusedOps::PAGED_ATTN,
14144                    fuel_graph::registry::FusedOpParams::PagedAttn {
14145                        softmax_scale: 1.0,
14146                        block_size: 2,
14147                        softcap: None,
14148                    },
14149                ),
14150                inputs: vec![q, kc, vc, bt, cl],
14151                shape: Shape::from_dims(&[1, 1, 1, 2]),
14152                dtype: DType::F32,
14153            });
14154            g.set_target_backend(op, BackendId::Cpu);
14155            (q, kc, vc, bt, cl, op)
14156        };
14157        let mut inputs = StorageCache::new();
14158        inputs.insert(q_id, Arc::new(RwLock::new(q)));
14159        inputs.insert(kc_id, Arc::new(RwLock::new(k_cache)));
14160        inputs.insert(vc_id, Arc::new(RwLock::new(v_cache)));
14161        inputs.insert(bt_id, Arc::new(RwLock::new(block_table_u32)));
14162        inputs.insert(cl_id, Arc::new(RwLock::new(context_lens_u32)));
14163        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14164        let guard = result_arc.read().unwrap();
14165        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14166            panic!("expected Cpu storage");
14167        };
14168        let r = c.as_slice::<f32>().unwrap();
14169        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
14170        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
14171        assert!(
14172            (r[0] - 10.0 * expected_p0).abs() < 1e-5,
14173            "row[0]: got {} expected {}",
14174            r[0],
14175            10.0 * expected_p0
14176        );
14177        assert!(
14178            (r[1] - 10.0 * expected_p1).abs() < 1e-5,
14179            "row[1]: got {} expected {}",
14180            r[1],
14181            10.0 * expected_p1
14182        );
14183    }
14184
14185    /// E2E: PagedAttn BF16 — same single-row test, tolerant.
14186    #[test]
14187    fn pipelined_realize_paged_attn_bf16() {
14188        let q_v: Vec<half::bf16> = [2.0_f32, 0.0]
14189            .iter()
14190            .map(|x| half::bf16::from_f32(*x))
14191            .collect();
14192        let kc_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0]
14193            .iter()
14194            .map(|x| half::bf16::from_f32(*x))
14195            .collect();
14196        let vc_v: Vec<half::bf16> = [10.0_f32, 0.0, 0.0, 10.0]
14197            .iter()
14198            .map(|x| half::bf16::from_f32(*x))
14199            .collect();
14200        let q = fuel_memory::from_slice_cpu(&q_v);
14201        let k_cache = fuel_memory::from_slice_cpu(&kc_v);
14202        let v_cache = fuel_memory::from_slice_cpu(&vc_v);
14203        let bt = fuel_memory::Storage::new(
14204            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
14205                0_u32,
14206            ])),
14207            DType::U32,
14208        );
14209        let cl = fuel_memory::Storage::new(
14210            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
14211                2_u32,
14212            ])),
14213            DType::U32,
14214        );
14215        let graph = Arc::new(RwLock::new(Graph::new()));
14216        let (q_id, kc_id, vc_id, bt_id, cl_id, op_id) = {
14217            let mut g = graph.write().unwrap();
14218            let q = g.push(Node {
14219                op: Op::Const,
14220                inputs: vec![],
14221                shape: Shape::from_dims(&[1, 1, 1, 2]),
14222                dtype: DType::BF16,
14223            });
14224            let kc = g.push(Node {
14225                op: Op::Const,
14226                inputs: vec![],
14227                shape: Shape::from_dims(&[1, 2, 1, 2]),
14228                dtype: DType::BF16,
14229            });
14230            let vc = g.push(Node {
14231                op: Op::Const,
14232                inputs: vec![],
14233                shape: Shape::from_dims(&[1, 2, 1, 2]),
14234                dtype: DType::BF16,
14235            });
14236            let bt = g.push(Node {
14237                op: Op::Const,
14238                inputs: vec![],
14239                shape: Shape::from_dims(&[1, 1]),
14240                dtype: DType::U32,
14241            });
14242            let cl = g.push(Node {
14243                op: Op::Const,
14244                inputs: vec![],
14245                shape: Shape::from_dims(&[1]),
14246                dtype: DType::U32,
14247            });
14248            let op = g.push(Node {
14249                op: Op::Fused(
14250                    fuel_graph::registry::FusedOps::PAGED_ATTN,
14251                    fuel_graph::registry::FusedOpParams::PagedAttn {
14252                        softmax_scale: 1.0,
14253                        block_size: 2,
14254                        softcap: None,
14255                    },
14256                ),
14257                inputs: vec![q, kc, vc, bt, cl],
14258                shape: Shape::from_dims(&[1, 1, 1, 2]),
14259                dtype: DType::BF16,
14260            });
14261            g.set_target_backend(op, BackendId::Cpu);
14262            (q, kc, vc, bt, cl, op)
14263        };
14264        let mut inputs = StorageCache::new();
14265        inputs.insert(q_id, Arc::new(RwLock::new(q)));
14266        inputs.insert(kc_id, Arc::new(RwLock::new(k_cache)));
14267        inputs.insert(vc_id, Arc::new(RwLock::new(v_cache)));
14268        inputs.insert(bt_id, Arc::new(RwLock::new(bt)));
14269        inputs.insert(cl_id, Arc::new(RwLock::new(cl)));
14270        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14271        let guard = result_arc.read().unwrap();
14272        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14273            panic!("expected Cpu storage");
14274        };
14275        let got: Vec<f32> = c
14276            .as_slice::<half::bf16>()
14277            .unwrap()
14278            .iter()
14279            .map(|v| v.to_f32())
14280            .collect();
14281        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
14282        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
14283        let want = [10.0 * expected_p0, 10.0 * expected_p1];
14284        for (g, w) in got.iter().zip(want.iter()) {
14285            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
14286        }
14287    }
14288
14289    /// E2E: Op::FlashAttn — F32 single-head, single-batch, no mask.
14290    /// q = [[2.0, 0.0]], k = [[1.0, 0.0], [0.0, 1.0]], v = [[10, 0], [0, 10]]
14291    /// scale = 1.0
14292    /// scores = q · kᵀ = [2.0, 0.0]
14293    /// softmax = [e^2/(e^2+1), 1/(e^2+1)] ≈ [0.8808, 0.1192]
14294    /// out = softmax @ v = [10*0.8808, 10*0.1192] ≈ [8.808, 1.192]
14295    #[test]
14296    fn pipelined_realize_flash_attn_f32() {
14297        // [B=1, H=1, S=1or2, D=2]
14298        let q = fuel_memory::from_slice_cpu(&[2.0_f32, 0.0]);
14299        let k = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
14300        let v = fuel_memory::from_slice_cpu(&[10.0_f32, 0.0, 0.0, 10.0]);
14301        let graph = Arc::new(RwLock::new(Graph::new()));
14302        let (q_id, k_id, v_id, op_id) = {
14303            let mut g = graph.write().unwrap();
14304            let q = g.push(Node {
14305                op: Op::Const,
14306                inputs: vec![],
14307                shape: Shape::from_dims(&[1, 1, 1, 2]),
14308                dtype: DType::F32,
14309            });
14310            let k = g.push(Node {
14311                op: Op::Const,
14312                inputs: vec![],
14313                shape: Shape::from_dims(&[1, 1, 2, 2]),
14314                dtype: DType::F32,
14315            });
14316            let v = g.push(Node {
14317                op: Op::Const,
14318                inputs: vec![],
14319                shape: Shape::from_dims(&[1, 1, 2, 2]),
14320                dtype: DType::F32,
14321            });
14322            let op = g.push(Node {
14323                op: Op::Fused(
14324                    fuel_graph::registry::FusedOps::FLASH_ATTN,
14325                    fuel_graph::registry::FusedOpParams::FlashAttn {
14326                        softmax_scale: 1.0,
14327                        causal: false,
14328                        window_size_left: None,
14329                        window_size_right: None,
14330                        softcap: None,
14331                        k_len: None,
14332                    },
14333                ),
14334                inputs: vec![q, k, v],
14335                shape: Shape::from_dims(&[1, 1, 1, 2]),
14336                dtype: DType::F32,
14337            });
14338            g.set_target_backend(op, BackendId::Cpu);
14339            (q, k, v, op)
14340        };
14341        let mut inputs = StorageCache::new();
14342        inputs.insert(q_id, Arc::new(RwLock::new(q)));
14343        inputs.insert(k_id, Arc::new(RwLock::new(k)));
14344        inputs.insert(v_id, Arc::new(RwLock::new(v)));
14345        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14346        let guard = result_arc.read().unwrap();
14347        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14348            panic!("expected Cpu storage");
14349        };
14350        let r = c.as_slice::<f32>().unwrap();
14351        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
14352        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
14353        assert!(
14354            (r[0] - 10.0 * expected_p0).abs() < 1e-5,
14355            "row[0]: got {} expected {}",
14356            r[0],
14357            10.0 * expected_p0
14358        );
14359        assert!(
14360            (r[1] - 10.0 * expected_p1).abs() < 1e-5,
14361            "row[1]: got {} expected {}",
14362            r[1],
14363            10.0 * expected_p1
14364        );
14365    }
14366
14367    /// E2E: FlashAttn with causal mask — second query position
14368    /// attends to both keys (positions 0 and 1), first only attends
14369    /// to key 0 (everything beyond is masked).
14370    #[test]
14371    fn pipelined_realize_flash_attn_causal_f32() {
14372        // q [1,1,2,2]: query 0 = [1, 0], query 1 = [0, 1]
14373        // k [1,1,2,2]: keys = [[1, 0], [0, 1]]
14374        // v [1,1,2,2]: values = [[5, 6], [7, 8]]
14375        // softmax_scale=1, causal:
14376        //   query 0: only key 0 admissible → out = v[0] = [5, 6]
14377        //   query 1: both admissible. scores = q1·k = [0, 1]
14378        //            softmax = [1/(e+1), e/(e+1)]
14379        //            out = scores · v = [(5)/(e+1) + 7e/(e+1), 6/(e+1) + 8e/(e+1)]
14380        let q = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
14381        let k = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
14382        let v = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0, 7.0, 8.0]);
14383        let graph = Arc::new(RwLock::new(Graph::new()));
14384        let (q_id, k_id, v_id, op_id) = {
14385            let mut g = graph.write().unwrap();
14386            let q = g.push(Node {
14387                op: Op::Const,
14388                inputs: vec![],
14389                shape: Shape::from_dims(&[1, 1, 2, 2]),
14390                dtype: DType::F32,
14391            });
14392            let k = g.push(Node {
14393                op: Op::Const,
14394                inputs: vec![],
14395                shape: Shape::from_dims(&[1, 1, 2, 2]),
14396                dtype: DType::F32,
14397            });
14398            let v = g.push(Node {
14399                op: Op::Const,
14400                inputs: vec![],
14401                shape: Shape::from_dims(&[1, 1, 2, 2]),
14402                dtype: DType::F32,
14403            });
14404            let op = g.push(Node {
14405                op: Op::Fused(
14406                    fuel_graph::registry::FusedOps::FLASH_ATTN,
14407                    fuel_graph::registry::FusedOpParams::FlashAttn {
14408                        softmax_scale: 1.0,
14409                        causal: true,
14410                        window_size_left: None,
14411                        window_size_right: None,
14412                        softcap: None,
14413                        k_len: None,
14414                    },
14415                ),
14416                inputs: vec![q, k, v],
14417                shape: Shape::from_dims(&[1, 1, 2, 2]),
14418                dtype: DType::F32,
14419            });
14420            g.set_target_backend(op, BackendId::Cpu);
14421            (q, k, v, op)
14422        };
14423        let mut inputs = StorageCache::new();
14424        inputs.insert(q_id, Arc::new(RwLock::new(q)));
14425        inputs.insert(k_id, Arc::new(RwLock::new(k)));
14426        inputs.insert(v_id, Arc::new(RwLock::new(v)));
14427        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14428        let guard = result_arc.read().unwrap();
14429        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14430            panic!("expected Cpu storage");
14431        };
14432        let r = c.as_slice::<f32>().unwrap();
14433        // Query 0 sees only key 0 → output = v[0]
14434        assert!((r[0] - 5.0).abs() < 1e-5, "got {}", r[0]);
14435        assert!((r[1] - 6.0).abs() < 1e-5, "got {}", r[1]);
14436        // Query 1 sees both. softmax([0, 1]) = [1/(e+1), e/(e+1)]
14437        let denom = (1.0_f32).exp() + 1.0;
14438        let expected_a = 5.0 / denom + 7.0 * (1.0_f32).exp() / denom;
14439        let expected_b = 6.0 / denom + 8.0 * (1.0_f32).exp() / denom;
14440        assert!(
14441            (r[2] - expected_a).abs() < 1e-5,
14442            "row1[0]: got {} expected {}",
14443            r[2],
14444            expected_a
14445        );
14446        assert!(
14447            (r[3] - expected_b).abs() < 1e-5,
14448            "row1[1]: got {} expected {}",
14449            r[3],
14450            expected_b
14451        );
14452    }
14453
14454    /// E2E: FlashAttn over a fixed-**capacity** K/V with a runtime
14455    /// `k_len` resolved through a `SymEnv` (Phase D symbolic extents).
14456    /// Only the first `k_len` rows are attended; trailing "poison" rows
14457    /// in the capacity buffer are ignored, and the causal mask is
14458    /// bottom-right-aligned at offset `k_len - Sq`. This is flash decode
14459    /// over a persistent KV-cache: K/V are `[.., max_seq, ..]` capacity
14460    /// and the live prefix grows per token.
14461    #[test]
14462    fn pipelined_realize_flash_attn_dynamic_k_len() {
14463        use fuel_ir::{DynScalar, SymId};
14464        // q [1,1,2,2]; K/V capacity [1,1,4,2]; bind k_len = 3 so row 3
14465        // (the "poison" row) is never attended.
14466        let q = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
14467        let k = fuel_memory::from_slice_cpu(&[
14468            1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0, 100.0,
14469            100.0, // poison row 3 — must be ignored (k_len=3)
14470        ]);
14471        let v = fuel_memory::from_slice_cpu(&[
14472            5.0_f32, 6.0, 7.0, 8.0, 9.0, 10.0, 999.0,
14473            999.0, // poison row 3 — must be ignored
14474        ]);
14475        let sym = SymId(0);
14476        let graph = Arc::new(RwLock::new(Graph::new()));
14477        let (q_id, k_id, v_id, op_id) = {
14478            let mut g = graph.write().unwrap();
14479            let q = g.push(Node {
14480                op: Op::Const,
14481                inputs: vec![],
14482                shape: Shape::from_dims(&[1, 1, 2, 2]),
14483                dtype: DType::F32,
14484            });
14485            let k = g.push(Node {
14486                op: Op::Const,
14487                inputs: vec![],
14488                shape: Shape::from_dims(&[1, 1, 4, 2]),
14489                dtype: DType::F32,
14490            });
14491            let v = g.push(Node {
14492                op: Op::Const,
14493                inputs: vec![],
14494                shape: Shape::from_dims(&[1, 1, 4, 2]),
14495                dtype: DType::F32,
14496            });
14497            let op = g.push(Node {
14498                op: Op::Fused(
14499                    fuel_graph::registry::FusedOps::FLASH_ATTN,
14500                    fuel_graph::registry::FusedOpParams::FlashAttn {
14501                        softmax_scale: 1.0,
14502                        causal: true,
14503                        window_size_left: None,
14504                        window_size_right: None,
14505                        softcap: None,
14506                        k_len: Some(DynScalar::Sym(sym)),
14507                    },
14508                ),
14509                inputs: vec![q, k, v],
14510                shape: Shape::from_dims(&[1, 1, 2, 2]),
14511                dtype: DType::F32,
14512            });
14513            g.set_target_backend(op, BackendId::Cpu);
14514            (q, k, v, op)
14515        };
14516        let mut inputs = StorageCache::new();
14517        inputs.insert(q_id, Arc::new(RwLock::new(q)));
14518        inputs.insert(k_id, Arc::new(RwLock::new(k)));
14519        inputs.insert(v_id, Arc::new(RwLock::new(v)));
14520        let mut env = SymEnv::new();
14521        env.bind(sym, 3).unwrap();
14522        let (result_arc, _) = PipelinedExecutor::realize_with_env(graph, op_id, inputs, env)
14523            .expect("realize_with_env");
14524        let guard = result_arc.read().unwrap();
14525        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14526            panic!("expected Cpu storage");
14527        };
14528        let r = c.as_slice::<f32>().unwrap();
14529        let e = 1.0_f32.exp();
14530        // causal_offset = k_len - Sq = 3 - 2 = 1.
14531        // Query 0 (abs pos 1): keys {0,1}. scores [1,0] → softmax [e,1]/(e+1).
14532        let d0 = e + 1.0;
14533        let e0x = (5.0 * e + 7.0) / d0;
14534        let e0y = (6.0 * e + 8.0) / d0;
14535        // Query 1 (abs pos 2): keys {0,1,2}. scores [0,1,1] → [1,e,e]/(1+2e).
14536        let d1 = 1.0 + 2.0 * e;
14537        let e1x = (5.0 + 7.0 * e + 9.0 * e) / d1;
14538        let e1y = (6.0 + 8.0 * e + 10.0 * e) / d1;
14539        for (got, want) in r.iter().zip([e0x, e0y, e1x, e1y].iter()) {
14540            assert!(
14541                (got - want).abs() < 1e-4,
14542                "flash dyn k_len: got {got}, want {want} (full output {r:?}); \
14543                 a poison-contaminated value means the capacity rows past k_len leaked in",
14544            );
14545        }
14546    }
14547
14548    /// A flash `k_len` symbol unbound in the `SymEnv` surfaces a typed
14549    /// error at realize (never a panic).
14550    #[test]
14551    fn pipelined_realize_flash_attn_dynamic_k_len_unbound_errors() {
14552        use fuel_ir::{DynScalar, SymId};
14553        let q = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
14554        let k = fuel_memory::from_slice_cpu(&[0.0_f32; 16]);
14555        let v = fuel_memory::from_slice_cpu(&[0.0_f32; 16]);
14556        let graph = Arc::new(RwLock::new(Graph::new()));
14557        let (q_id, k_id, v_id, op_id) = {
14558            let mut g = graph.write().unwrap();
14559            let q = g.push(Node {
14560                op: Op::Const,
14561                inputs: vec![],
14562                shape: Shape::from_dims(&[1, 1, 2, 2]),
14563                dtype: DType::F32,
14564            });
14565            let k = g.push(Node {
14566                op: Op::Const,
14567                inputs: vec![],
14568                shape: Shape::from_dims(&[1, 1, 4, 2]),
14569                dtype: DType::F32,
14570            });
14571            let v = g.push(Node {
14572                op: Op::Const,
14573                inputs: vec![],
14574                shape: Shape::from_dims(&[1, 1, 4, 2]),
14575                dtype: DType::F32,
14576            });
14577            let op = g.push(Node {
14578                op: Op::Fused(
14579                    fuel_graph::registry::FusedOps::FLASH_ATTN,
14580                    fuel_graph::registry::FusedOpParams::FlashAttn {
14581                        softmax_scale: 1.0,
14582                        causal: true,
14583                        window_size_left: None,
14584                        window_size_right: None,
14585                        softcap: None,
14586                        k_len: Some(DynScalar::Sym(SymId(0))),
14587                    },
14588                ),
14589                inputs: vec![q, k, v],
14590                shape: Shape::from_dims(&[1, 1, 2, 2]),
14591                dtype: DType::F32,
14592            });
14593            g.set_target_backend(op, BackendId::Cpu);
14594            (q, k, v, op)
14595        };
14596        let mut inputs = StorageCache::new();
14597        inputs.insert(q_id, Arc::new(RwLock::new(q)));
14598        inputs.insert(k_id, Arc::new(RwLock::new(k)));
14599        inputs.insert(v_id, Arc::new(RwLock::new(v)));
14600        // Empty env — the k_len symbol is unbound.
14601        let result = PipelinedExecutor::realize_with_env(graph, op_id, inputs, SymEnv::new());
14602        assert!(
14603            result.is_err(),
14604            "unbound flash k_len symbol must surface a typed error"
14605        );
14606    }
14607
14608    /// E2E: FlashAttn BF16 — same single-row test as f32, tolerant.
14609    #[test]
14610    fn pipelined_realize_flash_attn_bf16() {
14611        let q_v: Vec<half::bf16> = [2.0_f32, 0.0]
14612            .iter()
14613            .map(|x| half::bf16::from_f32(*x))
14614            .collect();
14615        let k_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0]
14616            .iter()
14617            .map(|x| half::bf16::from_f32(*x))
14618            .collect();
14619        let v_v: Vec<half::bf16> = [10.0_f32, 0.0, 0.0, 10.0]
14620            .iter()
14621            .map(|x| half::bf16::from_f32(*x))
14622            .collect();
14623        let q = fuel_memory::from_slice_cpu(&q_v);
14624        let k = fuel_memory::from_slice_cpu(&k_v);
14625        let v = fuel_memory::from_slice_cpu(&v_v);
14626        let graph = Arc::new(RwLock::new(Graph::new()));
14627        let (q_id, k_id, v_id, op_id) = {
14628            let mut g = graph.write().unwrap();
14629            let q = g.push(Node {
14630                op: Op::Const,
14631                inputs: vec![],
14632                shape: Shape::from_dims(&[1, 1, 1, 2]),
14633                dtype: DType::BF16,
14634            });
14635            let k = g.push(Node {
14636                op: Op::Const,
14637                inputs: vec![],
14638                shape: Shape::from_dims(&[1, 1, 2, 2]),
14639                dtype: DType::BF16,
14640            });
14641            let v = g.push(Node {
14642                op: Op::Const,
14643                inputs: vec![],
14644                shape: Shape::from_dims(&[1, 1, 2, 2]),
14645                dtype: DType::BF16,
14646            });
14647            let op = g.push(Node {
14648                op: Op::Fused(
14649                    fuel_graph::registry::FusedOps::FLASH_ATTN,
14650                    fuel_graph::registry::FusedOpParams::FlashAttn {
14651                        softmax_scale: 1.0,
14652                        causal: false,
14653                        window_size_left: None,
14654                        window_size_right: None,
14655                        softcap: None,
14656                        k_len: None,
14657                    },
14658                ),
14659                inputs: vec![q, k, v],
14660                shape: Shape::from_dims(&[1, 1, 1, 2]),
14661                dtype: DType::BF16,
14662            });
14663            g.set_target_backend(op, BackendId::Cpu);
14664            (q, k, v, op)
14665        };
14666        let mut inputs = StorageCache::new();
14667        inputs.insert(q_id, Arc::new(RwLock::new(q)));
14668        inputs.insert(k_id, Arc::new(RwLock::new(k)));
14669        inputs.insert(v_id, Arc::new(RwLock::new(v)));
14670        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14671        let guard = result_arc.read().unwrap();
14672        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14673            panic!("expected Cpu storage");
14674        };
14675        let got: Vec<f32> = c
14676            .as_slice::<half::bf16>()
14677            .unwrap()
14678            .iter()
14679            .map(|v| v.to_f32())
14680            .collect();
14681        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
14682        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
14683        let want = [10.0 * expected_p0, 10.0 * expected_p1];
14684        for (g, w) in got.iter().zip(want.iter()) {
14685            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
14686        }
14687    }
14688
14689    /// E2E: Op::FusedLinear — F32. a[1,2,3] @ b[1,3,2] + bias[2].
14690    /// a = [[[1,2,3],[4,5,6]]], b = [[[1,0],[0,1],[1,1]]], bias=[10,20]
14691    /// matmul = [[1+0+3, 0+2+3], [4+0+6, 0+5+6]] = [[4, 5], [10, 11]]
14692    /// + bias = [[14, 25], [20, 31]]
14693    #[test]
14694    fn pipelined_realize_fused_linear_f32() {
14695        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14696        let b = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0]);
14697        let bias = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
14698        let graph = Arc::new(RwLock::new(Graph::new()));
14699        let (a_id, b_id, bias_id, op_id) = {
14700            let mut g = graph.write().unwrap();
14701            let a = g.push(Node {
14702                op: Op::Const,
14703                inputs: vec![],
14704                shape: Shape::from_dims(&[1, 2, 3]),
14705                dtype: DType::F32,
14706            });
14707            let b = g.push(Node {
14708                op: Op::Const,
14709                inputs: vec![],
14710                shape: Shape::from_dims(&[1, 3, 2]),
14711                dtype: DType::F32,
14712            });
14713            let bias = g.push(Node {
14714                op: Op::Const,
14715                inputs: vec![],
14716                shape: Shape::from_dims(&[2]),
14717                dtype: DType::F32,
14718            });
14719            let op = g.push(Node {
14720                op: Op::Fused(
14721                    fuel_graph::registry::FusedOps::FUSED_LINEAR,
14722                    fuel_graph::registry::FusedOpParams::FusedLinear,
14723                ),
14724                inputs: vec![a, b, bias],
14725                shape: Shape::from_dims(&[1, 2, 2]),
14726                dtype: DType::F32,
14727            });
14728            g.set_target_backend(op, BackendId::Cpu);
14729            (a, b, bias, op)
14730        };
14731        let mut inputs = StorageCache::new();
14732        inputs.insert(a_id, Arc::new(RwLock::new(a)));
14733        inputs.insert(b_id, Arc::new(RwLock::new(b)));
14734        inputs.insert(bias_id, Arc::new(RwLock::new(bias)));
14735        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14736        let guard = result_arc.read().unwrap();
14737        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14738            panic!("expected Cpu storage");
14739        };
14740        assert_eq!(c.as_slice::<f32>().unwrap(), &[14.0, 25.0, 20.0, 31.0]);
14741    }
14742
14743    /// E2E: FusedLinear F64 — same shape test on doubles.
14744    #[test]
14745    fn pipelined_realize_fused_linear_f64() {
14746        let a = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
14747        let b = fuel_memory::from_slice_cpu(&[1.0_f64, 0.0, 0.0, 1.0, 1.0, 1.0]);
14748        let bias = fuel_memory::from_slice_cpu(&[10.0_f64, 20.0]);
14749        let graph = Arc::new(RwLock::new(Graph::new()));
14750        let (a_id, b_id, bias_id, op_id) = {
14751            let mut g = graph.write().unwrap();
14752            let a = g.push(Node {
14753                op: Op::Const,
14754                inputs: vec![],
14755                shape: Shape::from_dims(&[1, 2, 3]),
14756                dtype: DType::F64,
14757            });
14758            let b = g.push(Node {
14759                op: Op::Const,
14760                inputs: vec![],
14761                shape: Shape::from_dims(&[1, 3, 2]),
14762                dtype: DType::F64,
14763            });
14764            let bias = g.push(Node {
14765                op: Op::Const,
14766                inputs: vec![],
14767                shape: Shape::from_dims(&[2]),
14768                dtype: DType::F64,
14769            });
14770            let op = g.push(Node {
14771                op: Op::Fused(
14772                    fuel_graph::registry::FusedOps::FUSED_LINEAR,
14773                    fuel_graph::registry::FusedOpParams::FusedLinear,
14774                ),
14775                inputs: vec![a, b, bias],
14776                shape: Shape::from_dims(&[1, 2, 2]),
14777                dtype: DType::F64,
14778            });
14779            g.set_target_backend(op, BackendId::Cpu);
14780            (a, b, bias, op)
14781        };
14782        let mut inputs = StorageCache::new();
14783        inputs.insert(a_id, Arc::new(RwLock::new(a)));
14784        inputs.insert(b_id, Arc::new(RwLock::new(b)));
14785        inputs.insert(bias_id, Arc::new(RwLock::new(bias)));
14786        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14787        let guard = result_arc.read().unwrap();
14788        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14789            panic!("expected Cpu storage");
14790        };
14791        assert_eq!(c.as_slice::<f64>().unwrap(), &[14.0, 25.0, 20.0, 31.0]);
14792    }
14793
14794    /// E2E (row 172 item 1): RowScaledMatMul F32 on CPU. a [1,2,3] @ b [1,3,2]
14795    /// = [[4, 5], [10, 11]]... computed by hand below; each row is scaled by its
14796    /// own entry of row_scale [1,2,1] = [2, 10]. A per-column or unscaled result
14797    /// would differ, so this discriminates the epilogue.
14798    #[test]
14799    fn pipelined_realize_row_scaled_matmul_f32() {
14800        // a rows: [1,2,3], [4,5,6]; b = [[1,0],[0,1],[1,1]].
14801        // a@b = [[1+3, 2+3], [4+6, 5+6]] = [[4, 5], [10, 11]].
14802        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14803        let b = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0]);
14804        let scale = fuel_memory::from_slice_cpu(&[2.0_f32, 10.0]);
14805        let graph = Arc::new(RwLock::new(Graph::new()));
14806        let (a_id, b_id, s_id, op_id) = {
14807            let mut g = graph.write().unwrap();
14808            let mut konst = |dims: &[usize]| {
14809                g.push(Node {
14810                    op: Op::Const,
14811                    inputs: vec![],
14812                    shape: Shape::from_dims(dims),
14813                    dtype: DType::F32,
14814                })
14815            };
14816            let (a, b, s) = (konst(&[1, 2, 3]), konst(&[1, 3, 2]), konst(&[1, 2, 1]));
14817            let op = g.push(Node {
14818                op: Op::Fused(
14819                    fuel_graph::registry::FusedOps::ROW_SCALED_MATMUL,
14820                    fuel_graph::registry::FusedOpParams::RowScaledMatMul,
14821                ),
14822                inputs: vec![a, b, s],
14823                shape: Shape::from_dims(&[1, 2, 2]),
14824                dtype: DType::F32,
14825            });
14826            g.set_target_backend(op, BackendId::Cpu);
14827            (a, b, s, op)
14828        };
14829        let mut inputs = StorageCache::new();
14830        inputs.insert(a_id, Arc::new(RwLock::new(a)));
14831        inputs.insert(b_id, Arc::new(RwLock::new(b)));
14832        inputs.insert(s_id, Arc::new(RwLock::new(scale)));
14833        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14834        let guard = result_arc.read().unwrap();
14835        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14836            panic!("expected Cpu storage");
14837        };
14838        assert_eq!(c.as_slice::<f32>().unwrap(), &[8.0, 10.0, 100.0, 110.0]);
14839    }
14840
14841    /// E2E: FusedLinear BF16 — tolerant compare.
14842    #[test]
14843    fn pipelined_realize_fused_linear_bf16() {
14844        let a_v: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]
14845            .iter()
14846            .map(|x| half::bf16::from_f32(*x))
14847            .collect();
14848        let b_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0]
14849            .iter()
14850            .map(|x| half::bf16::from_f32(*x))
14851            .collect();
14852        let bias_v: Vec<half::bf16> = [10.0_f32, 20.0]
14853            .iter()
14854            .map(|x| half::bf16::from_f32(*x))
14855            .collect();
14856        let a = fuel_memory::from_slice_cpu(&a_v);
14857        let b = fuel_memory::from_slice_cpu(&b_v);
14858        let bias = fuel_memory::from_slice_cpu(&bias_v);
14859        let graph = Arc::new(RwLock::new(Graph::new()));
14860        let (a_id, b_id, bias_id, op_id) = {
14861            let mut g = graph.write().unwrap();
14862            let a = g.push(Node {
14863                op: Op::Const,
14864                inputs: vec![],
14865                shape: Shape::from_dims(&[1, 2, 3]),
14866                dtype: DType::BF16,
14867            });
14868            let b = g.push(Node {
14869                op: Op::Const,
14870                inputs: vec![],
14871                shape: Shape::from_dims(&[1, 3, 2]),
14872                dtype: DType::BF16,
14873            });
14874            let bias = g.push(Node {
14875                op: Op::Const,
14876                inputs: vec![],
14877                shape: Shape::from_dims(&[2]),
14878                dtype: DType::BF16,
14879            });
14880            let op = g.push(Node {
14881                op: Op::Fused(
14882                    fuel_graph::registry::FusedOps::FUSED_LINEAR,
14883                    fuel_graph::registry::FusedOpParams::FusedLinear,
14884                ),
14885                inputs: vec![a, b, bias],
14886                shape: Shape::from_dims(&[1, 2, 2]),
14887                dtype: DType::BF16,
14888            });
14889            g.set_target_backend(op, BackendId::Cpu);
14890            (a, b, bias, op)
14891        };
14892        let mut inputs = StorageCache::new();
14893        inputs.insert(a_id, Arc::new(RwLock::new(a)));
14894        inputs.insert(b_id, Arc::new(RwLock::new(b)));
14895        inputs.insert(bias_id, Arc::new(RwLock::new(bias)));
14896        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14897        let guard = result_arc.read().unwrap();
14898        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14899            panic!("expected Cpu storage");
14900        };
14901        let got: Vec<f32> = c
14902            .as_slice::<half::bf16>()
14903            .unwrap()
14904            .iter()
14905            .map(|v| v.to_f32())
14906            .collect();
14907        let want = [14.0_f32, 25.0, 20.0, 31.0];
14908        for (g, w) in got.iter().zip(want.iter()) {
14909            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
14910        }
14911    }
14912
14913    /// E2E: Op::ReduceSumTo — sum the leading axis of a [2,3] tensor.
14914    /// Input [[1,2,3],[4,5,6]] → output [5,7,9].
14915    #[test]
14916    fn pipelined_realize_reduce_sum_to_f32_drops_leading_axis() {
14917        let v = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14918        let graph = Arc::new(RwLock::new(Graph::new()));
14919        let (in_id, op_id) = {
14920            let mut g = graph.write().unwrap();
14921            let in_id = g.push(Node {
14922                op: Op::Const,
14923                inputs: vec![],
14924                shape: Shape::from_dims(&[2, 3]),
14925                dtype: DType::F32,
14926            });
14927            let op_id = g.push(Node {
14928                op: Op::ReduceSumTo(Shape::from_dims(&[3])),
14929                inputs: vec![in_id],
14930                shape: Shape::from_dims(&[3]),
14931                dtype: DType::F32,
14932            });
14933            g.set_target_backend(op_id, BackendId::Cpu);
14934            (in_id, op_id)
14935        };
14936        let mut inputs = StorageCache::new();
14937        inputs.insert(in_id, Arc::new(RwLock::new(v)));
14938        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14939        let guard = result_arc.read().unwrap();
14940        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14941            panic!("expected Cpu storage");
14942        };
14943        assert_eq!(c.as_slice::<f32>().unwrap(), &[5.0, 7.0, 9.0]);
14944    }
14945
14946    /// E2E: Op::ReduceSumTo — keep-dim with 1 in the middle.
14947    /// Input [2,3,4] → [2,1,4] sums along dim 1.
14948    #[test]
14949    fn pipelined_realize_reduce_sum_to_f32_keepdim_middle() {
14950        // [2,3,4]: layer 0 = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
14951        //          layer 1 = [[13..16],[17..20],[21..24]]
14952        let mut v: Vec<f32> = (1..=24).map(|x| x as f32).collect();
14953        let _ = &mut v;
14954        let s = fuel_memory::from_slice_cpu(&v);
14955        let graph = Arc::new(RwLock::new(Graph::new()));
14956        let (in_id, op_id) = {
14957            let mut g = graph.write().unwrap();
14958            let in_id = g.push(Node {
14959                op: Op::Const,
14960                inputs: vec![],
14961                shape: Shape::from_dims(&[2, 3, 4]),
14962                dtype: DType::F32,
14963            });
14964            let op_id = g.push(Node {
14965                op: Op::ReduceSumTo(Shape::from_dims(&[2, 1, 4])),
14966                inputs: vec![in_id],
14967                shape: Shape::from_dims(&[2, 1, 4]),
14968                dtype: DType::F32,
14969            });
14970            g.set_target_backend(op_id, BackendId::Cpu);
14971            (in_id, op_id)
14972        };
14973        let mut inputs = StorageCache::new();
14974        inputs.insert(in_id, Arc::new(RwLock::new(s)));
14975        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14976        let guard = result_arc.read().unwrap();
14977        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14978            panic!("expected Cpu storage");
14979        };
14980        // layer0 dim1-sum: col j = 1+5+9, 2+6+10, 3+7+11, 4+8+12 = [15,18,21,24]
14981        // layer1 dim1-sum: col j = 13+17+21, 14+18+22, 15+19+23, 16+20+24 = [51,54,57,60]
14982        assert_eq!(
14983            c.as_slice::<f32>().unwrap(),
14984            &[15.0, 18.0, 21.0, 24.0, 51.0, 54.0, 57.0, 60.0],
14985        );
14986    }
14987
14988    /// E2E: ReduceSumTo F64 — same drop-leading-axis test on doubles.
14989    #[test]
14990    fn pipelined_realize_reduce_sum_to_f64() {
14991        let v = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
14992        let graph = Arc::new(RwLock::new(Graph::new()));
14993        let (in_id, op_id) = {
14994            let mut g = graph.write().unwrap();
14995            let in_id = g.push(Node {
14996                op: Op::Const,
14997                inputs: vec![],
14998                shape: Shape::from_dims(&[2, 3]),
14999                dtype: DType::F64,
15000            });
15001            let op_id = g.push(Node {
15002                op: Op::ReduceSumTo(Shape::from_dims(&[3])),
15003                inputs: vec![in_id],
15004                shape: Shape::from_dims(&[3]),
15005                dtype: DType::F64,
15006            });
15007            g.set_target_backend(op_id, BackendId::Cpu);
15008            (in_id, op_id)
15009        };
15010        let mut inputs = StorageCache::new();
15011        inputs.insert(in_id, Arc::new(RwLock::new(v)));
15012        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
15013        let guard = result_arc.read().unwrap();
15014        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15015            panic!("expected Cpu storage");
15016        };
15017        assert_eq!(c.as_slice::<f64>().unwrap(), &[5.0, 7.0, 9.0]);
15018    }
15019
15020    /// E2E: Op::ReduceMaxTo F32 — drop the leading axis with max-reduce.
15021    #[test]
15022    fn pipelined_realize_reduce_max_to_f32_drops_leading_axis() {
15023        // Input [2,3]: row 0 = [1, 7, 3], row 1 = [4, 2, 6]. Max along
15024        // dim 0: [4, 7, 6].
15025        let v = fuel_memory::from_slice_cpu(&[1.0_f32, 7.0, 3.0, 4.0, 2.0, 6.0]);
15026        let graph = Arc::new(RwLock::new(Graph::new()));
15027        let (in_id, op_id) = {
15028            let mut g = graph.write().unwrap();
15029            let in_id = g.push(Node {
15030                op: Op::Const,
15031                inputs: vec![],
15032                shape: Shape::from_dims(&[2, 3]),
15033                dtype: DType::F32,
15034            });
15035            let op_id = g.push(Node {
15036                op: Op::ReduceMaxTo(Shape::from_dims(&[3])),
15037                inputs: vec![in_id],
15038                shape: Shape::from_dims(&[3]),
15039                dtype: DType::F32,
15040            });
15041            g.set_target_backend(op_id, BackendId::Cpu);
15042            (in_id, op_id)
15043        };
15044        let mut inputs = StorageCache::new();
15045        inputs.insert(in_id, Arc::new(RwLock::new(v)));
15046        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
15047        let guard = result_arc.read().unwrap();
15048        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15049            panic!("expected Cpu storage");
15050        };
15051        assert_eq!(c.as_slice::<f32>().unwrap(), &[4.0, 7.0, 6.0]);
15052    }
15053
15054    /// E2E: Op::ReduceMaxTo F32 — keep-dim with 1 in the trailing axis.
15055    /// Mirrors the SoftmaxLastDim lowering's max-side shape: input
15056    /// [..., last] → [..., 1].
15057    #[test]
15058    fn pipelined_realize_reduce_max_to_f32_keepdim_trailing() {
15059        // Input [2, 3]: row maxes = [3, 6].
15060        let v = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
15061        let graph = Arc::new(RwLock::new(Graph::new()));
15062        let (in_id, op_id) = {
15063            let mut g = graph.write().unwrap();
15064            let in_id = g.push(Node {
15065                op: Op::Const,
15066                inputs: vec![],
15067                shape: Shape::from_dims(&[2, 3]),
15068                dtype: DType::F32,
15069            });
15070            let op_id = g.push(Node {
15071                op: Op::ReduceMaxTo(Shape::from_dims(&[2, 1])),
15072                inputs: vec![in_id],
15073                shape: Shape::from_dims(&[2, 1]),
15074                dtype: DType::F32,
15075            });
15076            g.set_target_backend(op_id, BackendId::Cpu);
15077            (in_id, op_id)
15078        };
15079        let mut inputs = StorageCache::new();
15080        inputs.insert(in_id, Arc::new(RwLock::new(v)));
15081        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
15082        let guard = result_arc.read().unwrap();
15083        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15084            panic!("expected Cpu storage");
15085        };
15086        assert_eq!(c.as_slice::<f32>().unwrap(), &[3.0, 6.0]);
15087    }
15088
15089    /// E2E: ReduceSumTo BF16 — tolerant compare via f32-acc.
15090    #[test]
15091    fn pipelined_realize_reduce_sum_to_bf16() {
15092        let v: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]
15093            .iter()
15094            .map(|x| half::bf16::from_f32(*x))
15095            .collect();
15096        let s = fuel_memory::from_slice_cpu(&v);
15097        let graph = Arc::new(RwLock::new(Graph::new()));
15098        let (in_id, op_id) = {
15099            let mut g = graph.write().unwrap();
15100            let in_id = g.push(Node {
15101                op: Op::Const,
15102                inputs: vec![],
15103                shape: Shape::from_dims(&[2, 3]),
15104                dtype: DType::BF16,
15105            });
15106            let op_id = g.push(Node {
15107                op: Op::ReduceSumTo(Shape::from_dims(&[3])),
15108                inputs: vec![in_id],
15109                shape: Shape::from_dims(&[3]),
15110                dtype: DType::BF16,
15111            });
15112            g.set_target_backend(op_id, BackendId::Cpu);
15113            (in_id, op_id)
15114        };
15115        let mut inputs = StorageCache::new();
15116        inputs.insert(in_id, Arc::new(RwLock::new(s)));
15117        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
15118        let guard = result_arc.read().unwrap();
15119        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15120            panic!("expected Cpu storage");
15121        };
15122        let got: Vec<f32> = c
15123            .as_slice::<half::bf16>()
15124            .unwrap()
15125            .iter()
15126            .map(|v| v.to_f32())
15127            .collect();
15128        let want = [5.0_f32, 7.0, 9.0];
15129        for (g, w) in got.iter().zip(want.iter()) {
15130            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
15131        }
15132    }
15133
15134    /// E2E: Op::ConvTranspose2D — F32 spread test.
15135    /// x = [[1, 2], [3, 4]] shape [1,1,2,2], all-ones kernel
15136    /// shape [1,1,2,2], stride=1, padding=0, dilation=1, no bias.
15137    /// Expected output (3x3):
15138    ///   [[1,  3, 2],
15139    ///    [4, 10, 6],
15140    ///    [3,  7, 4]]
15141    #[test]
15142    fn pipelined_realize_conv_transpose2d_f32() {
15143        let x_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
15144        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
15145        let graph = Arc::new(RwLock::new(Graph::new()));
15146        let (x_id, w_id, c_id) = {
15147            let mut g = graph.write().unwrap();
15148            let x = g.push(Node {
15149                op: Op::Const,
15150                inputs: vec![],
15151                shape: Shape::from_dims(&[1, 1, 2, 2]),
15152                dtype: DType::F32,
15153            });
15154            let w = g.push(Node {
15155                op: Op::Const,
15156                inputs: vec![],
15157                shape: Shape::from_dims(&[1, 1, 2, 2]),
15158                dtype: DType::F32,
15159            });
15160            let c = g.push(Node {
15161                op: Op::Fused(
15162                    fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D,
15163                    fuel_graph::registry::FusedOpParams::ConvTranspose2D {
15164                        stride: (1, 1),
15165                        padding: (0, 0),
15166                        output_padding: (0, 0),
15167                        dilation: (1, 1),
15168                        groups: 1,
15169                    },
15170                ),
15171                inputs: vec![x, w],
15172                shape: Shape::from_dims(&[1, 1, 3, 3]),
15173                dtype: DType::F32,
15174            });
15175            g.set_target_backend(c, BackendId::Cpu);
15176            (x, w, c)
15177        };
15178        let mut inputs = StorageCache::new();
15179        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
15180        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
15181        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
15182        let guard = result_arc.read().unwrap();
15183        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15184            panic!("expected Cpu storage");
15185        };
15186        assert_eq!(
15187            c.as_slice::<f32>().unwrap(),
15188            &[1.0, 3.0, 2.0, 4.0, 10.0, 6.0, 3.0, 7.0, 4.0],
15189        );
15190    }
15191
15192    /// E2E: ConvTranspose2D F64 — same shape test.
15193    #[test]
15194    fn pipelined_realize_conv_transpose2d_f64() {
15195        let x_storage = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0]);
15196        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f64, 1.0, 1.0, 1.0]);
15197        let graph = Arc::new(RwLock::new(Graph::new()));
15198        let (x_id, w_id, c_id) = {
15199            let mut g = graph.write().unwrap();
15200            let x = g.push(Node {
15201                op: Op::Const,
15202                inputs: vec![],
15203                shape: Shape::from_dims(&[1, 1, 2, 2]),
15204                dtype: DType::F64,
15205            });
15206            let w = g.push(Node {
15207                op: Op::Const,
15208                inputs: vec![],
15209                shape: Shape::from_dims(&[1, 1, 2, 2]),
15210                dtype: DType::F64,
15211            });
15212            let c = g.push(Node {
15213                op: Op::Fused(
15214                    fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D,
15215                    fuel_graph::registry::FusedOpParams::ConvTranspose2D {
15216                        stride: (1, 1),
15217                        padding: (0, 0),
15218                        output_padding: (0, 0),
15219                        dilation: (1, 1),
15220                        groups: 1,
15221                    },
15222                ),
15223                inputs: vec![x, w],
15224                shape: Shape::from_dims(&[1, 1, 3, 3]),
15225                dtype: DType::F64,
15226            });
15227            g.set_target_backend(c, BackendId::Cpu);
15228            (x, w, c)
15229        };
15230        let mut inputs = StorageCache::new();
15231        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
15232        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
15233        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
15234        let guard = result_arc.read().unwrap();
15235        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15236            panic!("expected Cpu storage");
15237        };
15238        assert_eq!(
15239            c.as_slice::<f64>().unwrap(),
15240            &[1.0, 3.0, 2.0, 4.0, 10.0, 6.0, 3.0, 7.0, 4.0],
15241        );
15242    }
15243
15244    /// E2E: ConvTranspose2D BF16 — tolerant compare via f32-acc.
15245    #[test]
15246    fn pipelined_realize_conv_transpose2d_bf16() {
15247        let x: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0]
15248            .iter()
15249            .map(|v| half::bf16::from_f32(*v))
15250            .collect();
15251        let w: Vec<half::bf16> = [1.0_f32, 1.0, 1.0, 1.0]
15252            .iter()
15253            .map(|v| half::bf16::from_f32(*v))
15254            .collect();
15255        let x_storage = fuel_memory::from_slice_cpu(&x);
15256        let w_storage = fuel_memory::from_slice_cpu(&w);
15257        let graph = Arc::new(RwLock::new(Graph::new()));
15258        let (x_id, w_id, c_id) = {
15259            let mut g = graph.write().unwrap();
15260            let x = g.push(Node {
15261                op: Op::Const,
15262                inputs: vec![],
15263                shape: Shape::from_dims(&[1, 1, 2, 2]),
15264                dtype: DType::BF16,
15265            });
15266            let w = g.push(Node {
15267                op: Op::Const,
15268                inputs: vec![],
15269                shape: Shape::from_dims(&[1, 1, 2, 2]),
15270                dtype: DType::BF16,
15271            });
15272            let c = g.push(Node {
15273                op: Op::Fused(
15274                    fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D,
15275                    fuel_graph::registry::FusedOpParams::ConvTranspose2D {
15276                        stride: (1, 1),
15277                        padding: (0, 0),
15278                        output_padding: (0, 0),
15279                        dilation: (1, 1),
15280                        groups: 1,
15281                    },
15282                ),
15283                inputs: vec![x, w],
15284                shape: Shape::from_dims(&[1, 1, 3, 3]),
15285                dtype: DType::BF16,
15286            });
15287            g.set_target_backend(c, BackendId::Cpu);
15288            (x, w, c)
15289        };
15290        let mut inputs = StorageCache::new();
15291        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
15292        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
15293        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
15294        let guard = result_arc.read().unwrap();
15295        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15296            panic!("expected Cpu storage");
15297        };
15298        let got: Vec<f32> = c
15299            .as_slice::<half::bf16>()
15300            .unwrap()
15301            .iter()
15302            .map(|v| v.to_f32())
15303            .collect();
15304        let want = [1.0_f32, 3.0, 2.0, 4.0, 10.0, 6.0, 3.0, 7.0, 4.0];
15305        for (g, w) in got.iter().zip(want.iter()) {
15306            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
15307        }
15308    }
15309
15310    /// E2E: GQA-style matmul through the pipelined executor.
15311    /// lhs has 4 batch heads, rhs has 2; each rhs head is shared
15312    /// by 2 lhs heads. Output's batch dim follows lhs (4 heads).
15313    #[test]
15314    fn pipelined_realize_matmul_gqa() {
15315        // lhs [4, 1, 2]: heads 0..3 are [[1,2]], [[3,4]], [[5,6]], [[7,8]]
15316        // rhs [2, 2, 1]: heads 0,1 are [[1],[0]], [[0],[1]]
15317        // Expected out [4, 1, 1]: [[1]], [[3]], [[6]], [[8]]
15318        let lhs_storage =
15319            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]);
15320        let rhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
15321
15322        let graph = Arc::new(RwLock::new(Graph::new()));
15323        let (lhs_id, rhs_id, mm_id) = {
15324            let mut g = graph.write().unwrap();
15325            let lhs = g.push(Node {
15326                op: Op::Const,
15327                inputs: vec![],
15328                shape: Shape::from_dims(&[4, 1, 2]),
15329                dtype: DType::F32,
15330            });
15331            let rhs = g.push(Node {
15332                op: Op::Const,
15333                inputs: vec![],
15334                shape: Shape::from_dims(&[2, 2, 1]),
15335                dtype: DType::F32,
15336            });
15337            let mm = g.push(Node {
15338                op: Op::MatMul,
15339                inputs: vec![lhs, rhs],
15340                shape: Shape::from_dims(&[4, 1, 1]),
15341                dtype: DType::F32,
15342            });
15343            g.set_target_backend(mm, BackendId::Cpu);
15344            (lhs, rhs, mm)
15345        };
15346        let mut inputs = StorageCache::new();
15347        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
15348        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
15349
15350        let (result_arc, result_layout) =
15351            PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
15352        assert_eq!(result_layout.shape().dims(), &[4, 1, 1]);
15353
15354        let guard = result_arc.read().unwrap();
15355        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15356            panic!("expected Cpu storage");
15357        };
15358        assert_eq!(c.as_slice::<f32>().unwrap(), &[1.0, 3.0, 6.0, 8.0]);
15359    }
15360
15361    /// E2E: matmul with a transposed rhs — proves stage 3+4
15362    /// integration carries through the matmul path. The transpose
15363    /// is metadata-only; auto-Contiguize materializes the strided
15364    /// rhs before the matmul kernel sees it.
15365    #[test]
15366    fn pipelined_realize_matmul_with_transposed_rhs() {
15367        // lhs [[1, 2], [3, 4]], rhs original [[5, 6], [7, 8]]
15368        // rhs.T = [[5, 7], [6, 8]]
15369        // lhs @ rhs.T = [[1*5+2*6, 1*7+2*8], [3*5+4*6, 3*7+4*8]]
15370        //             = [[17, 23], [39, 53]]
15371        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
15372        let rhs_storage = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0, 7.0, 8.0]);
15373
15374        let graph = Arc::new(RwLock::new(Graph::new()));
15375        let (lhs_id, rhs_id, t_id, mm_id) = {
15376            let mut g = graph.write().unwrap();
15377            let lhs = g.push(Node {
15378                op: Op::Const,
15379                inputs: vec![],
15380                shape: Shape::from_dims(&[2, 2]),
15381                dtype: DType::F32,
15382            });
15383            let rhs = g.push(Node {
15384                op: Op::Const,
15385                inputs: vec![],
15386                shape: Shape::from_dims(&[2, 2]),
15387                dtype: DType::F32,
15388            });
15389            let t = g.push(Node {
15390                op: Op::Transpose,
15391                inputs: vec![rhs],
15392                shape: Shape::from_dims(&[2, 2]),
15393                dtype: DType::F32,
15394            });
15395            let mm = g.push(Node {
15396                op: Op::MatMul,
15397                inputs: vec![lhs, t],
15398                shape: Shape::from_dims(&[2, 2]),
15399                dtype: DType::F32,
15400            });
15401            g.set_target_backend(mm, BackendId::Cpu);
15402            (lhs, rhs, t, mm)
15403        };
15404        let _ = t_id;
15405        let mut inputs = StorageCache::new();
15406        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
15407        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
15408
15409        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
15410        let guard = result_arc.read().unwrap();
15411        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15412            panic!("expected Cpu storage");
15413        };
15414        assert_eq!(c.as_slice::<f32>().unwrap(), &[17.0, 23.0, 39.0, 53.0]);
15415    }
15416
15417    /// E2E: Const + Reshape — contiguous-input reshape is zero
15418    /// copy. The output Storage Arc is the input Arc; the layout
15419    /// is contiguous in the new shape.
15420    #[test]
15421    fn pipelined_realize_reshape_zero_copy_when_contiguous() {
15422        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
15423        let graph = Arc::new(RwLock::new(Graph::new()));
15424        let (in_id, r_id) = {
15425            let mut g = graph.write().unwrap();
15426            let in_id = g.push(Node {
15427                op: Op::Const,
15428                inputs: vec![],
15429                shape: Shape::from_dims(&[2, 3]),
15430                dtype: DType::F32,
15431            });
15432            let r_id = g.push(Node {
15433                op: Op::Reshape(Shape::from_dims(&[3, 2])),
15434                inputs: vec![in_id],
15435                shape: Shape::from_dims(&[3, 2]),
15436                dtype: DType::F32,
15437            });
15438            (in_id, r_id)
15439        };
15440        let mut inputs = StorageCache::new();
15441        let in_arc = Arc::new(RwLock::new(storage));
15442        inputs.insert(in_id, Arc::clone(&in_arc));
15443
15444        let (result_arc, result_layout) =
15445            PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
15446
15447        // Zero copy — same Arc.
15448        assert!(
15449            Arc::ptr_eq(&result_arc, &in_arc),
15450            "contiguous reshape must zero-copy"
15451        );
15452        assert_eq!(result_layout.shape().dims(), &[3, 2]);
15453        assert!(result_layout.is_contiguous());
15454
15455        // Bytes are unchanged; just reinterpreted as [3, 2].
15456        let guard = result_arc.read().unwrap();
15457        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15458            panic!("expected Cpu storage");
15459        };
15460        assert_eq!(
15461            c.as_slice::<f32>().unwrap(),
15462            &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
15463        );
15464    }
15465
15466    /// E2E: Const + Transpose + Reshape — reshape on a strided
15467    /// input auto-contiguizes the bytes. Output Arc is fresh
15468    /// (NOT the input Arc); the bytes are the materialized
15469    /// transposed layout.
15470    #[test]
15471    fn pipelined_realize_reshape_materializes_when_strided() {
15472        // shape [2, 3]: 1 2 3 / 4 5 6
15473        // Transpose → [3, 2] strided
15474        // Reshape → [6] (forces materialization)
15475        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
15476        let graph = Arc::new(RwLock::new(Graph::new()));
15477        let (in_id, t_id, r_id) = {
15478            let mut g = graph.write().unwrap();
15479            let in_id = g.push(Node {
15480                op: Op::Const,
15481                inputs: vec![],
15482                shape: Shape::from_dims(&[2, 3]),
15483                dtype: DType::F32,
15484            });
15485            let t_id = g.push(Node {
15486                op: Op::Transpose,
15487                inputs: vec![in_id],
15488                shape: Shape::from_dims(&[3, 2]),
15489                dtype: DType::F32,
15490            });
15491            let r_id = g.push(Node {
15492                op: Op::Reshape(Shape::from_dims(&[6])),
15493                inputs: vec![t_id],
15494                shape: Shape::from_dims(&[6]),
15495                dtype: DType::F32,
15496            });
15497            (in_id, t_id, r_id)
15498        };
15499        let _ = t_id;
15500        let mut inputs = StorageCache::new();
15501        let in_arc = Arc::new(RwLock::new(storage));
15502        inputs.insert(in_id, Arc::clone(&in_arc));
15503
15504        let (result_arc, result_layout) =
15505            PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
15506
15507        // Fresh Arc — auto-contiguize allocated new bytes.
15508        assert!(!Arc::ptr_eq(&result_arc, &in_arc));
15509        assert_eq!(result_layout.shape().dims(), &[6]);
15510        assert!(result_layout.is_contiguous());
15511
15512        // Materialized transposed bytes flattened: [1, 4, 2, 5, 3, 6].
15513        let guard = result_arc.read().unwrap();
15514        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15515            panic!("expected Cpu storage");
15516        };
15517        assert_eq!(
15518            c.as_slice::<f32>().unwrap(),
15519            &[1.0, 4.0, 2.0, 5.0, 3.0, 6.0]
15520        );
15521    }
15522
15523    /// E2E: Const + Transpose + SumDim — exercises stage 3
15524    /// (metadata-only Transpose, strided intermediate Layout) +
15525    /// stage 4 (auto-Contiguize before reduce kernel) end-to-end.
15526    /// The transpose makes the intermediate non-contiguous; the
15527    /// reduce wrapper would have failed in stage 2; with stage 4's
15528    /// auto-Contiguize, the kernel sees the materialized contiguous
15529    /// transposed bytes and produces the right answer.
15530    #[test]
15531    fn pipelined_realize_transpose_then_sum_dim_e2e() {
15532        // shape [2, 3]: rows are [1, 2, 3], [4, 5, 6]
15533        // After transpose: shape [3, 2], rows are [1, 4], [2, 5], [3, 6]
15534        // After SumDim(1): shape [3], values [5, 7, 9]
15535        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
15536        let graph = Arc::new(RwLock::new(Graph::new()));
15537        let (in_id, t_id, sum_id) = {
15538            let mut g = graph.write().unwrap();
15539            let in_id = g.push(Node {
15540                op: Op::Const,
15541                inputs: vec![],
15542                shape: Shape::from_dims(&[2, 3]),
15543                dtype: DType::F32,
15544            });
15545            let t_id = g.push(Node {
15546                op: Op::Transpose,
15547                inputs: vec![in_id],
15548                shape: Shape::from_dims(&[3, 2]),
15549                dtype: DType::F32,
15550            });
15551            let sum_id = g.push(Node {
15552                op: Op::SumDim(1),
15553                inputs: vec![t_id],
15554                shape: Shape::from_dims(&[3]),
15555                dtype: DType::F32,
15556            });
15557            // Only the reduce kernel runs on the backend; the
15558            // transpose is metadata-only and doesn't need a target.
15559            g.set_target_backend(sum_id, BackendId::Cpu);
15560            (in_id, t_id, sum_id)
15561        };
15562        let _ = t_id;
15563        let mut inputs = StorageCache::new();
15564        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
15565
15566        let (result_arc, result_layout) =
15567            PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
15568
15569        // The reduce output is contiguous (kernel-produced).
15570        assert_eq!(result_layout.shape().dims(), &[3]);
15571        assert!(result_layout.is_contiguous());
15572
15573        let guard = result_arc.read().unwrap();
15574        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15575            panic!("expected Cpu storage");
15576        };
15577        let typed: &[f32] = c.as_slice().unwrap();
15578        assert_eq!(typed, &[5.0, 7.0, 9.0]);
15579    }
15580
15581    /// E2E: Const + BroadcastTo + Add — broadcast intermediate
15582    /// auto-contiguizes for the Add kernel; the result is the
15583    /// expected sum.
15584    #[test]
15585    fn pipelined_realize_broadcast_then_add_e2e() {
15586        // shape [3]: [10, 20, 30]
15587        // BroadcastTo [2, 3]: [[10, 20, 30], [10, 20, 30]]
15588        // Plus shape [2, 3]: [[1, 2, 3], [4, 5, 6]]
15589        // Result: [[11, 22, 33], [14, 25, 36]]
15590        let bc_input = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
15591        let plus_input = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
15592        let graph = Arc::new(RwLock::new(Graph::new()));
15593        let (bc_in_id, plus_in_id, b_id, add_id) = {
15594            let mut g = graph.write().unwrap();
15595            let bc_in = g.push(Node {
15596                op: Op::Const,
15597                inputs: vec![],
15598                shape: Shape::from_dims(&[3]),
15599                dtype: DType::F32,
15600            });
15601            let plus_in = g.push(Node {
15602                op: Op::Const,
15603                inputs: vec![],
15604                shape: Shape::from_dims(&[2, 3]),
15605                dtype: DType::F32,
15606            });
15607            let b = g.push(Node {
15608                op: Op::BroadcastTo(Shape::from_dims(&[2, 3])),
15609                inputs: vec![bc_in],
15610                shape: Shape::from_dims(&[2, 3]),
15611                dtype: DType::F32,
15612            });
15613            let add = g.push(Node {
15614                op: Op::Add,
15615                inputs: vec![b, plus_in],
15616                shape: Shape::from_dims(&[2, 3]),
15617                dtype: DType::F32,
15618            });
15619            g.set_target_backend(add, BackendId::Cpu);
15620            (bc_in, plus_in, b, add)
15621        };
15622        let _ = b_id;
15623        let mut inputs = StorageCache::new();
15624        inputs.insert(bc_in_id, Arc::new(RwLock::new(bc_input)));
15625        inputs.insert(plus_in_id, Arc::new(RwLock::new(plus_input)));
15626
15627        let (result_arc, _result_layout) =
15628            PipelinedExecutor::realize(graph, add_id, inputs).expect("realize");
15629        let guard = result_arc.read().unwrap();
15630        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15631            panic!("expected Cpu storage");
15632        };
15633        let typed: &[f32] = c.as_slice().unwrap();
15634        assert_eq!(typed, &[11.0, 22.0, 33.0, 14.0, 25.0, 36.0]);
15635    }
15636
15637    /// E2E: Const + SumDim — verifies that `OpParams::Reduce`
15638    /// flows from the graph (input shape via `op_to_op_params`)
15639    /// through compile_one and reaches the reduce kernel.
15640    #[test]
15641    fn pipelined_realize_sum_dim() {
15642        // shape [2, 3]; reduce dim 1 → output shape [2]
15643        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
15644        let graph = Arc::new(RwLock::new(Graph::new()));
15645        let (in_id, sum_id) = {
15646            let mut g = graph.write().unwrap();
15647            let in_id = g.push(Node {
15648                op: Op::Const,
15649                inputs: vec![],
15650                shape: Shape::from_dims(&[2, 3]),
15651                dtype: DType::F32,
15652            });
15653            let sum_id = g.push(Node {
15654                op: Op::SumDim(1),
15655                inputs: vec![in_id],
15656                shape: Shape::from_dims(&[2]),
15657                dtype: DType::F32,
15658            });
15659            g.set_target_backend(sum_id, BackendId::Cpu);
15660            (in_id, sum_id)
15661        };
15662        let mut inputs = StorageCache::new();
15663        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
15664
15665        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
15666        let guard = result_arc.read().unwrap();
15667        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
15668            let typed: &[f32] = c.as_slice().unwrap();
15669            assert_eq!(typed, &[6.0, 15.0]);
15670        }
15671    }
15672
15673    /// E2E: SumAll on a rank-3 input, exercising the all-dims branch
15674    /// of `op_to_op_params` (every dim reduced, rank-0 output).
15675    #[test]
15676    fn pipelined_realize_sum_all_rank3() {
15677        let data: Vec<f32> = (1..=24).map(|x| x as f32).collect();
15678        let storage = fuel_memory::from_slice_cpu(&data);
15679        let graph = Arc::new(RwLock::new(Graph::new()));
15680        let (in_id, sum_id) = {
15681            let mut g = graph.write().unwrap();
15682            let in_id = g.push(Node {
15683                op: Op::Const,
15684                inputs: vec![],
15685                shape: Shape::from_dims(&[2, 3, 4]),
15686                dtype: DType::F32,
15687            });
15688            let sum_id = g.push(Node {
15689                op: Op::SumAll,
15690                inputs: vec![in_id],
15691                shape: Shape::from_dims(&[]),
15692                dtype: DType::F32,
15693            });
15694            g.set_target_backend(sum_id, BackendId::Cpu);
15695            (in_id, sum_id)
15696        };
15697        let mut inputs = StorageCache::new();
15698        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
15699
15700        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
15701        let guard = result_arc.read().unwrap();
15702        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
15703            let typed: &[f32] = c.as_slice().unwrap();
15704            // 1 + 2 + ... + 24 = 300
15705            assert_eq!(typed, &[300.0]);
15706        }
15707    }
15708
15709    /// E2E: MaxDim + MeanDim chained — verifies all four reduce
15710    /// OpKinds reach their wrappers via the OpParams plumbing.
15711    #[test]
15712    fn pipelined_realize_max_then_mean() {
15713        // shape [2, 3], MaxDim(1) → [2], MeanDim(0) → []
15714        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 9.0, 3.0, 4.0, 2.0, 8.0]);
15715        let graph = Arc::new(RwLock::new(Graph::new()));
15716        let (in_id, mean_id) = {
15717            let mut g = graph.write().unwrap();
15718            let in_id = g.push(Node {
15719                op: Op::Const,
15720                inputs: vec![],
15721                shape: Shape::from_dims(&[2, 3]),
15722                dtype: DType::F32,
15723            });
15724            let max_id = g.push(Node {
15725                op: Op::MaxDim(1),
15726                inputs: vec![in_id],
15727                shape: Shape::from_dims(&[2]),
15728                dtype: DType::F32,
15729            });
15730            let mean_id = g.push(Node {
15731                op: Op::MeanDim(0),
15732                inputs: vec![max_id],
15733                shape: Shape::from_dims(&[]),
15734                dtype: DType::F32,
15735            });
15736            g.set_target_backend(max_id, BackendId::Cpu);
15737            g.set_target_backend(mean_id, BackendId::Cpu);
15738            (in_id, mean_id)
15739        };
15740        let mut inputs = StorageCache::new();
15741        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
15742
15743        let (result_arc, _) = PipelinedExecutor::realize(graph, mean_id, inputs).expect("realize");
15744        let guard = result_arc.read().unwrap();
15745        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
15746            let typed: &[f32] = c.as_slice().unwrap();
15747            // MaxDim(1) on [[1,9,3],[4,2,8]] = [9, 8]; MeanDim(0) = 8.5
15748            assert_eq!(typed, &[8.5]);
15749        }
15750    }
15751
15752    /// E2E: Sigmoid + Silu — exercises two of the more compositional
15753    /// new unary kernels through the pipelined executor. Verifies
15754    /// the additional `op_to_op_kind` mappings reach the right
15755    /// dispatch wrappers.
15756    #[test]
15757    fn pipelined_realize_sigmoid_then_silu() {
15758        let storage = fuel_memory::from_slice_cpu(&[0.0_f32, 1.0, -1.0]);
15759        let graph = Arc::new(RwLock::new(Graph::new()));
15760        let (in_id, sig_id, silu_id) = {
15761            let mut g = graph.write().unwrap();
15762            let in_id = g.push(Node {
15763                op: Op::Const,
15764                inputs: vec![],
15765                shape: Shape::from_dims(&[3]),
15766                dtype: DType::F32,
15767            });
15768            let sig_id = g.push(Node {
15769                op: Op::Sigmoid,
15770                inputs: vec![in_id],
15771                shape: Shape::from_dims(&[3]),
15772                dtype: DType::F32,
15773            });
15774            // Silu of the sigmoid output — chains to confirm cache flow.
15775            let silu_id = g.push(Node {
15776                op: Op::Silu,
15777                inputs: vec![sig_id],
15778                shape: Shape::from_dims(&[3]),
15779                dtype: DType::F32,
15780            });
15781            g.set_target_backend(sig_id, BackendId::Cpu);
15782            g.set_target_backend(silu_id, BackendId::Cpu);
15783            (in_id, sig_id, silu_id)
15784        };
15785        let _ = sig_id;
15786        let mut inputs = StorageCache::new();
15787        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
15788
15789        let (result_arc, _) = PipelinedExecutor::realize(graph, silu_id, inputs).expect("realize");
15790        let guard = result_arc.read().unwrap();
15791        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
15792            let typed: &[f32] = c.as_slice().unwrap();
15793            // sigmoid(0) = 0.5; silu(0.5) = 0.5 * sigmoid(0.5) ≈ 0.3112
15794            assert!((typed[0] - 0.5 * (1.0 / (1.0 + (-0.5_f32).exp()))).abs() < 1e-6);
15795        }
15796    }
15797
15798    /// E2E: chained unary ops — Const + Sqr + Sqrt should be a noop
15799    /// for non-negative inputs. Exercises the cache reuse path.
15800    #[test]
15801    fn pipelined_realize_chained_unary_sqr_then_sqrt() {
15802        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 4.0, 9.0]);
15803        let graph = Arc::new(RwLock::new(Graph::new()));
15804        let (in_id, sqrt_id) = {
15805            let mut g = graph.write().unwrap();
15806            let in_id = g.push(Node {
15807                op: Op::Const,
15808                inputs: vec![],
15809                shape: Shape::from_dims(&[3]),
15810                dtype: DType::F32,
15811            });
15812            let sqr_id = g.push(Node {
15813                op: Op::Sqr,
15814                inputs: vec![in_id],
15815                shape: Shape::from_dims(&[3]),
15816                dtype: DType::F32,
15817            });
15818            let sqrt_id = g.push(Node {
15819                op: Op::Sqrt,
15820                inputs: vec![sqr_id],
15821                shape: Shape::from_dims(&[3]),
15822                dtype: DType::F32,
15823            });
15824            g.set_target_backend(sqr_id, BackendId::Cpu);
15825            g.set_target_backend(sqrt_id, BackendId::Cpu);
15826            (in_id, sqrt_id)
15827        };
15828        let mut inputs = StorageCache::new();
15829        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
15830
15831        let (result_arc, _) = PipelinedExecutor::realize(graph, sqrt_id, inputs).expect("realize");
15832        let guard = result_arc.read().unwrap();
15833        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
15834            let typed: &[f32] = c.as_slice().unwrap();
15835            // sqrt(sqr(x)) == |x| == x for non-negative inputs.
15836            assert_eq!(typed, &[1.0, 4.0, 9.0]);
15837        }
15838    }
15839
15840    /// Multi-stage pipelined: Const + Const + Add + Add (chain of
15841    /// two adds). Tests that work items are processed in topo order
15842    /// and intermediate results are cached and reused.
15843    #[test]
15844    fn pipelined_realize_chained_adds() {
15845        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
15846        let b_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
15847        let c_storage = fuel_memory::from_slice_cpu(&[100.0_f32, 200.0]);
15848
15849        let graph = Arc::new(RwLock::new(Graph::new()));
15850        let (a_id, b_id, c_id, ab_id, abc_id) = {
15851            let mut g = graph.write().unwrap();
15852            let a = g.push(Node {
15853                op: Op::Const,
15854                inputs: vec![],
15855                shape: Shape::from_dims(&[2]),
15856                dtype: DType::F32,
15857            });
15858            let b = g.push(Node {
15859                op: Op::Const,
15860                inputs: vec![],
15861                shape: Shape::from_dims(&[2]),
15862                dtype: DType::F32,
15863            });
15864            let c = g.push(Node {
15865                op: Op::Const,
15866                inputs: vec![],
15867                shape: Shape::from_dims(&[2]),
15868                dtype: DType::F32,
15869            });
15870            let ab = g.push(Node {
15871                op: Op::Add,
15872                inputs: vec![a, b],
15873                shape: Shape::from_dims(&[2]),
15874                dtype: DType::F32,
15875            });
15876            let abc = g.push(Node {
15877                op: Op::Add,
15878                inputs: vec![ab, c],
15879                shape: Shape::from_dims(&[2]),
15880                dtype: DType::F32,
15881            });
15882            g.set_target_backend(ab, BackendId::Cpu);
15883            g.set_target_backend(abc, BackendId::Cpu);
15884            (a, b, c, ab, abc)
15885        };
15886
15887        let mut inputs = StorageCache::new();
15888        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
15889        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
15890        inputs.insert(c_id, Arc::new(RwLock::new(c_storage)));
15891
15892        let (result_arc, _) = PipelinedExecutor::realize(graph, abc_id, inputs).expect("realize");
15893        // Suppress unused warning for the intermediate id.
15894        let _ = ab_id;
15895
15896        let guard = result_arc.read().unwrap();
15897        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
15898            let typed: &[f32] = c.as_slice().unwrap();
15899            // (1+10) + 100 = 111;  (2+20) + 200 = 222.
15900            assert_eq!(typed, &[111.0, 222.0]);
15901        }
15902    }
15903
15904    /// E2E: triu(diagonal=0) on a 3×3 matrix.
15905    /// Input:  [1 2 3 / 4 5 6 / 7 8 9]
15906    /// Output: [1 2 3 / 0 5 6 / 0 0 9]
15907    #[test]
15908    fn pipelined_realize_triu_3x3_diag0() {
15909        let storage =
15910            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
15911        let graph = Arc::new(RwLock::new(Graph::new()));
15912        let (in_id, out_id) = {
15913            let mut g = graph.write().unwrap();
15914            let in_id = g.push(Node {
15915                op: Op::Const,
15916                inputs: vec![],
15917                shape: Shape::from_dims(&[3, 3]),
15918                dtype: DType::F32,
15919            });
15920            let out_id = g.push(Node {
15921                op: Op::Triu { diagonal: 0 },
15922                inputs: vec![in_id],
15923                shape: Shape::from_dims(&[3, 3]),
15924                dtype: DType::F32,
15925            });
15926            g.set_target_backend(out_id, BackendId::Cpu);
15927            (in_id, out_id)
15928        };
15929        let mut inputs = StorageCache::new();
15930        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
15931        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
15932        let guard = result_arc.read().unwrap();
15933        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15934            panic!("expected Cpu storage");
15935        };
15936        let out: &[f32] = c.as_slice().unwrap();
15937        assert_eq!(out, &[1.0, 2.0, 3.0, 0.0, 5.0, 6.0, 0.0, 0.0, 9.0,]);
15938    }
15939
15940    /// E2E: tril(diagonal=0) on a 3×3 matrix — the canonical causal mask.
15941    /// Output: [1 0 0 / 4 5 0 / 7 8 9]
15942    #[test]
15943    fn pipelined_realize_tril_3x3_diag0_causal_mask() {
15944        let storage =
15945            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
15946        let graph = Arc::new(RwLock::new(Graph::new()));
15947        let (in_id, out_id) = {
15948            let mut g = graph.write().unwrap();
15949            let in_id = g.push(Node {
15950                op: Op::Const,
15951                inputs: vec![],
15952                shape: Shape::from_dims(&[3, 3]),
15953                dtype: DType::F32,
15954            });
15955            let out_id = g.push(Node {
15956                op: Op::Tril { diagonal: 0 },
15957                inputs: vec![in_id],
15958                shape: Shape::from_dims(&[3, 3]),
15959                dtype: DType::F32,
15960            });
15961            g.set_target_backend(out_id, BackendId::Cpu);
15962            (in_id, out_id)
15963        };
15964        let mut inputs = StorageCache::new();
15965        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
15966        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
15967        let guard = result_arc.read().unwrap();
15968        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15969            panic!("expected Cpu storage");
15970        };
15971        let out: &[f32] = c.as_slice().unwrap();
15972        assert_eq!(out, &[1.0, 0.0, 0.0, 4.0, 5.0, 0.0, 7.0, 8.0, 9.0,]);
15973    }
15974
15975    /// E2E: log_softmax over a 2×3 input. Rows are [1,2,3] and [3,2,1].
15976    /// log_softmax(row) = row - max - log(sum exp(row - max)).
15977    /// Row 0: max=3, exp(-2)+exp(-1)+exp(0) = 0.135+0.368+1.0 = 1.503;
15978    ///        log(1.503) ≈ 0.4076; out = [1-3-0.4076, 2-3-0.4076, 3-3-0.4076]
15979    ///                              = [-2.4076, -1.4076, -0.4076]
15980    /// Row 1 is row 0 reversed: [-0.4076, -1.4076, -2.4076].
15981    #[test]
15982    fn pipelined_realize_log_softmax_last_dim() {
15983        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 3.0, 2.0, 1.0]);
15984        let graph = Arc::new(RwLock::new(Graph::new()));
15985        let (in_id, out_id) = {
15986            let mut g = graph.write().unwrap();
15987            let in_id = g.push(Node {
15988                op: Op::Const,
15989                inputs: vec![],
15990                shape: Shape::from_dims(&[2, 3]),
15991                dtype: DType::F32,
15992            });
15993            let out_id = g.push(Node {
15994                op: Op::LogSoftmaxLastDim,
15995                inputs: vec![in_id],
15996                shape: Shape::from_dims(&[2, 3]),
15997                dtype: DType::F32,
15998            });
15999            g.set_target_backend(out_id, BackendId::Cpu);
16000            (in_id, out_id)
16001        };
16002        let mut inputs = StorageCache::new();
16003        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
16004        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
16005        let guard = result_arc.read().unwrap();
16006        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16007            panic!("expected Cpu storage");
16008        };
16009        let out: &[f32] = c.as_slice().unwrap();
16010        let expected = [
16011            -2.407_606,
16012            -1.4076059,
16013            -0.40760595_f32,
16014            -0.40760595,
16015            -1.4076059,
16016            -2.407_606,
16017        ];
16018        for (a, b) in out.iter().zip(expected.iter()) {
16019            assert!((a - b).abs() < 1e-5, "log_softmax mismatch: {a} vs {b}");
16020        }
16021        // The exp() of the output should sum to 1 per row.
16022        for row in out.chunks(3) {
16023            let sum: f32 = row.iter().map(|x| x.exp()).sum();
16024            assert!(
16025                (sum - 1.0).abs() < 1e-5,
16026                "softmax(log_softmax) row sum != 1: {sum}"
16027            );
16028        }
16029    }
16030
16031    // --- side-effect roots + destructive cleanup (9c Phase B) -----
16032
16033    /// Side-effect roots get merged into the realize walk even when
16034    /// not reachable from the user's targets. The production trigger
16035    /// is `Op::Release` (emitted by `ResidencyEvictionRule`); this
16036    /// test uses that exact shape.
16037    ///
16038    /// Graph: Const(a) + Const(b) → Add (user target); separate
16039    /// Const(c) → Release(c) (side-effect root, not reachable from
16040    /// Add). After realize_many on `[add]`, the Add should be in the
16041    /// output AND the Release should have fired (verified by the
16042    /// fact that realize succeeded — Op::Release in the walk used to
16043    /// fail compilation pre-Phase B+).
16044    #[test]
16045    fn pipelined_realize_merges_op_release_side_effect_root() {
16046        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
16047        let b = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
16048        let c = fuel_memory::from_slice_cpu(&[100.0_f32, 200.0]);
16049        let graph = Arc::new(RwLock::new(Graph::new()));
16050        let (a_id, b_id, c_id, add_id, release_id) = {
16051            let mut g = graph.write().unwrap();
16052            let a = g.push(Node {
16053                op: Op::Const,
16054                inputs: vec![],
16055                shape: Shape::from_dims(&[2]),
16056                dtype: DType::F32,
16057            });
16058            let b = g.push(Node {
16059                op: Op::Const,
16060                inputs: vec![],
16061                shape: Shape::from_dims(&[2]),
16062                dtype: DType::F32,
16063            });
16064            // c is NOT reachable from add; its Release IS marked as
16065            // a side-effect root.
16066            let c = g.push(Node {
16067                op: Op::Const,
16068                inputs: vec![],
16069                shape: Shape::from_dims(&[2]),
16070                dtype: DType::F32,
16071            });
16072            let add = g.push(Node {
16073                op: Op::Add,
16074                inputs: vec![a, b],
16075                shape: Shape::from_dims(&[2]),
16076                dtype: DType::F32,
16077            });
16078            // Production shape: Op::Release on c, marked as
16079            // side-effect root so it fires even though no graph
16080            // node reads its output.
16081            let release = g.push(Node {
16082                op: Op::Release,
16083                inputs: vec![c],
16084                shape: Shape::from_dims(&[0]),
16085                dtype: DType::F32,
16086            });
16087            g.set_target_backend(add, BackendId::Cpu);
16088            g.set_target_backend(release, BackendId::Cpu);
16089            g.add_side_effect_root(release);
16090            (a, b, c, add, release)
16091        };
16092        let mut inputs = StorageCache::new();
16093        inputs.insert(a_id, Arc::new(RwLock::new(a)));
16094        inputs.insert(b_id, Arc::new(RwLock::new(b)));
16095        let c_arc = Arc::new(RwLock::new(c));
16096        let c_arc_external = Arc::clone(&c_arc);
16097        inputs.insert(c_id, c_arc);
16098
16099        // Only `add` is requested. The Release on c is a side-effect
16100        // root that must still fire.
16101        let out = PipelinedExecutor::realize_many(graph, &[add_id], inputs).expect("realize_many");
16102        assert_eq!(out.len(), 1);
16103        let add_guard = out[0].0.read().unwrap();
16104        let fuel_memory::BackendStorage::Cpu(arr) = &add_guard.inner else {
16105            panic!()
16106        };
16107        assert_eq!(arr.as_slice::<f32>().unwrap(), &[11.0, 22.0]);
16108
16109        // The Release's destructive_input cleanup dropped the
16110        // cache's Arc to c. The only Arc to c that survives is the
16111        // external one this test holds — confirms the eviction
16112        // actually freed the cache's reference.
16113        assert_eq!(
16114            Arc::strong_count(&c_arc_external),
16115            1,
16116            "Op::Release should evict the cache's Arc to its source; \
16117             only the test's external clone should remain",
16118        );
16119        let _ = release_id;
16120    }
16121
16122    /// `compile_one` emits a `WorkItemKind::ReleaseMarker` for
16123    /// `Op::Release` with `destructive_input = Some(0)`. Verify
16124    /// the WorkItem shape via a direct compile_one call.
16125    #[test]
16126    fn compile_one_emits_release_marker_with_destructive_input() {
16127        let graph_rc = Arc::new(RwLock::new(Graph::new()));
16128        let (src_id, release_id) = {
16129            let mut g = graph_rc.write().unwrap();
16130            let src = g.push(Node {
16131                op: Op::Const,
16132                inputs: vec![],
16133                shape: Shape::from_dims(&[2]),
16134                dtype: DType::F32,
16135            });
16136            let release = g.push(Node {
16137                op: Op::Release,
16138                inputs: vec![src],
16139                shape: Shape::from_dims(&[0]),
16140                dtype: DType::F32,
16141            });
16142            g.set_target_backend(release, BackendId::Cpu);
16143            (src, release)
16144        };
16145        let g = graph_rc.read().unwrap();
16146        let bindings = crate::dispatch::global_bindings();
16147        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
16148        let item = compile_one(
16149            &g,
16150            release_id,
16151            &mut layout_cache,
16152            &bindings,
16153            &SymEnv::default(),
16154        )
16155        .expect("compile_one Op::Release");
16156        assert!(matches!(item.kind, WorkItemKind::ReleaseMarker));
16157        assert_eq!(item.destructive_input, Some(0));
16158        assert_eq!(item.inputs, vec![src_id]);
16159        assert_eq!(
16160            item.elem_count, 0,
16161            "Release output is the zero-element marker"
16162        );
16163    }
16164
16165    // --- Op::Move (executor-unification Session 1, gap 13) --------
16166
16167    /// `compile_one` emits a `WorkItemKind::Move` for `Op::Move` with
16168    /// `destructive_input = Some(0)` and a resolved transfer kernel
16169    /// (binding-table lookup at `(OpKind::Copy, [dt, dt], source
16170    /// backend)` — Move shares Op::Copy's data-movement kernel).
16171    #[test]
16172    fn compile_one_emits_move_with_destructive_input() {
16173        let graph_rc = Arc::new(RwLock::new(Graph::new()));
16174        let (src_id, move_id) = {
16175            let mut g = graph_rc.write().unwrap();
16176            let src = g.push(Node {
16177                op: Op::Const,
16178                inputs: vec![],
16179                shape: Shape::from_dims(&[2]),
16180                dtype: DType::F32,
16181            });
16182            let mv = g.push(Node {
16183                op: Op::Move {
16184                    target: DeviceLocation::Cpu,
16185                },
16186                inputs: vec![src],
16187                shape: Shape::from_dims(&[2]),
16188                dtype: DType::F32,
16189            });
16190            g.set_target_backend(mv, BackendId::Cpu);
16191            (src, mv)
16192        };
16193        let g = graph_rc.read().unwrap();
16194        let bindings = crate::dispatch::global_bindings();
16195        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
16196        let item = compile_one(
16197            &g,
16198            move_id,
16199            &mut layout_cache,
16200            &bindings,
16201            &SymEnv::default(),
16202        )
16203        .expect("compile_one Op::Move");
16204        assert!(matches!(
16205            item.kind,
16206            WorkItemKind::Move {
16207                target_location: DeviceLocation::Cpu
16208            },
16209        ));
16210        assert_eq!(item.destructive_input, Some(0), "Move destroys its source");
16211        assert_eq!(item.inputs, vec![src_id]);
16212        assert!(
16213            item.compiled.is_some(),
16214            "Move resolves a transfer kernel at (OpKind::Copy, [dt, dt], source backend)",
16215        );
16216    }
16217
16218    // --- runtime fused op (JIT-adopted Tier-2 kernel) --------------
16219
16220    /// `compile_one` resolves an `Op::Fused(fid, Runtime)` node with
16221    /// `fid.is_runtime()` from the runtime-kernel sidecar (never the
16222    /// binding table): `WorkItemKind::Kernel`, `compiled.op ==
16223    /// OpKind::RuntimeFused`, and the kernel pointer is exactly the one
16224    /// `adopt_runtime_fused` bound.
16225    #[test]
16226    fn compile_one_resolves_runtime_fused_from_the_sidecar() {
16227        fn sentinel_kernel(
16228            _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
16229            _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
16230            _layouts: &[Layout],
16231            _params: &crate::kernel::OpParams,
16232        ) -> Result<()> {
16233            Ok(())
16234        }
16235        // A region shape unique to this test (process-global sidecar; see
16236        // runtime_fused_pathfinder's tests for the collision rationale).
16237        let region = fuel_graph::jit::PatternNode::Op {
16238            op: fuel_graph::jit::OpTag::Exp,
16239            attrs: fuel_graph::jit::OpAttrs::default(),
16240            operands: vec![fuel_graph::jit::PatternNode::Op {
16241                op: fuel_graph::jit::OpTag::Sub,
16242                attrs: fuel_graph::jit::OpAttrs::default(),
16243                operands: vec![
16244                    fuel_graph::jit::PatternNode::Bind { index: 0 },
16245                    fuel_graph::jit::PatternNode::Bind { index: 1 },
16246                ],
16247            }],
16248        };
16249        let rid = crate::runtime_fused_kernels::adopt_runtime_fused(
16250            "test::compile_one::exp_sub",
16251            region,
16252            sentinel_kernel as crate::kernel::KernelRef,
16253            vec![DType::F32, DType::F32, DType::F32],
16254            BackendId::Cpu,
16255        )
16256        .expect("registrable region");
16257
16258        let graph_rc = Arc::new(RwLock::new(Graph::new()));
16259        let fused_id = {
16260            let mut g = graph_rc.write().unwrap();
16261            let s = Shape::from_dims(&[4]);
16262            let a = g.push(Node {
16263                op: Op::Const,
16264                inputs: vec![],
16265                shape: s.clone(),
16266                dtype: DType::F32,
16267            });
16268            let b = g.push(Node {
16269                op: Op::Const,
16270                inputs: vec![],
16271                shape: s.clone(),
16272                dtype: DType::F32,
16273            });
16274            let fused = g.push(Node {
16275                op: Op::Fused(
16276                    rid,
16277                    fuel_graph::registry::FusedOpParams::Runtime {
16278                        scalars: Vec::new(),
16279                    },
16280                ),
16281                inputs: vec![a, b],
16282                shape: s,
16283                dtype: DType::F32,
16284            });
16285            // The arm emitter pins the backend; mirror that here.
16286            g.set_target_backend(fused, BackendId::Cpu);
16287            fused
16288        };
16289        let g = graph_rc.read().unwrap();
16290        let bindings = crate::dispatch::global_bindings();
16291        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
16292        let item = compile_one(
16293            &g,
16294            fused_id,
16295            &mut layout_cache,
16296            &bindings,
16297            &SymEnv::default(),
16298        )
16299        .expect("compile_one runtime fused op");
16300        assert!(matches!(item.kind, WorkItemKind::Kernel));
16301        let compiled = item.compiled.expect("resolved a kernel");
16302        assert_eq!(compiled.op, fuel_ir::dispatch::OpKind::RuntimeFused);
16303        assert_eq!(compiled.backend, BackendId::Cpu);
16304        assert!(
16305            std::ptr::fn_addr_eq(compiled.kernel, sentinel_kernel as crate::kernel::KernelRef),
16306            "the kernel pointer is exactly the adopted one",
16307        );
16308        assert!(
16309            layout_cache.contains_key(&fused_id),
16310            "output layout cached for consumers"
16311        );
16312    }
16313
16314    /// The dtype belt-and-suspenders guard: an `Op::Fused(runtime)` node
16315    /// whose per-operand dtypes disagree with the adopted kernel's tuple is
16316    /// a typed error, not a silent wrong-kernel dispatch.
16317    #[test]
16318    fn compile_one_rejects_runtime_fused_dtype_mismatch() {
16319        fn noop_kernel(
16320            _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
16321            _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
16322            _layouts: &[Layout],
16323            _params: &crate::kernel::OpParams,
16324        ) -> Result<()> {
16325            Ok(())
16326        }
16327        let region = fuel_graph::jit::PatternNode::Op {
16328            op: fuel_graph::jit::OpTag::Log,
16329            attrs: fuel_graph::jit::OpAttrs::default(),
16330            operands: vec![fuel_graph::jit::PatternNode::Op {
16331                op: fuel_graph::jit::OpTag::Maximum,
16332                attrs: fuel_graph::jit::OpAttrs::default(),
16333                operands: vec![
16334                    fuel_graph::jit::PatternNode::Bind { index: 0 },
16335                    fuel_graph::jit::PatternNode::Bind { index: 1 },
16336                ],
16337            }],
16338        };
16339        // Adopted for F32 operands…
16340        let rid = crate::runtime_fused_kernels::adopt_runtime_fused(
16341            "test::compile_one::log_maximum",
16342            region,
16343            noop_kernel as crate::kernel::KernelRef,
16344            vec![DType::F32, DType::F32, DType::F32],
16345            BackendId::Cpu,
16346        )
16347        .expect("registrable region");
16348
16349        let graph_rc = Arc::new(RwLock::new(Graph::new()));
16350        let fused_id = {
16351            let mut g = graph_rc.write().unwrap();
16352            let s = Shape::from_dims(&[4]);
16353            // …but the node's operands are F64.
16354            let a = g.push(Node {
16355                op: Op::Const,
16356                inputs: vec![],
16357                shape: s.clone(),
16358                dtype: DType::F64,
16359            });
16360            let b = g.push(Node {
16361                op: Op::Const,
16362                inputs: vec![],
16363                shape: s.clone(),
16364                dtype: DType::F64,
16365            });
16366            let fused = g.push(Node {
16367                op: Op::Fused(
16368                    rid,
16369                    fuel_graph::registry::FusedOpParams::Runtime {
16370                        scalars: Vec::new(),
16371                    },
16372                ),
16373                inputs: vec![a, b],
16374                shape: s,
16375                dtype: DType::F64,
16376            });
16377            g.set_target_backend(fused, BackendId::Cpu);
16378            fused
16379        };
16380        let g = graph_rc.read().unwrap();
16381        let bindings = crate::dispatch::global_bindings();
16382        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
16383        let err = match compile_one(
16384            &g,
16385            fused_id,
16386            &mut layout_cache,
16387            &bindings,
16388            &SymEnv::default(),
16389        ) {
16390            Ok(_) => panic!("dtype mismatch must be a typed error"),
16391            Err(e) => e,
16392        };
16393        // Post-fold, the dtype tuple IS the binding key: a mismatch is the
16394        // same honest `NoBackendForOp` miss as an absent kernel — reported
16395        // with the `RuntimeFused` diagnostic op tag, never a wrong-kernel bind.
16396        assert!(
16397            matches!(
16398                err,
16399                fuel_ir::Error::NoBackendForOp {
16400                    op: fuel_ir::dispatch::OpKind::RuntimeFused,
16401                    ..
16402                }
16403            ),
16404            "a dtype mismatch is an honest binding miss: {err}",
16405        );
16406    }
16407
16408    /// A runtime fused node carrying live `Runtime { scalars }` compiles with
16409    /// `OpParams::JitScalars` — the launch channel for the kernel's trailing
16410    /// `p{i}` args. (A param-free node keeps `OpParams::None`, covered by
16411    /// `compile_one_resolves_runtime_fused_from_the_sidecar`.)
16412    #[test]
16413    fn compile_one_maps_runtime_scalars_to_jit_scalars() {
16414        fn noop_kernel(
16415            _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
16416            _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
16417            _layouts: &[Layout],
16418            _params: &crate::kernel::OpParams,
16419        ) -> Result<()> {
16420            Ok(())
16421        }
16422        // Unique slot-template region (process-global sidecar).
16423        let region = fuel_graph::jit::PatternNode::Op {
16424            op: fuel_graph::jit::OpTag::Floor,
16425            attrs: fuel_graph::jit::OpAttrs::default(),
16426            operands: vec![fuel_graph::jit::PatternNode::Op {
16427                op: fuel_graph::jit::OpTag::MulScalar,
16428                attrs: fuel_graph::jit::OpAttrs::default(), // open slot
16429                operands: vec![fuel_graph::jit::PatternNode::Bind { index: 0 }],
16430            }],
16431        };
16432        let rid = crate::runtime_fused_kernels::adopt_runtime_fused(
16433            "test::compile_one::floor_mul_scalar",
16434            region,
16435            noop_kernel as crate::kernel::KernelRef,
16436            vec![DType::F32, DType::F32],
16437            BackendId::Cpu,
16438        )
16439        .expect("slot template registrable");
16440
16441        let graph_rc = Arc::new(RwLock::new(Graph::new()));
16442        let fused_id = {
16443            let mut g = graph_rc.write().unwrap();
16444            let s = Shape::from_dims(&[4]);
16445            let x = g.push(Node {
16446                op: Op::Const,
16447                inputs: vec![],
16448                shape: s.clone(),
16449                dtype: DType::F32,
16450            });
16451            let fused = g.push(Node {
16452                op: Op::Fused(
16453                    rid,
16454                    fuel_graph::registry::FusedOpParams::Runtime {
16455                        scalars: vec![3.5, -1.25],
16456                    },
16457                ),
16458                inputs: vec![x],
16459                shape: s,
16460                dtype: DType::F32,
16461            });
16462            g.set_target_backend(fused, BackendId::Cpu);
16463            fused
16464        };
16465        let g = graph_rc.read().unwrap();
16466        let bindings = crate::dispatch::global_bindings();
16467        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
16468        let item = compile_one(
16469            &g,
16470            fused_id,
16471            &mut layout_cache,
16472            &bindings,
16473            &SymEnv::default(),
16474        )
16475        .expect("compile_one runtime fused op with scalars");
16476        let compiled = item.compiled.expect("resolved a kernel");
16477        assert!(
16478            matches!(
16479                &compiled.op_params,
16480                crate::kernel::OpParams::JitScalars { scalars } if scalars == &vec![3.5, -1.25]
16481            ),
16482            "Runtime scalars ride into OpParams::JitScalars, got {:?}",
16483            compiled.op_params,
16484        );
16485    }
16486
16487    /// Move-to-same-device is the degenerate case: per the legacy
16488    /// `GraphExecutor` contract (`Op::Copy | Op::Move` shared arm →
16489    /// `backend.copy_to`) it is a plain copy — fresh storage on the
16490    /// same device, data intact — and the source is still evicted
16491    /// afterward (destructive semantics don't depend on the devices
16492    /// differing).
16493    #[test]
16494    fn pipelined_op_move_same_device_is_plain_copy() {
16495        let src = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
16496        let graph = Arc::new(RwLock::new(Graph::new()));
16497        let (src_id, move_id) = {
16498            let mut g = graph.write().unwrap();
16499            let src = g.push(Node {
16500                op: Op::Const,
16501                inputs: vec![],
16502                shape: Shape::from_dims(&[4]),
16503                dtype: DType::F32,
16504            });
16505            let mv = g.push(Node {
16506                op: Op::Move {
16507                    target: DeviceLocation::Cpu,
16508                },
16509                inputs: vec![src],
16510                shape: Shape::from_dims(&[4]),
16511                dtype: DType::F32,
16512            });
16513            g.set_target_backend(mv, BackendId::Cpu);
16514            (src, mv)
16515        };
16516        let src_arc = Arc::new(RwLock::new(src));
16517        let src_arc_external = Arc::clone(&src_arc);
16518        let mut inputs = StorageCache::new();
16519        inputs.insert(src_id, src_arc);
16520
16521        let (out, layout) =
16522            PipelinedExecutor::realize(graph, move_id, inputs).expect("realize Op::Move");
16523        let guard = out.read().unwrap();
16524        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16525            panic!()
16526        };
16527        assert_eq!(
16528            c.as_slice::<f32>().unwrap(),
16529            &[1.0, 2.0, 3.0, 4.0],
16530            "Op::Move output should carry input's data to target",
16531        );
16532        assert!(layout.is_contiguous());
16533        drop(guard);
16534        assert!(
16535            !Arc::ptr_eq(&out, &src_arc_external),
16536            "same-device Move is a plain copy — fresh storage, not an alias",
16537        );
16538        // The realize loop's destructive_input cleanup dropped the
16539        // cache's Arc to the source; only the test's external clone
16540        // survives.
16541        assert_eq!(
16542            Arc::strong_count(&src_arc_external),
16543            1,
16544            "Op::Move should evict the cache's Arc to its source",
16545        );
16546    }
16547
16548    /// The multiple-consumer-source case: a Move must NOT strand
16549    /// another consumer of its source. `execution_plan` (via
16550    /// `derive_ordering`, keyed off `destructive_input`) pins the
16551    /// Move AFTER the sibling reader; the executor's post-Move cache
16552    /// eviction then can't break the reader. Mirrors the legacy
16553    /// `op_move_pinned_after_sibling_reader_via_derive_ordering`
16554    /// test in fuel-graph-router/tests/cross_device.rs.
16555    ///
16556    ///   a   = const [1, 2, 3, 4]
16557    ///   b   = relu(a)        (non-destructive sibling reader)
16558    ///   m   = move(a, Cpu)   (destructive — evicts a once run)
16559    ///   out = add(b, m)      → [2, 4, 6, 8]
16560    #[test]
16561    fn pipelined_op_move_multi_consumer_source_not_stranded() {
16562        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
16563        let graph = Arc::new(RwLock::new(Graph::new()));
16564        let (a_id, out_id) = {
16565            let mut g = graph.write().unwrap();
16566            let a = g.push(Node {
16567                op: Op::Const,
16568                inputs: vec![],
16569                shape: Shape::from_dims(&[4]),
16570                dtype: DType::F32,
16571            });
16572            let b = g.push(Node {
16573                op: Op::Relu,
16574                inputs: vec![a],
16575                shape: Shape::from_dims(&[4]),
16576                dtype: DType::F32,
16577            });
16578            let m = g.push(Node {
16579                op: Op::Move {
16580                    target: DeviceLocation::Cpu,
16581                },
16582                inputs: vec![a],
16583                shape: Shape::from_dims(&[4]),
16584                dtype: DType::F32,
16585            });
16586            let out = g.push(Node {
16587                op: Op::Add,
16588                inputs: vec![b, m],
16589                shape: Shape::from_dims(&[4]),
16590                dtype: DType::F32,
16591            });
16592            g.set_target_backend(b, BackendId::Cpu);
16593            g.set_target_backend(m, BackendId::Cpu);
16594            g.set_target_backend(out, BackendId::Cpu);
16595            (a, out)
16596        };
16597        let mut inputs = StorageCache::new();
16598        inputs.insert(a_id, Arc::new(RwLock::new(a)));
16599
16600        let (out, _) = PipelinedExecutor::realize(graph, out_id, inputs)
16601            .expect("realize add(relu(a), move(a))");
16602        let guard = out.read().unwrap();
16603        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16604            panic!()
16605        };
16606        assert_eq!(
16607            c.as_slice::<f32>().unwrap(),
16608            &[2.0, 4.0, 6.0, 8.0],
16609            "relu(a) must run before move(a) evicts a",
16610        );
16611    }
16612
16613    /// A Move whose source is itself in the realize target set must
16614    /// not evict it — the caller asked for the source's storage. The
16615    /// destructive cleanup's `target_set` gate covers Move exactly
16616    /// like Release.
16617    #[test]
16618    fn pipelined_op_move_source_in_target_set_not_evicted() {
16619        let a = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0]);
16620        let graph = Arc::new(RwLock::new(Graph::new()));
16621        let (a_id, move_id) = {
16622            let mut g = graph.write().unwrap();
16623            let a = g.push(Node {
16624                op: Op::Const,
16625                inputs: vec![],
16626                shape: Shape::from_dims(&[2]),
16627                dtype: DType::F32,
16628            });
16629            let mv = g.push(Node {
16630                op: Op::Move {
16631                    target: DeviceLocation::Cpu,
16632                },
16633                inputs: vec![a],
16634                shape: Shape::from_dims(&[2]),
16635                dtype: DType::F32,
16636            });
16637            g.set_target_backend(mv, BackendId::Cpu);
16638            (a, mv)
16639        };
16640        let a_arc = Arc::new(RwLock::new(a));
16641        let a_arc_external = Arc::clone(&a_arc);
16642        let mut inputs = StorageCache::new();
16643        inputs.insert(a_id, a_arc);
16644
16645        let out = PipelinedExecutor::realize_many(graph, &[move_id, a_id], inputs)
16646            .expect("realize_many [move, source]");
16647        assert_eq!(out.len(), 2);
16648        let mv_guard = out[0].0.read().unwrap();
16649        let fuel_memory::BackendStorage::Cpu(c) = &mv_guard.inner else {
16650            panic!()
16651        };
16652        assert_eq!(c.as_slice::<f32>().unwrap(), &[5.0, 6.0]);
16653        assert!(
16654            Arc::ptr_eq(&out[1].0, &a_arc_external),
16655            "requested source must survive the Move's destructive cleanup",
16656        );
16657    }
16658
16659    // --- realize_many (Phase 7.6 step 9c Phase A) ----------------
16660
16661    /// realize_many on empty targets returns an empty Vec — no graph
16662    /// walk, no panic.
16663    #[test]
16664    fn pipelined_realize_many_empty_targets() {
16665        let graph = Arc::new(RwLock::new(Graph::new()));
16666        let inputs = StorageCache::new();
16667        let out = PipelinedExecutor::realize_many(graph, &[], inputs).expect("realize_many");
16668        assert!(out.is_empty());
16669    }
16670
16671    /// realize_many with two independent target chains. Each chain's
16672    /// output is in the cache; the shared topo walk realizes both.
16673    /// Verifies parallel chain handling + return order matches input.
16674    #[test]
16675    fn pipelined_realize_many_two_independent_targets() {
16676        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
16677        let rhs = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
16678        let graph = Arc::new(RwLock::new(Graph::new()));
16679        let (lhs_id, rhs_id, add_id, mul_id) = {
16680            let mut g = graph.write().unwrap();
16681            let lhs = g.push(Node {
16682                op: Op::Const,
16683                inputs: vec![],
16684                shape: Shape::from_dims(&[3]),
16685                dtype: DType::F32,
16686            });
16687            let rhs = g.push(Node {
16688                op: Op::Const,
16689                inputs: vec![],
16690                shape: Shape::from_dims(&[3]),
16691                dtype: DType::F32,
16692            });
16693            let add = g.push(Node {
16694                op: Op::Add,
16695                inputs: vec![lhs, rhs],
16696                shape: Shape::from_dims(&[3]),
16697                dtype: DType::F32,
16698            });
16699            let mul = g.push(Node {
16700                op: Op::Mul,
16701                inputs: vec![lhs, rhs],
16702                shape: Shape::from_dims(&[3]),
16703                dtype: DType::F32,
16704            });
16705            g.set_target_backend(add, BackendId::Cpu);
16706            g.set_target_backend(mul, BackendId::Cpu);
16707            (lhs, rhs, add, mul)
16708        };
16709        let mut inputs = StorageCache::new();
16710        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs)));
16711        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs)));
16712
16713        // Pass mul first to confirm return order matches targets order
16714        // (not graph order — graph order would put add first).
16715        let out = PipelinedExecutor::realize_many(graph, &[mul_id, add_id], inputs)
16716            .expect("realize_many");
16717        assert_eq!(out.len(), 2);
16718
16719        let mul_guard = out[0].0.read().unwrap();
16720        let fuel_memory::BackendStorage::Cpu(c) = &mul_guard.inner else {
16721            panic!()
16722        };
16723        assert_eq!(c.as_slice::<f32>().unwrap(), &[10.0, 40.0, 90.0]);
16724
16725        let add_guard = out[1].0.read().unwrap();
16726        let fuel_memory::BackendStorage::Cpu(c) = &add_guard.inner else {
16727            panic!()
16728        };
16729        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 22.0, 33.0]);
16730    }
16731
16732    /// realize_many with the same NodeId twice — caller asking for
16733    /// the same output twice. Both outputs are the same Arc (cheap).
16734    #[test]
16735    fn pipelined_realize_many_duplicate_target_returns_same_arc() {
16736        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
16737        let graph = Arc::new(RwLock::new(Graph::new()));
16738        let (in_id, neg_id) = {
16739            let mut g = graph.write().unwrap();
16740            let in_id = g.push(Node {
16741                op: Op::Const,
16742                inputs: vec![],
16743                shape: Shape::from_dims(&[3]),
16744                dtype: DType::F32,
16745            });
16746            let neg = g.push(Node {
16747                op: Op::Neg,
16748                inputs: vec![in_id],
16749                shape: Shape::from_dims(&[3]),
16750                dtype: DType::F32,
16751            });
16752            g.set_target_backend(neg, BackendId::Cpu);
16753            (in_id, neg)
16754        };
16755        let mut inputs = StorageCache::new();
16756        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
16757
16758        let out = PipelinedExecutor::realize_many(graph, &[neg_id, neg_id], inputs)
16759            .expect("realize_many");
16760        assert_eq!(out.len(), 2);
16761        assert!(
16762            Arc::ptr_eq(&out[0].0, &out[1].0),
16763            "duplicate target should share the same storage Arc",
16764        );
16765    }
16766
16767    /// realize_many with shared upstream nodes evaluates the shared
16768    /// chunk exactly once. Two targets `f = a + b` and `g = (a + b) * a`
16769    /// — `a + b` is computed once.
16770    #[test]
16771    fn pipelined_realize_many_shared_subgraph_evaluates_once() {
16772        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
16773        let b_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
16774        let graph = Arc::new(RwLock::new(Graph::new()));
16775        let (a_id, b_id, add_id, mul_id) = {
16776            let mut g = graph.write().unwrap();
16777            let a = g.push(Node {
16778                op: Op::Const,
16779                inputs: vec![],
16780                shape: Shape::from_dims(&[3]),
16781                dtype: DType::F32,
16782            });
16783            let b = g.push(Node {
16784                op: Op::Const,
16785                inputs: vec![],
16786                shape: Shape::from_dims(&[3]),
16787                dtype: DType::F32,
16788            });
16789            let add = g.push(Node {
16790                op: Op::Add,
16791                inputs: vec![a, b],
16792                shape: Shape::from_dims(&[3]),
16793                dtype: DType::F32,
16794            });
16795            let mul = g.push(Node {
16796                op: Op::Mul,
16797                inputs: vec![add, a],
16798                shape: Shape::from_dims(&[3]),
16799                dtype: DType::F32,
16800            });
16801            g.set_target_backend(add, BackendId::Cpu);
16802            g.set_target_backend(mul, BackendId::Cpu);
16803            (a, b, add, mul)
16804        };
16805        let mut inputs = StorageCache::new();
16806        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
16807        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
16808
16809        let out = PipelinedExecutor::realize_many(graph, &[add_id, mul_id], inputs)
16810            .expect("realize_many");
16811        assert_eq!(out.len(), 2);
16812
16813        let add_guard = out[0].0.read().unwrap();
16814        let fuel_memory::BackendStorage::Cpu(c) = &add_guard.inner else {
16815            panic!()
16816        };
16817        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 22.0, 33.0]);
16818
16819        let mul_guard = out[1].0.read().unwrap();
16820        let fuel_memory::BackendStorage::Cpu(c) = &mul_guard.inner else {
16821            panic!()
16822        };
16823        // (a + b) * a = [11*1, 22*2, 33*3] = [11, 44, 99].
16824        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 44.0, 99.0]);
16825    }
16826
16827    /// E2E: masked_fill with -inf — the attention masking pattern.
16828    /// x = [1, 2, 3, 4]; mask = [0, 1, 0, 1]; value = -1000.
16829    /// out = [1, -1000, 3, -1000].
16830    #[test]
16831    fn pipelined_realize_masked_fill_attention_pattern() {
16832        let x_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
16833        let mut mask_storage = fuel_memory::from_slice_cpu(&[0u8, 1, 0, 1]);
16834        mask_storage.dtype = DType::Bool; // GAP-168(c): a Bool mask, not U8 bytes
16835        let graph = Arc::new(RwLock::new(Graph::new()));
16836        let (x_id, mask_id, out_id) = {
16837            let mut g = graph.write().unwrap();
16838            let x = g.push(Node {
16839                op: Op::Const,
16840                inputs: vec![],
16841                shape: Shape::from_dims(&[4]),
16842                dtype: DType::F32,
16843            });
16844            let mask = g.push(Node {
16845                op: Op::Const,
16846                inputs: vec![],
16847                shape: Shape::from_dims(&[4]),
16848                dtype: DType::Bool,
16849            });
16850            let out = g.push(Node {
16851                op: Op::MaskedFill {
16852                    value: fuel_ir::Scalar::F32(-1000.0),
16853                },
16854                inputs: vec![x, mask],
16855                shape: Shape::from_dims(&[4]),
16856                dtype: DType::F32,
16857            });
16858            g.set_target_backend(out, BackendId::Cpu);
16859            (x, mask, out)
16860        };
16861        let mut inputs = StorageCache::new();
16862        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
16863        inputs.insert(mask_id, Arc::new(RwLock::new(mask_storage)));
16864        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
16865        let guard = result_arc.read().unwrap();
16866        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16867            panic!("expected Cpu storage");
16868        };
16869        let out: &[f32] = c.as_slice().unwrap();
16870        assert_eq!(out, &[1.0, -1000.0, 3.0, -1000.0]);
16871    }
16872
16873    // ---- WriteSlice (Phase 7.6 step 9c E.3.2) -------------------------------
16874
16875    /// E2E: pipelined realize of `Op::WriteSlice` writing a [1, 3, 2]
16876    /// source slab into a [4, 3, 2] destination at axis-0 row 2 — the
16877    /// canonical KV-cache append shape.
16878    #[test]
16879    fn pipelined_realize_write_slice_kv_cache_append() {
16880        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 24]);
16881        let src_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
16882        let graph = Arc::new(RwLock::new(Graph::new()));
16883        let (dest_id, src_id, ws_id) = {
16884            let mut g = graph.write().unwrap();
16885            let dest = g.push(Node {
16886                op: Op::Const,
16887                inputs: vec![],
16888                shape: Shape::from_dims(&[4, 3, 2]),
16889                dtype: DType::F32,
16890            });
16891            let src = g.push(Node {
16892                op: Op::Const,
16893                inputs: vec![],
16894                shape: Shape::from_dims(&[1, 3, 2]),
16895                dtype: DType::F32,
16896            });
16897            let ws = g.push(Node {
16898                op: Op::WriteSlice {
16899                    ranges: vec![(2, 3), (0, 3), (0, 2)],
16900                    dyn_offset: None,
16901                },
16902                inputs: vec![dest, src],
16903                shape: Shape::from_dims(&[4, 3, 2]), // adopts dest shape
16904                dtype: DType::F32,
16905            });
16906            g.set_target_backend(ws, BackendId::Cpu);
16907            (dest, src, ws)
16908        };
16909        let mut inputs = StorageCache::new();
16910        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
16911        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
16912        let (result_arc, _) = PipelinedExecutor::realize(graph, ws_id, inputs).expect("realize");
16913        let guard = result_arc.read().unwrap();
16914        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16915            panic!("expected Cpu storage");
16916        };
16917        let out: &[f32] = c.as_slice().unwrap();
16918        let expected = [
16919            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,
16920            6.0, // row 2 = source
16921            0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
16922        ];
16923        assert_eq!(out, &expected);
16924    }
16925
16926    /// E2E: pipelined realize of `Op::WriteSlice` adopts the
16927    /// destination's Storage Arc as the output slot (in-place
16928    /// alias) — the resulting Arc points to the SAME bytes the
16929    /// destination was constructed from.
16930    #[test]
16931    fn pipelined_realize_write_slice_aliases_dest_storage() {
16932        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
16933        let src_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
16934        let graph = Arc::new(RwLock::new(Graph::new()));
16935        let (dest_id, src_id, ws_id, dest_arc_external) = {
16936            let mut g = graph.write().unwrap();
16937            let dest = g.push(Node {
16938                op: Op::Const,
16939                inputs: vec![],
16940                shape: Shape::from_dims(&[3, 2]),
16941                dtype: DType::F32,
16942            });
16943            let src = g.push(Node {
16944                op: Op::Const,
16945                inputs: vec![],
16946                shape: Shape::from_dims(&[1, 2]),
16947                dtype: DType::F32,
16948            });
16949            let ws = g.push(Node {
16950                op: Op::WriteSlice {
16951                    ranges: vec![(1, 2), (0, 2)],
16952                    dyn_offset: None,
16953                },
16954                inputs: vec![dest, src],
16955                shape: Shape::from_dims(&[3, 2]),
16956                dtype: DType::F32,
16957            });
16958            g.set_target_backend(ws, BackendId::Cpu);
16959            let arc = Arc::new(RwLock::new(dest_storage));
16960            (dest, src, ws, arc)
16961        };
16962        let mut inputs = StorageCache::new();
16963        inputs.insert(dest_id, Arc::clone(&dest_arc_external));
16964        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
16965        let (result_arc, _) = PipelinedExecutor::realize(graph, ws_id, inputs).expect("realize");
16966        // Bytes were written into the same Arc the caller held —
16967        // the WriteSlice op aliases dest's Storage Arc, not allocates
16968        // a fresh buffer.
16969        assert!(
16970            Arc::ptr_eq(&result_arc, &dest_arc_external),
16971            "WriteSlice output Arc must be the same Arc as the destination's"
16972        );
16973        let guard = dest_arc_external.read().unwrap();
16974        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16975            panic!("expected Cpu storage");
16976        };
16977        let out: &[f32] = c.as_slice().unwrap();
16978        assert_eq!(out, &[0.0, 0.0, 10.0, 20.0, 0.0, 0.0]);
16979    }
16980
16981    // ---- WriteSlice dynamic offset (Phase D symbolic extents) ---------------
16982
16983    /// E2E: pipelined realize of `Op::WriteSlice` with a runtime start
16984    /// offset (`dyn_offset`) resolved through a per-pass `SymEnv`. The
16985    /// width-2 source slab lands at the bound offset (3), not the static
16986    /// `ranges[0].0` placeholder (0) — the persistent-decode KV-cache
16987    /// write at a per-token `cached_len`.
16988    #[test]
16989    fn pipelined_realize_write_slice_dynamic_offset() {
16990        use fuel_ir::{DynScalar, SymId};
16991        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
16992        let src_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0]);
16993        let graph = Arc::new(RwLock::new(Graph::new()));
16994        let sym = SymId(0);
16995        let (dest_id, src_id, ws_id) = {
16996            let mut g = graph.write().unwrap();
16997            let dest = g.push(Node {
16998                op: Op::Const,
16999                inputs: vec![],
17000                shape: Shape::from_dims(&[6]),
17001                dtype: DType::F32,
17002            });
17003            let src = g.push(Node {
17004                op: Op::Const,
17005                inputs: vec![],
17006                shape: Shape::from_dims(&[2]),
17007                dtype: DType::F32,
17008            });
17009            let ws = g.push(Node {
17010                // ranges[0] = (0, 2): the start is a placeholder (ignored —
17011                // overridden by dyn_offset); only the width (2) is read.
17012                op: Op::WriteSlice {
17013                    ranges: vec![(0, 2)],
17014                    dyn_offset: Some((0, DynScalar::Sym(sym))),
17015                },
17016                inputs: vec![dest, src],
17017                shape: Shape::from_dims(&[6]),
17018                dtype: DType::F32,
17019            });
17020            g.set_target_backend(ws, BackendId::Cpu);
17021            (dest, src, ws)
17022        };
17023        let mut inputs = StorageCache::new();
17024        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
17025        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
17026
17027        // Bind cached_len = 3: the slab must land at indices [3, 4].
17028        let mut env = SymEnv::new();
17029        env.bind(sym, 3).unwrap();
17030
17031        let (result_arc, _) = PipelinedExecutor::realize_with_env(graph, ws_id, inputs, env)
17032            .expect("realize_with_env");
17033        let guard = result_arc.read().unwrap();
17034        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
17035            panic!("expected Cpu storage");
17036        };
17037        let out: &[f32] = c.as_slice().unwrap();
17038        assert_eq!(
17039            out,
17040            &[0.0, 0.0, 0.0, 7.0, 8.0, 0.0],
17041            "slab must land at the SymEnv-bound offset 3, not the static placeholder 0",
17042        );
17043    }
17044
17045    /// Increment 2a — the data-determined bind seam. After
17046    /// `Op::NonZeroIndices` realizes, the executor reads its runtime count
17047    /// from bundle slot 1 and PUBLISHES it into the produced `SymEnv` under
17048    /// `count_sym`. This is the first op to bind a *data-determined* symbol
17049    /// mid-realize (all prior binds are host-known before realize) — the
17050    /// keystone capability for SSM decode / MoE sparsity / MLA KV.
17051    #[test]
17052    fn pipelined_realize_nonzero_indices_publishes_count() {
17053        use fuel_ir::SymId;
17054        use fuel_ir::storage::{OutputViewSpec, compose_bundle};
17055        // flat [0,1,0,1,1,0] → 3 nonzeros at 1,3,4; capacity 6.
17056        let x_storage = fuel_memory::from_slice_cpu(&[0.0_f32, 1.0, 0.0, 1.0, 1.0, 0.0]);
17057        let graph = Arc::new(RwLock::new(Graph::new()));
17058        let count_sym = SymId(0);
17059        let (x_id, nzi_id) = {
17060            let mut g = graph.write().unwrap();
17061            let x = g.push(Node {
17062                op: Op::Const,
17063                inputs: vec![],
17064                shape: Shape::from_dims(&[2, 3]),
17065                dtype: DType::F32,
17066            });
17067            let capacity = 6usize;
17068            let idx_shape = Shape::from_dims(&[capacity]);
17069            let cnt_shape = Shape::from_dims(&[1]);
17070            let specs = vec![
17071                OutputViewSpec {
17072                    dtype: DType::U32,
17073                    shape: idx_shape.clone(),
17074                    layout: Layout::contiguous(idx_shape.clone()),
17075                    name: Some("indices"),
17076                },
17077                OutputViewSpec {
17078                    dtype: DType::U32,
17079                    shape: cnt_shape.clone(),
17080                    layout: Layout::contiguous(cnt_shape),
17081                    name: Some("count"),
17082                },
17083            ];
17084            let (_bytes, views) = compose_bundle(&specs).unwrap();
17085            let nzi = g.push(Node {
17086                op: Op::NonZeroIndices { count_sym },
17087                inputs: vec![x],
17088                shape: idx_shape,
17089                dtype: DType::U32,
17090            });
17091            g.set_output_views(nzi, Arc::from(views.into_boxed_slice()))
17092                .unwrap();
17093            g.set_target_backend(nzi, BackendId::Cpu);
17094            (x, nzi)
17095        };
17096        let mut inputs = StorageCache::new();
17097        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
17098
17099        let (_arc, _layout, produced) =
17100            PipelinedExecutor::realize_with_env_producing(graph, nzi_id, inputs, SymEnv::new())
17101                .expect("realize_with_env_producing");
17102
17103        assert_eq!(
17104            produced.get(count_sym),
17105            Some(3),
17106            "the executor must publish the data-determined nonzero count into the SymEnv",
17107        );
17108    }
17109
17110    /// A `dyn_offset` whose symbol is unbound in the `SymEnv` surfaces a
17111    /// typed error at realize (never a panic).
17112    #[test]
17113    fn pipelined_realize_write_slice_dynamic_offset_unbound_errors() {
17114        use fuel_ir::{DynScalar, SymId};
17115        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
17116        let src_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0]);
17117        let graph = Arc::new(RwLock::new(Graph::new()));
17118        let (dest_id, src_id, ws_id) = {
17119            let mut g = graph.write().unwrap();
17120            let dest = g.push(Node {
17121                op: Op::Const,
17122                inputs: vec![],
17123                shape: Shape::from_dims(&[6]),
17124                dtype: DType::F32,
17125            });
17126            let src = g.push(Node {
17127                op: Op::Const,
17128                inputs: vec![],
17129                shape: Shape::from_dims(&[2]),
17130                dtype: DType::F32,
17131            });
17132            let ws = g.push(Node {
17133                op: Op::WriteSlice {
17134                    ranges: vec![(0, 2)],
17135                    dyn_offset: Some((0, DynScalar::Sym(SymId(0)))),
17136                },
17137                inputs: vec![dest, src],
17138                shape: Shape::from_dims(&[6]),
17139                dtype: DType::F32,
17140            });
17141            g.set_target_backend(ws, BackendId::Cpu);
17142            (dest, src, ws)
17143        };
17144        let mut inputs = StorageCache::new();
17145        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
17146        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
17147        // Empty env — the symbol is unbound.
17148        let result = PipelinedExecutor::realize_with_env(graph, ws_id, inputs, SymEnv::new());
17149        assert!(
17150            result.is_err(),
17151            "unbound dyn_offset symbol must surface a typed error, not a panic",
17152        );
17153    }
17154
17155    /// A runtime offset whose resolved slab runs past the destination
17156    /// capacity errors at realize (never an out-of-bounds write).
17157    #[test]
17158    fn pipelined_realize_write_slice_dynamic_offset_out_of_capacity_errors() {
17159        use fuel_ir::{DynScalar, SymId};
17160        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
17161        let src_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0]);
17162        let graph = Arc::new(RwLock::new(Graph::new()));
17163        let sym = SymId(0);
17164        let (dest_id, src_id, ws_id) = {
17165            let mut g = graph.write().unwrap();
17166            let dest = g.push(Node {
17167                op: Op::Const,
17168                inputs: vec![],
17169                shape: Shape::from_dims(&[6]),
17170                dtype: DType::F32,
17171            });
17172            let src = g.push(Node {
17173                op: Op::Const,
17174                inputs: vec![],
17175                shape: Shape::from_dims(&[2]),
17176                dtype: DType::F32,
17177            });
17178            let ws = g.push(Node {
17179                op: Op::WriteSlice {
17180                    ranges: vec![(0, 2)],
17181                    dyn_offset: Some((0, DynScalar::Sym(sym))),
17182                },
17183                inputs: vec![dest, src],
17184                shape: Shape::from_dims(&[6]),
17185                dtype: DType::F32,
17186            });
17187            g.set_target_backend(ws, BackendId::Cpu);
17188            (dest, src, ws)
17189        };
17190        let mut inputs = StorageCache::new();
17191        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
17192        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
17193        // offset 5 + width 2 = 7 > capacity 6.
17194        let mut env = SymEnv::new();
17195        env.bind(sym, 5).unwrap();
17196        let result = PipelinedExecutor::realize_with_env(graph, ws_id, inputs, env);
17197        assert!(
17198            result.is_err(),
17199            "resolved slab past destination capacity must surface a typed error",
17200        );
17201    }
17202
17203    /// Regression for the PipelinedExecutor ordering-integration session.
17204    ///
17205    /// Graph: `x = Const`, `step_x = Step(x)`, `y = SigmoidInplace(x)`.
17206    /// `Step` and `SigmoidInplace` are both readers of `x`; `Step` is
17207    /// non-destructive, `SigmoidInplace` mutates `x`'s storage. The
17208    /// correct semantic is for `Step` to read PRE-mutation bytes.
17209    ///
17210    /// Pre-this-session (raw `topo_order_multi`): the two are siblings
17211    /// in topo order and the tie-break is unspecified — `SigmoidInplace`
17212    /// could run first, making `step_x` see post-sigmoid bytes
17213    /// (`[1, 1, 1, 1]` because every sigmoid output is positive).
17214    ///
17215    /// Post-this-session: `execution_plan` consults `derive_ordering`,
17216    /// which pins `SigmoidInplace` AFTER every other reader of `x`.
17217    /// `step_x` deterministically sees `x` and is `[1, 0, 1, 0]`.
17218    #[test]
17219    fn pipelined_inplace_with_multiple_readers_orders_correctly() {
17220        use fuel_ir::Shape;
17221        let data = [1.0_f32, -2.0, 3.0, -4.0];
17222        let src_storage = fuel_memory::from_slice_cpu(&data);
17223
17224        let graph = Arc::new(RwLock::new(Graph::new()));
17225        let (x_id, step_id, sig_id) = {
17226            let mut g = graph.write().unwrap();
17227            let x = g.push(Node {
17228                op: Op::Const,
17229                inputs: vec![],
17230                shape: Shape::from_dims(&[4]),
17231                dtype: DType::F32,
17232            });
17233            let step = g.push(Node {
17234                op: Op::Step,
17235                inputs: vec![x],
17236                shape: Shape::from_dims(&[4]),
17237                dtype: DType::F32,
17238            });
17239            let sig = g.push(Node {
17240                op: Op::SigmoidInplace,
17241                inputs: vec![x],
17242                shape: Shape::from_dims(&[4]),
17243                dtype: DType::F32,
17244            });
17245            g.set_target_backend(step, BackendId::Cpu);
17246            g.set_target_backend(sig, BackendId::Cpu);
17247            (x, step, sig)
17248        };
17249
17250        let mut cache = StorageCache::new();
17251        cache.insert(x_id, Arc::new(RwLock::new(src_storage)));
17252
17253        let results = PipelinedExecutor::realize_many(graph, &[step_id, sig_id], cache)
17254            .expect("realize_many");
17255
17256        // step_x must reflect pre-mutation x: sign of [1, -2, 3, -4] →
17257        // [1, 0, 1, 0]. If the executor ran SigmoidInplace first, step
17258        // would see all-positive sigmoid outputs and produce [1, 1, 1, 1].
17259        let step_guard = results[0].0.read().unwrap();
17260        let fuel_memory::BackendStorage::Cpu(c) = &step_guard.inner else {
17261            panic!("expected Cpu storage for step output");
17262        };
17263        let step_out: &[f32] = c.as_slice().expect("f32 cast");
17264        assert_eq!(
17265            step_out,
17266            &[1.0_f32, 0.0, 1.0, 0.0],
17267            "Step must run before SigmoidInplace; got post-mutation bytes"
17268        );
17269        drop(step_guard);
17270
17271        // SigmoidInplace's output Arc IS the mutated cache entry — bytes
17272        // approximate sigmoid([1, -2, 3, -4]).
17273        let sig_guard = results[1].0.read().unwrap();
17274        let fuel_memory::BackendStorage::Cpu(c) = &sig_guard.inner else {
17275            panic!("expected Cpu storage for sigmoid output");
17276        };
17277        let sig_out: &[f32] = c.as_slice().expect("f32 cast");
17278        let sig_ref = [
17279            1.0_f32 / (1.0 + (-1.0_f32).exp()),
17280            1.0_f32 / (1.0 + (2.0_f32).exp()),
17281            1.0_f32 / (1.0 + (-3.0_f32).exp()),
17282            1.0_f32 / (1.0 + (4.0_f32).exp()),
17283        ];
17284        for (got, want) in sig_out.iter().zip(sig_ref.iter()) {
17285            assert!((got - want).abs() < 1e-6, "sigmoid: got {got}, want {want}");
17286        }
17287    }
17288
17289    /// Regression for the PipelinedExecutor ordering-integration session.
17290    ///
17291    /// Canonical residual-connection pattern:
17292    ///   `x = Const`, `y = ReluInplace(x)`, `z = Add(y, x)`.
17293    ///
17294    /// Pre-this-session: `derive_ordering` was never run, so the cycle
17295    /// (Add must precede ReluInplace per ordering edge; Add must follow
17296    /// ReluInplace per data-flow edge through y) was undetected. The
17297    /// executor produced `z = relu(x) + relu(x) = [2, 0, 6, 0]` —
17298    /// silently wrong.
17299    ///
17300    /// Post-this-session: `insert_safety_copies` runs before
17301    /// `execution_plan`, inserts `Op::Copy(x) → x_safe`, rewires Add's
17302    /// `x` input to `x_safe`. Result: `z = relu(x) + x = [2, -2, 6, -4]`.
17303    #[test]
17304    fn pipelined_residual_connection_inserts_safety_copy() {
17305        use fuel_ir::Shape;
17306        let data = [1.0_f32, -2.0, 3.0, -4.0];
17307        let src_storage = fuel_memory::from_slice_cpu(&data);
17308
17309        let graph = Arc::new(RwLock::new(Graph::new()));
17310        let (x_id, _y_id, z_id) = {
17311            let mut g = graph.write().unwrap();
17312            let x = g.push(Node {
17313                op: Op::Const,
17314                inputs: vec![],
17315                shape: Shape::from_dims(&[4]),
17316                dtype: DType::F32,
17317            });
17318            let y = g.push(Node {
17319                op: Op::ReluInplace,
17320                inputs: vec![x],
17321                shape: Shape::from_dims(&[4]),
17322                dtype: DType::F32,
17323            });
17324            let z = g.push(Node {
17325                op: Op::Add,
17326                inputs: vec![y, x],
17327                shape: Shape::from_dims(&[4]),
17328                dtype: DType::F32,
17329            });
17330            g.set_target_backend(y, BackendId::Cpu);
17331            g.set_target_backend(z, BackendId::Cpu);
17332            (x, y, z)
17333        };
17334
17335        let mut cache = StorageCache::new();
17336        cache.insert(x_id, Arc::new(RwLock::new(src_storage)));
17337
17338        let (result_arc, _) = PipelinedExecutor::realize(graph, z_id, cache)
17339            .expect("realize z — insert_safety_copies must break the cycle");
17340
17341        let guard = result_arc.read().unwrap();
17342        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
17343            panic!("expected Cpu storage");
17344        };
17345        let got: &[f32] = c.as_slice().expect("f32 cast");
17346        assert_eq!(
17347            got,
17348            &[2.0_f32, -2.0, 6.0, -4.0],
17349            "Add must read pre-mutation x via the inserted safety copy"
17350        );
17351    }
17352
17353    // ------------------------------------------------------------------
17354    // Item 3 end-to-end: SelectiveScan through the bundled-output
17355    // PipelinedExecutor path. The producer allocates bundled
17356    // (y_bytes + last_state_bytes), the kernel writes both slots,
17357    // and the bundled-tuple builder returns each via Op::View.
17358    // ------------------------------------------------------------------
17359
17360    fn cpu_const_f32(
17361        graph: &Arc<RwLock<Graph>>,
17362        cache: &mut StorageCache,
17363        data: &[f32],
17364        dims: &[usize],
17365    ) -> NodeId {
17366        let id = {
17367            let mut g = graph.write().unwrap();
17368            g.push(Node {
17369                op: Op::Const,
17370                inputs: vec![],
17371                shape: Shape::from_dims(dims),
17372                dtype: DType::F32,
17373            })
17374        };
17375        cache.insert(id, Arc::new(RwLock::new(fuel_memory::from_slice_cpu(data))));
17376        id
17377    }
17378
17379    /// `selective_scan_bundled` realizes both `y` and `last_state` in
17380    /// a single `realize_many` pass; the Views project the same
17381    /// producer's bundled Storage Arc and the numerics match the
17382    /// hand-computed single-step kernel test (b=1,s=1,d=1,k=1).
17383    #[test]
17384    fn pipelined_realize_selective_scan_bundled_produces_y_and_last_state() {
17385        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
17386        let mut cache = StorageCache::new();
17387
17388        let u_id = cpu_const_f32(&graph, &mut cache, &[3.0], &[1, 1, 1]);
17389        let delta_id = cpu_const_f32(&graph, &mut cache, &[1.0], &[1, 1, 1]);
17390        let a_id = cpu_const_f32(&graph, &mut cache, &[-1.0], &[1, 1]);
17391        let b_id = cpu_const_f32(&graph, &mut cache, &[2.0], &[1, 1, 1]);
17392        let c_id = cpu_const_f32(&graph, &mut cache, &[0.5], &[1, 1, 1]);
17393
17394        let (y_id, last_state_id) = {
17395            let u_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), u_id);
17396            let delta_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), delta_id);
17397            let a_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), a_id);
17398            let b_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), b_id);
17399            let c_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), c_id);
17400            let (y, last_state) = u_t
17401                .selective_scan_bundled(&delta_t, &a_t, &b_t, &c_t, /* delta_softplus */ false)
17402                .expect("selective_scan_bundled");
17403            (y.id(), last_state.id())
17404        };
17405        // Set target_backend on the producer (View nodes inherit it).
17406        {
17407            let mut g = graph.write().unwrap();
17408            let producer = g.node(y_id).inputs[0];
17409            g.set_target_backend(producer, BackendId::Cpu);
17410        }
17411
17412        let outputs =
17413            PipelinedExecutor::realize_many(Arc::clone(&graph), &[y_id, last_state_id], cache)
17414                .expect("realize_many");
17415        let (y_arc, y_layout) = outputs[0].clone();
17416        let (last_state_arc, last_state_layout) = outputs[1].clone();
17417
17418        // Both Views project the same bundled producer Storage Arc.
17419        assert!(
17420            Arc::ptr_eq(&y_arc, &last_state_arc),
17421            "y and last_state Views project the SAME bundled producer Storage",
17422        );
17423
17424        // Hand-computed numerics (single-step recurrence):
17425        // h[0,0,0] = exp(1.0 * -1.0) * 0 + 1.0 * 2.0 * 3.0 = 6.0
17426        // y[0,0,0] = h * c = 6.0 * 0.5 = 3.0
17427        // last_state[0,0,0] = h = 6.0
17428        let guard = y_arc.read().unwrap();
17429        let fuel_memory::BackendStorage::Cpu(c_bytes) = &guard.inner else {
17430            panic!("expected Cpu storage");
17431        };
17432        let typed: &[f32] = c_bytes.as_slice().expect("f32 cast");
17433        assert_eq!(y_layout.start_offset(), 0);
17434        let y_value = typed[y_layout.start_offset()];
17435        assert!((y_value - 3.0).abs() < 1e-5, "y expected 3.0 got {y_value}");
17436        assert_eq!(
17437            last_state_layout.start_offset(),
17438            1,
17439            "slot 1 byte_offset 4 / sizeof(f32) = 1",
17440        );
17441        let ls_value = typed[last_state_layout.start_offset()];
17442        assert!(
17443            (ls_value - 6.0).abs() < 1e-5,
17444            "last_state expected 6.0 got {ls_value}"
17445        );
17446    }
17447
17448    /// E2E (row 172 item 2): TopKLastDim f32 on CPU through the bundled
17449    /// two-slot output. Row 0 has a NaN and tied values, row 1 distinct values;
17450    /// k = 3. The `values` View reads slot 0 and the `indices` View slot 1 of the
17451    /// SAME bundled storage (the indices slot starts 4-byte aligned).
17452    #[test]
17453    fn pipelined_realize_top_k_last_dim_bundled_values_and_indices() {
17454        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
17455        let mut cache = StorageCache::new();
17456        let x_id = cpu_const_f32(
17457            &graph,
17458            &mut cache,
17459            &[1.0, 5.0, f32::NAN, 5.0, 2.0, 3.0, 3.0, 3.0, -1.0, 9.0],
17460            &[2, 5],
17461        );
17462        let (v_id, i_id) = {
17463            let x = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), x_id);
17464            let (v, i) = x.top_k_last_dim(3).expect("top_k_last_dim");
17465            (v.id(), i.id())
17466        };
17467        {
17468            let mut g = graph.write().unwrap();
17469            let producer = g.node(v_id).inputs[0];
17470            g.set_target_backend(producer, BackendId::Cpu);
17471        }
17472        let outputs = PipelinedExecutor::realize_many(Arc::clone(&graph), &[v_id, i_id], cache)
17473            .expect("realize_many");
17474        let (arc, v_layout) = outputs[0].clone();
17475        let (_, i_layout) = outputs[1].clone();
17476        let guard = arc.read().unwrap();
17477        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
17478            panic!("expected Cpu storage");
17479        };
17480        let bytes = c.bytes();
17481        let vo = v_layout.start_offset() * 4;
17482        let io = i_layout.start_offset() * 4;
17483        let vals: Vec<f32> = bytes[vo..vo + 24]
17484            .chunks(4)
17485            .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
17486            .collect();
17487        let idx: Vec<u32> = bytes[io..io + 24]
17488            .chunks(4)
17489            .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
17490            .collect();
17491        assert_eq!(idx, vec![2, 1, 3, 4, 0, 1], "NaN first, ties by index");
17492        assert!(vals[0].is_nan());
17493        assert_eq!(&vals[1..], &[5.0, 5.0, 9.0, 3.0, 3.0]);
17494    }
17495
17496    /// E2E (row 172 item 2 step B): MatMulTopK f32 on CPU. Distinct matmul
17497    /// results, so the selection does not depend on accumulation order; the
17498    /// values and indices equal a hand matmul + top-2.
17499    #[test]
17500    fn pipelined_realize_matmul_top_k_f32() {
17501        // a [1, 2, 3], b [1, 3, 4]; row r of the result = a[r] @ b.
17502        let a = [1.0_f32, 2.0, 3.0, -1.0, 0.5, 2.0];
17503        let b = [
17504            1.0_f32, 0.0, 2.0, 1.0, 0.0, 1.0, 1.0, -1.0, 2.0, 1.0, 0.0, 3.0,
17505        ];
17506        let mut want_v = Vec::new();
17507        let mut want_i = Vec::new();
17508        for r in 0..2 {
17509            let row: Vec<f32> = (0..4)
17510                .map(|j| (0..3).map(|q| a[r * 3 + q] * b[q * 4 + j]).sum())
17511                .collect();
17512            let mut idx: Vec<usize> = (0..4).collect();
17513            idx.sort_by(|&x, &y| row[y].partial_cmp(&row[x]).unwrap());
17514            for &i in &idx[..2] {
17515                want_v.push(row[i]);
17516                want_i.push(i as u32);
17517            }
17518        }
17519        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
17520        let mut cache = StorageCache::new();
17521        let a_id = cpu_const_f32(&graph, &mut cache, &a, &[1, 2, 3]);
17522        let b_id = cpu_const_f32(&graph, &mut cache, &b, &[1, 3, 4]);
17523        let (v_id, i_id) = {
17524            let at = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), a_id);
17525            let bt = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), b_id);
17526            let (v, i) = at.matmul_top_k(&bt, 2).expect("matmul_top_k");
17527            (v.id(), i.id())
17528        };
17529        {
17530            let mut g = graph.write().unwrap();
17531            let producer = g.node(v_id).inputs[0];
17532            g.set_target_backend(producer, BackendId::Cpu);
17533        }
17534        let outputs = PipelinedExecutor::realize_many(Arc::clone(&graph), &[v_id, i_id], cache)
17535            .expect("realize_many");
17536        let (arc, v_layout) = outputs[0].clone();
17537        let (_, i_layout) = outputs[1].clone();
17538        let guard = arc.read().unwrap();
17539        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
17540            panic!("expected Cpu storage");
17541        };
17542        let bytes = c.bytes();
17543        let (vo, io) = (v_layout.start_offset() * 4, i_layout.start_offset() * 4);
17544        let vals: Vec<f32> = bytes[vo..vo + 16]
17545            .chunks(4)
17546            .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
17547            .collect();
17548        let idx: Vec<u32> = bytes[io..io + 16]
17549            .chunks(4)
17550            .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
17551            .collect();
17552        assert_eq!(idx, want_i);
17553        assert_eq!(vals, want_v);
17554    }
17555
17556    // ---- Ordering-defect repros (MLA decode multi-round WriteSlice) -----
17557
17558    /// DIAGNOSTIC (not a repro by itself): a plain single-hop view chain
17559    /// `S = Slice(X); K = Relu(S)` competing with a SECOND destructive
17560    /// WriteSlice on `X` (`Y = WriteSlice(X, ...)`) within one
17561    /// `realize_many` call. `collect_alias_set` adds `S` to `X`'s alias
17562    /// set (Slice IS `is_view_op`), so `derive_ordering` pins `Y` after
17563    /// `S`'s reader `K` directly. This form is expected to STAY GREEN —
17564    /// recorded here as the control that isolates the Reshape-specific
17565    /// gap exercised by the next test.
17566    #[test]
17567    fn pipelined_write_slice_round2_plain_slice_reader_not_stranded() {
17568        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
17569        let mut cache = StorageCache::new();
17570
17571        let b_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
17572        let src1_id = cpu_const_f32(&graph, &mut cache, &[1.0, 2.0], &[2]);
17573        let src2_id = cpu_const_f32(&graph, &mut cache, &[99.0, 98.0], &[2]);
17574
17575        let (k_id, y_id) = {
17576            let mut g = graph.write().unwrap();
17577            let x_id = g.push(Node {
17578                op: Op::WriteSlice {
17579                    ranges: vec![(0, 2)],
17580                    dyn_offset: None,
17581                },
17582                inputs: vec![b_id, src1_id],
17583                shape: Shape::from_dims(&[4]),
17584                dtype: DType::F32,
17585            });
17586            let s_id = g.push(Node {
17587                op: Op::Slice {
17588                    dim: 0,
17589                    start: 0,
17590                    len: 2,
17591                },
17592                inputs: vec![x_id],
17593                shape: Shape::from_dims(&[2]),
17594                dtype: DType::F32,
17595            });
17596            let k_id = g.push(Node {
17597                op: Op::Relu,
17598                inputs: vec![s_id],
17599                shape: Shape::from_dims(&[2]),
17600                dtype: DType::F32,
17601            });
17602            // Round 2 OVERLAPS round 1's [0,2) range so a wrong-order
17603            // execution would be numerically visible in K's output.
17604            let y_id = g.push(Node {
17605                op: Op::WriteSlice {
17606                    ranges: vec![(0, 2)],
17607                    dyn_offset: None,
17608                },
17609                inputs: vec![x_id, src2_id],
17610                shape: Shape::from_dims(&[4]),
17611                dtype: DType::F32,
17612            });
17613            g.set_target_backend(x_id, BackendId::Cpu);
17614            g.set_target_backend(k_id, BackendId::Cpu);
17615            g.set_target_backend(y_id, BackendId::Cpu);
17616            (k_id, y_id)
17617        };
17618
17619        let plan = fuel_graph::opt::execution_plan(&graph.read().unwrap(), &[k_id, y_id]);
17620        eprintln!("[diagnostic plain-slice] execution_plan = {:?}", plan,);
17621
17622        let outputs = PipelinedExecutor::realize_many(Arc::clone(&graph), &[k_id, y_id], cache)
17623            .expect("realize_many: plain slice reader must not error");
17624        let (k_arc, _) = &outputs[0];
17625        let guard = k_arc.read().unwrap();
17626        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
17627            panic!("expected Cpu storage");
17628        };
17629        let out: &[f32] = c.as_slice().unwrap();
17630        assert_eq!(
17631            out,
17632            &[1.0, 2.0],
17633            "K = relu(slice(X,0,2)) must read PRE-round-2 bytes; got {:?}",
17634            out,
17635        );
17636    }
17637
17638    /// CRITICAL SUSPECT #2 repro: `Op::Reshape`/`Op::Contiguize` compile
17639    /// to `WorkItemKind::ContiguizeOf`, which zero-copy ADOPTS the
17640    /// input's Storage Arc when the input is contiguous at offset 0 —
17641    /// but `Op::Reshape` is NOT in `collect_alias_set`'s alias-extending
17642    /// predicate (only `Op::is_view_op` + `Op::View{..}`). So for
17643    /// `X = write_slice(B, src1); S = X.slice(0, 0, 2) [offset-0
17644    /// contiguous]; R = S.reshape([2]); K = relu(R); Y =
17645    /// write_slice(X, src2)`, `collect_alias_set(X)` stops at `{X, S}`
17646    /// — `R` never enters the alias set, so `derive_ordering` never
17647    /// scans `R`'s consumers (`K`) for pinning against `Y`. `K` and `Y`
17648    /// become simultaneously "ready" once `R` completes, and
17649    /// `execution_plan`'s stable tiebreak (smaller `topo_order_multi`
17650    /// position wins) can schedule `Y` (destructive) BEFORE `K` — `K`
17651    /// then dereferences `R`'s adopted Arc (== `X`'s Arc, mutated
17652    /// in-place by `Y`) and silently reads POST-`Y` bytes. No error;
17653    /// wrong numbers.
17654    #[test]
17655    fn pipelined_write_slice_reshape_adopted_arc_reader_reads_pre_write_bytes() {
17656        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
17657        let mut cache = StorageCache::new();
17658
17659        let b_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
17660        let src1_id = cpu_const_f32(&graph, &mut cache, &[1.0, 2.0], &[2]);
17661        let src2_id = cpu_const_f32(&graph, &mut cache, &[99.0, 98.0], &[2]);
17662
17663        let (x_id, k_id, y_id) = {
17664            let mut g = graph.write().unwrap();
17665            let x_id = g.push(Node {
17666                op: Op::WriteSlice {
17667                    ranges: vec![(0, 2)],
17668                    dyn_offset: None,
17669                },
17670                inputs: vec![b_id, src1_id],
17671                shape: Shape::from_dims(&[4]),
17672                dtype: DType::F32,
17673            });
17674            let s_id = g.push(Node {
17675                // OFFSET-0 contiguous prefix slice — ContiguizeOf's
17676                // zero-copy fast path requires this at execute time.
17677                op: Op::Slice {
17678                    dim: 0,
17679                    start: 0,
17680                    len: 2,
17681                },
17682                inputs: vec![x_id],
17683                shape: Shape::from_dims(&[2]),
17684                dtype: DType::F32,
17685            });
17686            let r_id = g.push(Node {
17687                op: Op::Reshape(Shape::from_dims(&[2])),
17688                inputs: vec![s_id],
17689                shape: Shape::from_dims(&[2]),
17690                dtype: DType::F32,
17691            });
17692            let k_id = g.push(Node {
17693                op: Op::Relu,
17694                inputs: vec![r_id],
17695                shape: Shape::from_dims(&[2]),
17696                dtype: DType::F32,
17697            });
17698            // Round 2 OVERLAPS round 1's [0,2) range (not the [2,4)
17699            // tail) so a wrong-order execution is numerically visible
17700            // in K's output — a disjoint round 2 would corrupt bytes
17701            // K never reads, masking the defect.
17702            let y_id = g.push(Node {
17703                op: Op::WriteSlice {
17704                    ranges: vec![(0, 2)],
17705                    dyn_offset: None,
17706                },
17707                inputs: vec![x_id, src2_id],
17708                shape: Shape::from_dims(&[4]),
17709                dtype: DType::F32,
17710            });
17711            g.set_target_backend(x_id, BackendId::Cpu);
17712            g.set_target_backend(k_id, BackendId::Cpu);
17713            g.set_target_backend(y_id, BackendId::Cpu);
17714            (x_id, k_id, y_id)
17715        };
17716        let _ = x_id;
17717
17718        let plan = fuel_graph::opt::execution_plan(&graph.read().unwrap(), &[k_id, y_id]);
17719        eprintln!(
17720            "[diagnostic reshape-adopted-arc] execution_plan = {:?}",
17721            plan,
17722        );
17723
17724        let outputs = PipelinedExecutor::realize_many(Arc::clone(&graph), &[k_id, y_id], cache)
17725            .expect("realize_many");
17726        let (k_arc, _) = &outputs[0];
17727        let guard = k_arc.read().unwrap();
17728        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
17729            panic!("expected Cpu storage");
17730        };
17731        let out: &[f32] = c.as_slice().unwrap();
17732        // K = relu(reshape(slice(X,0,2))) must read PRE-round-2 bytes:
17733        // relu([1.0, 2.0]) = [1.0, 2.0]. Round 2 overwrites the SAME
17734        // [0,2) range with [99.0, 98.0] — if Y (round 2) runs before K
17735        // (the ordering defect), K instead observes [99.0, 98.0].
17736        assert_eq!(
17737            out,
17738            &[1.0, 2.0],
17739            "K must read PRE-round-2 bytes through the adopted Arc; got {:?} \
17740             (post-round-2 corruption if this fails)",
17741            out,
17742        );
17743    }
17744
17745    /// The MLA-decode shape from `rebind_latent_cache_fresh_graph`'s doc
17746    /// (`fuel-core/src/lazy_deepseek2.rs`): layer L's post-append buffer
17747    /// `X_L_N` (round N) is read TWICE within one realize call — once
17748    /// (non-destructively) through a Slice+Reshape "attention math" view
17749    /// chain whose result becomes an ancestor of layer L+1's round-N
17750    /// write, and again as the DESTINATION of layer L's round-(N+1)
17751    /// append. Reproduces the same Reshape-adoption gap as
17752    /// `pipelined_write_slice_reshape_adopted_arc_reader_reads_pre_write_bytes`
17753    /// at 2-layer scale, confirming the defect is not an artifact of the
17754    /// single-hop minimal form.
17755    #[test]
17756    fn pipelined_write_slice_mla_two_layer_round2_reshape_reader_not_stranded() {
17757        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
17758        let mut cache = StorageCache::new();
17759
17760        let b_l_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
17761        let src_l_n_id = cpu_const_f32(&graph, &mut cache, &[1.0, 2.0], &[2]);
17762        let b_l1_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
17763        let src_l_n1_id = cpu_const_f32(&graph, &mut cache, &[99.0, 98.0], &[2]);
17764
17765        let (x_l_n1_id, x_l1_n_id) = {
17766            let mut g = graph.write().unwrap();
17767            // Round N, layer L: append src_l_n into b_l.
17768            let x_l_n = g.push(Node {
17769                op: Op::WriteSlice {
17770                    ranges: vec![(0, 2)],
17771                    dyn_offset: None,
17772                },
17773                inputs: vec![b_l_id, src_l_n_id],
17774                shape: Shape::from_dims(&[4]),
17775                dtype: DType::F32,
17776            });
17777            // "Attention math" for round N at layer L: read the filled
17778            // prefix, reshape (head-split-style hop), then a kernel.
17779            let s_l_n = g.push(Node {
17780                op: Op::Slice {
17781                    dim: 0,
17782                    start: 0,
17783                    len: 2,
17784                },
17785                inputs: vec![x_l_n],
17786                shape: Shape::from_dims(&[2]),
17787                dtype: DType::F32,
17788            });
17789            let rs_l_n = g.push(Node {
17790                op: Op::Reshape(Shape::from_dims(&[2])),
17791                inputs: vec![s_l_n],
17792                shape: Shape::from_dims(&[2]),
17793                dtype: DType::F32,
17794            });
17795            let r_l_n = g.push(Node {
17796                op: Op::Relu,
17797                inputs: vec![rs_l_n],
17798                shape: Shape::from_dims(&[2]),
17799                dtype: DType::F32,
17800            });
17801            // Round N, layer L+1: append the attention-math result.
17802            let x_l1_n = g.push(Node {
17803                op: Op::WriteSlice {
17804                    ranges: vec![(0, 2)],
17805                    dyn_offset: None,
17806                },
17807                inputs: vec![b_l1_id, r_l_n],
17808                shape: Shape::from_dims(&[4]),
17809                dtype: DType::F32,
17810            });
17811            // Round N+1, layer L: append into x_l_n directly (SAME node
17812            // s_l_n/rs_l_n/r_l_n read from) — OVERLAPPING range so a
17813            // wrong-order execution is numerically visible downstream.
17814            let x_l_n1 = g.push(Node {
17815                op: Op::WriteSlice {
17816                    ranges: vec![(0, 2)],
17817                    dyn_offset: None,
17818                },
17819                inputs: vec![x_l_n, src_l_n1_id],
17820                shape: Shape::from_dims(&[4]),
17821                dtype: DType::F32,
17822            });
17823            g.set_target_backend(x_l_n, BackendId::Cpu);
17824            g.set_target_backend(r_l_n, BackendId::Cpu);
17825            g.set_target_backend(x_l1_n, BackendId::Cpu);
17826            g.set_target_backend(x_l_n1, BackendId::Cpu);
17827            (x_l_n1, x_l1_n)
17828        };
17829
17830        let plan = fuel_graph::opt::execution_plan(&graph.read().unwrap(), &[x_l1_n_id, x_l_n1_id]);
17831        eprintln!("[diagnostic mla-2-layer] execution_plan = {:?}", plan);
17832
17833        let outputs =
17834            PipelinedExecutor::realize_many(Arc::clone(&graph), &[x_l1_n_id, x_l_n1_id], cache)
17835                .expect("realize_many");
17836        // outputs[0] = x_l1_n = write_slice(b_l1, relu(reshape(slice(x_l_n))))
17837        // Must reflect round-N's PRE-round-(N+1) bytes: relu([1,2]) = [1,2].
17838        let (x_l1_n_arc, _) = &outputs[0];
17839        let guard = x_l1_n_arc.read().unwrap();
17840        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
17841            panic!("expected Cpu storage");
17842        };
17843        let out: &[f32] = c.as_slice().unwrap();
17844        assert_eq!(
17845            out,
17846            &[1.0, 2.0, 0.0, 0.0],
17847            "layer L+1's round-N append must reflect PRE-round-(N+1) attention \
17848             math output; got {:?} (post-round-(N+1) corruption if this fails)",
17849            out,
17850        );
17851    }
17852}