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    /// PR-C1 behavior contract: `realize_with_optimized_route` with an
8800    /// **empty** route (the no-pressure / no-telemetry case) is
8801    /// byte-identical to `realize_with_optimized` (arm-0). On a branchless
8802    /// graph the route has no branches to resolve, so both must produce
8803    /// the same bytes — realize is unchanged from Phase B.
8804    #[test]
8805    fn realize_with_optimized_route_empty_equals_arm0() {
8806        use crate::optimize::OptimizedGraph;
8807
8808        let build = || {
8809            let graph = Arc::new(RwLock::new(Graph::new()));
8810            let (lhs_id, rhs_id, add_id) = {
8811                let mut g = graph.write().unwrap();
8812                let lhs_id = g.push(Node {
8813                    op: Op::Const,
8814                    inputs: vec![],
8815                    shape: Shape::from_dims(&[3]),
8816                    dtype: DType::F32,
8817                });
8818                let rhs_id = g.push(Node {
8819                    op: Op::Const,
8820                    inputs: vec![],
8821                    shape: Shape::from_dims(&[3]),
8822                    dtype: DType::F32,
8823                });
8824                let add_id = g.push(Node {
8825                    op: Op::Add,
8826                    inputs: vec![lhs_id, rhs_id],
8827                    shape: Shape::from_dims(&[3]),
8828                    dtype: DType::F32,
8829                });
8830                g.set_target_backend(add_id, BackendId::Cpu);
8831                (lhs_id, rhs_id, add_id)
8832            };
8833            let mut inputs = StorageCache::new();
8834            inputs.insert(
8835                lhs_id,
8836                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
8837                    1.0_f32, 2.0, 3.0,
8838                ]))),
8839            );
8840            inputs.insert(
8841                rhs_id,
8842                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
8843                    10.0_f32, 20.0, 30.0,
8844                ]))),
8845            );
8846            (graph, add_id, inputs)
8847        };
8848
8849        let read_bytes = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8850            let guard = arc.read().unwrap();
8851            match &guard.inner {
8852                fuel_memory::BackendStorage::Cpu(c) => {
8853                    c.as_slice::<f32>().expect("f32 cast").to_vec()
8854                }
8855                _ => panic!("expected CPU output"),
8856            }
8857        };
8858
8859        // Stamp the fixture with the LIVE topology generation rather than a
8860        // hard-coded 0. The executor's chunk-boundary check compares the plan's
8861        // stamped generation against `topology_generation()`; a real
8862        // `OptimizedGraph` carries the generation snapshotted at optimize time
8863        // (`plan.rs` `compile_plan`, which reads it *after* the bindings table
8864        // is warm), so it already reflects every registered backend. Force
8865        // `global_bindings()` init here so any feature-gated auto-registration
8866        // has run and settled the counter before we read it — otherwise a stale
8867        // read would be bumped out from under us the first time realize warms
8868        // the bindings. Under default features this is 0; under
8869        // `--features vulkan`, `register_derived_gpu_caps` bumps it to 1.
8870        drop(global_bindings());
8871        let live_gen = crate::dispatch::topology_generation();
8872
8873        // Arm-0 path.
8874        let (g_a, add_a, in_a) = build();
8875        let opt_a = OptimizedGraph {
8876            roots: vec![add_a],
8877            generation: live_gen,
8878            placements: None,
8879            eviction: None,
8880        };
8881        let (arm0_arc, _) = PipelinedExecutor::realize_with_optimized(g_a, add_a, in_a, &opt_a)
8882            .expect("arm-0 realize");
8883        let arm0 = read_bytes(&arm0_arc);
8884
8885        // Empty-route path — must match arm-0 exactly.
8886        let (g_r, add_r, in_r) = build();
8887        let opt_r = OptimizedGraph {
8888            roots: vec![add_r],
8889            generation: live_gen,
8890            placements: None,
8891            eviction: None,
8892        };
8893        let empty_route = PickedRoute::new();
8894        let (route_arc, _) =
8895            PipelinedExecutor::realize_with_optimized_route(g_r, add_r, in_r, &opt_r, &empty_route)
8896                .expect("empty-route realize");
8897        let routed = read_bytes(&route_arc);
8898
8899        assert_eq!(arm0, vec![11.0, 22.0, 33.0]);
8900        assert_eq!(
8901            routed, arm0,
8902            "an empty route realizes byte-identically to arm-0 (Phase B contract)",
8903        );
8904    }
8905
8906    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
8907    /// §5): [`PipelinedExecutor::realize_with_optimized_picking_cached_env`]
8908    /// over a shared `order_cache` must (a) realize byte-identically to the
8909    /// uncached arm-0 path, on both the cold (empty cache) and warm
8910    /// (populated cache) call, and (b) actually populate the cache on the
8911    /// first call rather than silently never using it.
8912    #[test]
8913    fn realize_with_optimized_picking_cached_env_matches_arm0_cold_and_warm() {
8914        use crate::optimize::OptimizedGraph;
8915        use std::sync::OnceLock;
8916
8917        let build = || {
8918            let graph = Arc::new(RwLock::new(Graph::new()));
8919            let (lhs_id, rhs_id, add_id) = {
8920                let mut g = graph.write().unwrap();
8921                let lhs_id = g.push(Node {
8922                    op: Op::Const,
8923                    inputs: vec![],
8924                    shape: Shape::from_dims(&[3]),
8925                    dtype: DType::F32,
8926                });
8927                let rhs_id = g.push(Node {
8928                    op: Op::Const,
8929                    inputs: vec![],
8930                    shape: Shape::from_dims(&[3]),
8931                    dtype: DType::F32,
8932                });
8933                let add_id = g.push(Node {
8934                    op: Op::Add,
8935                    inputs: vec![lhs_id, rhs_id],
8936                    shape: Shape::from_dims(&[3]),
8937                    dtype: DType::F32,
8938                });
8939                g.set_target_backend(add_id, BackendId::Cpu);
8940                (lhs_id, rhs_id, add_id)
8941            };
8942            let mut inputs = StorageCache::new();
8943            inputs.insert(
8944                lhs_id,
8945                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
8946                    1.0_f32, 2.0, 3.0,
8947                ]))),
8948            );
8949            inputs.insert(
8950                rhs_id,
8951                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
8952                    10.0_f32, 20.0, 30.0,
8953                ]))),
8954            );
8955            (graph, add_id, inputs)
8956        };
8957        let read_bytes = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8958            let guard = arc.read().unwrap();
8959            match &guard.inner {
8960                fuel_memory::BackendStorage::Cpu(c) => {
8961                    c.as_slice::<f32>().expect("f32 cast").to_vec()
8962                }
8963                _ => panic!("expected CPU output"),
8964            }
8965        };
8966
8967        drop(global_bindings());
8968        let live_gen = crate::dispatch::topology_generation();
8969
8970        let (g, add, inputs) = build();
8971        let optimized = OptimizedGraph {
8972            roots: vec![add],
8973            generation: live_gen,
8974            placements: None,
8975            eviction: None,
8976        };
8977        let order_cache: OnceLock<Vec<NodeId>> = OnceLock::new();
8978        assert!(order_cache.get().is_none(), "sanity: cache starts empty");
8979
8980        // Cold call: cache miss, must compute AND populate.
8981        let (cold_arc, _) = PipelinedExecutor::realize_with_optimized_picking_cached_env(
8982            g.clone(),
8983            add,
8984            inputs,
8985            &optimized,
8986            &order_cache,
8987            None,
8988            None,
8989            SymEnv::default(),
8990        )
8991        .expect("cold cached realize");
8992        assert_eq!(read_bytes(&cold_arc), vec![11.0, 22.0, 33.0]);
8993        assert!(
8994            order_cache.get().is_some(),
8995            "the cold call must populate order_cache, not leave it empty"
8996        );
8997        let cached_order_after_cold = order_cache.get().unwrap().clone();
8998
8999        // Warm call: cache hit. Fresh inputs (same graph, new values) so the
9000        // realized OUTPUT differs from the cold call while the dispatch
9001        // ORDER (what's cached) must not change.
9002        let mut warm_inputs = StorageCache::new();
9003        warm_inputs.insert(
9004            g.read().unwrap().node(add).inputs[0],
9005            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9006                100.0_f32, 200.0, 300.0,
9007            ]))),
9008        );
9009        warm_inputs.insert(
9010            g.read().unwrap().node(add).inputs[1],
9011            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9012                1.0_f32, 2.0, 3.0,
9013            ]))),
9014        );
9015        let (warm_arc, _) = PipelinedExecutor::realize_with_optimized_picking_cached_env(
9016            g,
9017            add,
9018            warm_inputs,
9019            &optimized,
9020            &order_cache,
9021            None,
9022            None,
9023            SymEnv::default(),
9024        )
9025        .expect("warm cached realize");
9026        assert_eq!(
9027            read_bytes(&warm_arc),
9028            vec![101.0, 202.0, 303.0],
9029            "warm call must realize its OWN rebound inputs, not replay stale output",
9030        );
9031        assert_eq!(
9032            order_cache.get().unwrap(),
9033            &cached_order_after_cold,
9034            "the warm call must reuse the SAME cached order, not recompute a different one",
9035        );
9036    }
9037
9038    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
9039    /// §5), PM review question: does `OrderSource::Cached` weaken the
9040    /// existing `TopologyChanged` chunk-boundary check? No — proven at the
9041    /// unit level (not a live topology-bump integration test, deliberately:
9042    /// `bump_topology_generation()` mutates a process-wide atomic shared by
9043    /// every concurrently-running test in this binary, including the cold/
9044    /// warm cache test above, which reads it into a local at the start of
9045    /// ITS OWN body and would flake if another test's bump landed mid-call;
9046    /// introducing that cross-test hazard isn't worth it when the two arms'
9047    /// `generation_for` expressions are provably identical). `generation_for`
9048    /// is private to this module, so it's tested directly here: given the
9049    /// SAME `&OptimizedGraph`, `Cached` and `Optimized` must report the
9050    /// IDENTICAL generation — the chunk-boundary check that compares this
9051    /// value against the LIVE `topology_generation()` fires exactly the
9052    /// same way for both, so caching cannot silently skip or weaken it.
9053    #[test]
9054    fn cached_generation_for_matches_optimized_generation_for() {
9055        let optimized = OptimizedGraph {
9056            roots: vec![NodeId(0)],
9057            generation: 42,
9058            placements: None,
9059            eviction: None,
9060        };
9061        let order_cache: std::sync::OnceLock<Vec<NodeId>> = std::sync::OnceLock::new();
9062
9063        let optimized_gen = generation_for(&OrderSource::Optimized {
9064            optimized: &optimized,
9065            route: None,
9066        });
9067        let cached_gen = generation_for(&OrderSource::Cached {
9068            optimized: &optimized,
9069            order_cache: &order_cache,
9070        });
9071        assert_eq!(
9072            optimized_gen,
9073            Some(42),
9074            "sanity: Optimized reports the OptimizedGraph's own generation",
9075        );
9076        assert_eq!(
9077            cached_gen, optimized_gen,
9078            "Cached must report the SAME generation as Optimized for the same \
9079             OptimizedGraph -- the TopologyChanged check cannot tell the two apart, \
9080             by construction, so caching cannot silently weaken it",
9081        );
9082    }
9083
9084    /// **PR-C3 reorder-invariance gate (CPU, runnable — ORDERING level).**
9085    /// The auto-overlap reorder is a HINT: it changes only *which order*
9086    /// independent device runs dispatch in, never *which* nodes run nor the
9087    /// result. The byte-identical-OUTPUT proof is necessarily LIVE (the
9088    /// reorder fires only on a ≥2-device graph, which needs ≥2 real backends
9089    /// to realize — see `cuda_vulkan_multidevice_realize_live`'s
9090    /// `[22,86,192,340]` oracle, which now flows through this reorder, plus
9091    /// the dual-GPU `cuda_vulkan_overlap_bench_live` arbitrary-graph
9092    /// auto-overlap gate). THIS test proves the ordering-level invariant on a
9093    /// CPU-only path: the C3 reorder of a two-device graph is a valid
9094    /// topological **permutation** of the un-reordered topo order — same node
9095    /// multiset, every node still after its inputs — that genuinely DIFFERS
9096    /// from the un-reordered order (so the reorder fired). Because the
9097    /// executor caches each node's result and every op is deterministic,
9098    /// realizing any valid topological order yields identical bytes; this
9099    /// test guards the precondition (a valid permutation) that makes that so.
9100    #[test]
9101    fn c3_reorder_is_a_valid_topo_permutation() {
9102        // Two INDEPENDENT device sub-chains over distinct consts reconverging
9103        // at a final CUDA add, the Vulkan root bridged to CUDA by an explicit
9104        // Op::Copy (a residency seam = its own run). Reconverge inputs in the
9105        // "wrong" (cuda-first) order, the order the un-reordered topo DFS pops
9106        // CUDA-last — exactly the arbitrary-graph shape the auto-overlap pass
9107        // must fix. The chains are UNARY (Relu) so each stays a single
9108        // contiguous run (no const-re-read fan-in fragmenting them), exactly
9109        // like the live benchmark's `relu(mul·add)` chains; the CUDA chain is
9110        // HEAVIER (4 vs 2) so the critical-path reorder emits it first.
9111        // (Stamps only; not realized here — the ordering proof, CPU-runnable.)
9112        let n = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9113            g.push(Node {
9114                op,
9115                inputs,
9116                shape: Shape::from_dims(&[3]),
9117                dtype: DType::F32,
9118            })
9119        };
9120        let mut g = Graph::new();
9121        let ca = n(&mut g, Op::Const, vec![]);
9122        let cb = n(&mut g, Op::Const, vec![]);
9123        // CUDA chain — HEAVIER (4 unary stages, one contiguous run).
9124        let mut cprev = ca;
9125        for _ in 0..4 {
9126            cprev = n(&mut g, Op::Relu, vec![cprev]);
9127            g.set_target_backend(cprev, BackendId::Cuda);
9128        }
9129        let c2 = cprev; // CUDA chunk root
9130        // Vulkan chain — lighter (2 unary stages).
9131        let mut vprev = cb;
9132        for _ in 0..2 {
9133            vprev = n(&mut g, Op::Relu, vec![vprev]);
9134            g.set_target_backend(vprev, BackendId::Vulkan);
9135        }
9136        let v2 = vprev; // Vulkan chunk root
9137        // Vulkan -> CUDA copy (residency seam), then reconverge on CUDA with
9138        // inputs [cuda_root, copy] (cuda-first).
9139        let copy = g.push(Node {
9140            op: Op::Copy {
9141                target: DeviceLocation::Cuda { gpu_id: 0 },
9142            },
9143            inputs: vec![v2],
9144            shape: Shape::from_dims(&[3]),
9145            dtype: DType::F32,
9146        });
9147        g.set_target_backend(copy, BackendId::Cuda);
9148        let out = n(&mut g, Op::Add, vec![c2, copy]);
9149        g.set_target_backend(out, BackendId::Cuda);
9150
9151        let unreordered = execution_plan(&g, &[out]);
9152        let reordered = fuel_graph::lower_runs_arm0(&g, &[out]);
9153
9154        // (1) The reorder FIRED — the order changed (else the test is
9155        //     vacuous + auto-overlap did nothing on an arbitrary graph).
9156        assert_ne!(
9157            reordered, unreordered,
9158            "the C3 reorder must change the order on a two-device graph; \
9159             reordered={reordered:?} unreordered={unreordered:?}",
9160        );
9161
9162        // (2) Same node multiset — a permutation, no add/drop.
9163        let mut a = unreordered.clone();
9164        let mut b = reordered.clone();
9165        a.sort();
9166        b.sort();
9167        assert_eq!(a, b, "the reorder is a permutation of the same node set");
9168
9169        // (3) The reordered order is a VALID topological order: every node
9170        //     appears after all of its inputs that are in the order.
9171        let pos: std::collections::HashMap<NodeId, usize> = reordered
9172            .iter()
9173            .enumerate()
9174            .map(|(i, &node)| (node, i))
9175            .collect();
9176        for (i, &node) in reordered.iter().enumerate() {
9177            for &inp in &g.node(node).inputs {
9178                if let Some(&j) = pos.get(&inp) {
9179                    assert!(
9180                        j < i,
9181                        "input {inp:?} of {node:?} must precede it in the reordered \
9182                         order; reordered={reordered:?}",
9183                    );
9184                }
9185            }
9186        }
9187
9188        // (4) The overlap-relevant property: BOTH device producer chunks
9189        //     (the CUDA root c2, the Vulkan root v2) are emitted BEFORE the
9190        //     host-blocking cross-device copy — the A4b overlap topology the
9191        //     un-reordered cuda-last DFS violates — AND the HEAVIER CUDA chunk
9192        //     is emitted first (critical-path: the auto-submit device runs
9193        //     earliest, the live-overlap regression guard).
9194        let p = |node: NodeId| pos[&node];
9195        assert!(p(c2) < p(copy), "CUDA chunk before the cross-device copy");
9196        assert!(p(v2) < p(copy), "Vulkan chunk before the cross-device copy");
9197        assert!(
9198            p(c2) < p(v2),
9199            "the heavier CUDA chunk is emitted before the lighter Vulkan chunk \
9200             (critical-path heavy-first); reordered={reordered:?}",
9201        );
9202    }
9203
9204    /// **C3 follow-on — the OPERAND-ORDER-INVARIANCE gate (CPU, runnable —
9205    /// the reliable operand-independence proof).** The residual the live
9206    /// `cuda_vulkan_overlap_bench_live` benchmark targets is whether the
9207    /// reconverge OPERAND order (`xc.add(&xv)` vs `xv.add(&xc)`) changes the
9208    /// wall-clock overlap. Wall-clock is thermally noisy on a heterogeneous
9209    /// dev box; the DETERMINISTIC root guarantee is this: the C3-reordered
9210    /// dispatch order the executor consumes is **byte-identical for both
9211    /// operand orders**. If the lowered order is the same, the executor
9212    /// processes the SAME WorkItem stream with the SAME cross-device
9213    /// submit/wait timing, so overlap cannot depend on the operand order.
9214    ///
9215    /// This builds the SAME two-device reconverge as
9216    /// `c3_reorder_is_a_valid_topo_permutation` but TWICE — once cuda-first
9217    /// (`add(cuda_root, copy)`), once vulkan-first (`add(copy, cuda_root)`)
9218    /// — over structurally identical graphs (same node ids, only the
9219    /// reconverge's two inputs swapped) and asserts `lower_runs_arm0` emits
9220    /// the identical op/device run sequence. The live executor trace confirms
9221    /// the same: both operand orders produce the identical WorkItem stream
9222    /// (the eager-submit/drain/wait sequence at every cross-device copy is the
9223    /// same, and the CUDA chunk is enqueued first in both).
9224    #[test]
9225    fn c3_reorder_is_operand_order_invariant() {
9226        // Build the two-device reconverge with the reconverge inputs in the
9227        // given order; return (graph, out) over a FRESH graph so node ids line
9228        // up 1:1 between the two builds (only the add's input order differs).
9229        let build = |cuda_first: bool| -> (Graph, NodeId) {
9230            let n = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9231                g.push(Node {
9232                    op,
9233                    inputs,
9234                    shape: Shape::from_dims(&[3]),
9235                    dtype: DType::F32,
9236                })
9237            };
9238            let mut g = Graph::new();
9239            let ca = n(&mut g, Op::Const, vec![]);
9240            let cb = n(&mut g, Op::Const, vec![]);
9241            let mut cprev = ca;
9242            for _ in 0..4 {
9243                cprev = n(&mut g, Op::Relu, vec![cprev]);
9244                g.set_target_backend(cprev, BackendId::Cuda);
9245            }
9246            let c2 = cprev;
9247            let mut vprev = cb;
9248            for _ in 0..2 {
9249                vprev = n(&mut g, Op::Relu, vec![vprev]);
9250                g.set_target_backend(vprev, BackendId::Vulkan);
9251            }
9252            let v2 = vprev;
9253            let copy = g.push(Node {
9254                op: Op::Copy {
9255                    target: DeviceLocation::Cuda { gpu_id: 0 },
9256                },
9257                inputs: vec![v2],
9258                shape: Shape::from_dims(&[3]),
9259                dtype: DType::F32,
9260            });
9261            g.set_target_backend(copy, BackendId::Cuda);
9262            // The ONE knob: the reconverge's two inputs, swapped.
9263            let inputs = if cuda_first {
9264                vec![c2, copy]
9265            } else {
9266                vec![copy, c2]
9267            };
9268            let out = n(&mut g, Op::Add, inputs);
9269            g.set_target_backend(out, BackendId::Cuda);
9270            (g, out)
9271        };
9272
9273        let (g_cf, out_cf) = build(true);
9274        let (g_vf, out_vf) = build(false);
9275
9276        // Lower both via the production path (dispatch_order → lower_runs_arm0
9277        // → device_alternating_order, the C3 reorder).
9278        let order_cf = fuel_graph::lower_runs_arm0(&g_cf, &[out_cf]);
9279        let order_vf = fuel_graph::lower_runs_arm0(&g_vf, &[out_vf]);
9280
9281        // The decisive guarantee: the lowered dispatch order — as an
9282        // (op, device) sequence — is IDENTICAL for both operand orders. (Node
9283        // ids can differ if the build assigned them differently, but here the
9284        // builds are structurally identical so even the ids match; compare the
9285        // op/device sequence to be robust + descriptive on failure.)
9286        let tag = |g: &Graph, ids: &[NodeId]| -> Vec<(String, Option<BackendId>)> {
9287            ids.iter()
9288                .map(|&id| (format!("{:?}", g.node(id).op), g.target_backend(id)))
9289                .collect()
9290        };
9291        let seq_cf = tag(&g_cf, &order_cf);
9292        let seq_vf = tag(&g_vf, &order_vf);
9293        assert_eq!(
9294            seq_cf, seq_vf,
9295            "the C3-reordered dispatch order MUST be identical for both \
9296             reconverge operand orders (operand-order-invariance — the \
9297             executor then sees the same WorkItem stream regardless of \
9298             operand order, so overlap is operand-insensitive).\n\
9299             cuda-first = {seq_cf:?}\nvulkan-first = {seq_vf:?}",
9300        );
9301    }
9302
9303    /// A selector that always takes the LAST arm (arm 1) so a non-arm-0
9304    /// pick is observable (a `WinnerSelector` picks arm-0 ⇒ empty route).
9305    #[cfg(test)]
9306    #[derive(Debug)]
9307    struct PickLast;
9308    #[cfg(test)]
9309    impl RuntimeSelector for PickLast {
9310        fn select<'a>(
9311            &self,
9312            set: &'a crate::ranker::AlternativeSet,
9313        ) -> Option<&'a crate::ranker::Candidate> {
9314            set.alternatives().last()
9315        }
9316    }
9317
9318    /// Build the 2-arm diamond (mirrors `route_picker::tests::diamond`):
9319    /// arm-0 on CUDA, arm-1 on CPU; the arm exits carry their
9320    /// `target_backend` so the picker reads each arm's placement. Returns
9321    /// `(graph_arc, branch, post)`.
9322    #[cfg(test)]
9323    fn picking_diamond() -> (Arc<RwLock<Graph>>, NodeId, NodeId) {
9324        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9325            g.push(Node {
9326                op,
9327                inputs,
9328                shape: Shape::from_dims(&[2]),
9329                dtype: DType::F32,
9330            })
9331        };
9332        let mut g = Graph::new();
9333        let pre = node(&mut g, Op::Const, vec![]);
9334        let diverge = node(&mut g, Op::Relu, vec![pre]);
9335        let arm0 = node(&mut g, Op::Silu, vec![diverge]);
9336        let arm1 = node(&mut g, Op::GeluTanh, vec![diverge]);
9337        g.set_target_backend(arm0, BackendId::Cuda);
9338        g.set_target_backend(arm1, BackendId::Cpu);
9339        let reconverge = node(&mut g, Op::Relu, vec![arm0]);
9340        let mut b = g.open_branch(diverge);
9341        b.add_arm(arm0);
9342        b.add_arm(arm1);
9343        let branch = b
9344            .finalize_branches(&mut g, reconverge)
9345            .expect("well-formed 2-arm branch")
9346            .expect("2 arms survive");
9347        let post = node(&mut g, Op::Tanh, vec![reconverge]);
9348        (Arc::new(RwLock::new(g)), branch, post)
9349    }
9350
9351    /// Step E Phase C, PR C1: the streaming picking entry's gate.
9352    /// `streaming_pick_for` (the streaming successor of the old one-shot
9353    /// `pick_route_for`) must (1) return `Some(pick)` when a selector + a
9354    /// branch are present (⇒ the `OrderSource::Streaming` walk), (2) return
9355    /// `None` with no selector (the `runtime_selector_disabled` opt-out ⇒
9356    /// arm-0), and (3) short-circuit to `None` on a branchless graph (the
9357    /// fast-path ⇒ the untouched `dispatch_order` lowering).
9358    #[test]
9359    fn streaming_pick_for_gates() {
9360        let (graph, _branch, post) = picking_diamond();
9361        let _ = post;
9362
9363        // (1) selector + branch ⇒ Some(pick).
9364        let sel: Arc<dyn RuntimeSelector> = Arc::new(PickLast);
9365        assert!(
9366            PipelinedExecutor::streaming_pick_for(&graph, Some(sel.clone()), None)
9367                .expect("ok")
9368                .is_some(),
9369            "selector + branch ⇒ a streaming pick",
9370        );
9371
9372        // (2) no selector ⇒ None (arm-0 lowering).
9373        assert!(
9374            PipelinedExecutor::streaming_pick_for(&graph, None, None)
9375                .expect("ok")
9376                .is_none(),
9377            "no selector ⇒ no streaming pick (arm-0 lowering)",
9378        );
9379
9380        // (3) branchless graph + selector ⇒ None (the fast-path).
9381        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9382            g.push(Node {
9383                op,
9384                inputs,
9385                shape: Shape::from_dims(&[2]),
9386                dtype: DType::F32,
9387            })
9388        };
9389        let bl_graph = {
9390            let mut g = Graph::new();
9391            let c1 = node(&mut g, Op::Const, vec![]);
9392            let c2 = node(&mut g, Op::Const, vec![]);
9393            let add = node(&mut g, Op::Add, vec![c1, c2]);
9394            g.set_target_backend(add, BackendId::Cpu);
9395            Arc::new(RwLock::new(g))
9396        };
9397        assert!(
9398            PipelinedExecutor::streaming_pick_for(&bl_graph, Some(sel), None)
9399                .expect("ok")
9400                .is_none(),
9401            "branchless graph ⇒ no branches ⇒ no streaming pick (fast-path)",
9402        );
9403    }
9404
9405    /// **C1 byte-identity gate (executor layer).** The STREAMED dispatch
9406    /// order — produced by the compiler thread's lazy per-branch resolution
9407    /// (`walk_picked_route_streaming` over `resolve_branch`, the same path
9408    /// `order_for(OrderSource::Streaming)` collects) — equals the ONE-SHOT
9409    /// order (`lower_picked_route` over the route the eager `pick_route`
9410    /// resolves) on the branched diamond, for both arm-0 (WinnerSelector)
9411    /// and arm-1 (PickLast). This is the proof that C1 changes *when* a
9412    /// branch resolves, not *which* arm — the same selector, the same
9413    /// `resolve_branch`, the same emitted order.
9414    #[test]
9415    fn streamed_order_equals_one_shot() {
9416        let (graph, _branch, post) = picking_diamond();
9417        let g = graph.read().unwrap();
9418        let bindings = global_bindings();
9419
9420        for sel in [
9421            Arc::new(crate::ranker::WinnerSelector) as Arc<dyn RuntimeSelector>,
9422            Arc::new(PickLast) as Arc<dyn RuntimeSelector>,
9423        ] {
9424            // One-shot: resolve the whole route, then lower.
9425            let one_shot_route = pick_route(&g, &[post], &bindings, sel.as_ref(), None);
9426            let one_shot = fuel_graph::lower_picked_route(&g, &[post], &one_shot_route);
9427
9428            // Streamed: resolve each branch lazily at the frontier via the
9429            // SAME `resolve_branch` the compiler thread uses.
9430            let streamed = fuel_graph::lower_picked_route_streaming(&g, &[post], |branch| {
9431                resolve_branch(&g, branch, &bindings, sel.as_ref())
9432            });
9433
9434            assert_eq!(
9435                streamed, one_shot,
9436                "streamed order must equal one-shot for selector {sel:?}",
9437            );
9438        }
9439    }
9440
9441    /// ROW 157 / GAP-385: with ONE branch in the graph, the executor realizes a PICKED multi-node arm to the
9442    /// same numbers as arm 0. This is NOT shown for chained branches: with two or more in a row it failed
9443    /// (`input ... not realized`) until the lowering-order fix of 2026-11-17 (ROADMAP row 158); see
9444    /// `chained_branches_realize_equal_to_arm_zero_for_every_combination_of_arms_on_cpu`.
9445    ///
9446    /// A residual block on the host: `c1 -> relu -> silu -> tanh -> add(c1, .)`. The branch is built by
9447    /// the pathfinder's own `record_branch` (so the clone logic under test is the shipped code) with
9448    /// the alternative backend set to `Cpu`, which lets arm 1 run on this box. The route `{branch: 1}`
9449    /// makes the executor run the cloned three-node stretch; the result must equal the arm-0 result.
9450    ///
9451    /// What this does NOT show: a cross-device arm (the real alternative is another backend, with
9452    /// copies at its entry and exit), nor which arm a live selector picks. The same-backend arms mean
9453    /// the selector cannot map back to arm 1, so the route is given explicitly.
9454    #[test]
9455    fn a_single_picked_multi_node_arm_realizes_equal_to_arm_zero_on_cpu() {
9456        let (arm0, arm1) = realize_residual_block_both_arms(false);
9457        assert_eq!(
9458            arm1, arm0,
9459            "the cloned stretch computes what arm 0 computes"
9460        );
9461        assert_eq!(arm0.len(), 3);
9462        assert!(arm0.iter().all(|v| v.is_finite()));
9463    }
9464
9465    /// POSITIVE CONTROL for the test above (one branch): when the cloned stretch computes something else
9466    /// (Gelu in place of Silu, built by hand), the picked-arm result DIFFERS from arm 0. Without this the
9467    /// equality could pass by the executor ignoring the route and running arm 0 both times.
9468    #[test]
9469    fn a_picked_multi_node_arm_that_differs_changes_the_result() {
9470        let (arm0, arm1) = realize_residual_block_both_arms(true);
9471        assert_ne!(arm1, arm0, "the route must really run the cloned arm");
9472    }
9473
9474    /// Realize `c1 -> relu -> silu -> tanh -> add(c1, .)` through arm 0 and through arm 1. Arm 1 is the
9475    /// clone `record_branch` makes, or, when `control` is set, a hand-built clone whose middle node is
9476    /// Gelu instead of Silu.
9477    #[cfg(test)]
9478    fn realize_residual_block_both_arms(control: bool) -> (Vec<f32>, Vec<f32>) {
9479        use crate::optimize::OptimizedGraph;
9480        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9481            match &arc.read().unwrap().inner {
9482                fuel_memory::BackendStorage::Cpu(c) => c.as_slice::<f32>().expect("f32").to_vec(),
9483                _ => panic!("expected CPU output"),
9484            }
9485        };
9486        let build = || {
9487            let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9488                let id = g.push(Node {
9489                    op,
9490                    inputs,
9491                    shape: Shape::from_dims(&[3]),
9492                    dtype: DType::F32,
9493                });
9494                g.set_target_backend(id, BackendId::Cpu);
9495                id
9496            };
9497            let mut g = Graph::new();
9498            let c1 = node(&mut g, Op::Const, vec![]);
9499            let r = node(&mut g, Op::Relu, vec![c1]);
9500            let s = node(&mut g, Op::Silu, vec![r]);
9501            let t = node(&mut g, Op::Tanh, vec![s]);
9502            let res = node(&mut g, Op::Add, vec![c1, t]);
9503            let branch = if control {
9504                let r2 = node(&mut g, Op::Relu, vec![c1]);
9505                let s2 = node(&mut g, Op::GeluTanh, vec![r2]);
9506                let t2 = node(&mut g, Op::Tanh, vec![s2]);
9507                let mut b = g.open_branch(c1);
9508                b.add_arm(t);
9509                b.add_arm(t2);
9510                b.finalize_branches(&mut g, res)
9511                    .expect("well-formed")
9512                    .expect("2 arms")
9513            } else {
9514                crate::region_pathfinder::record_branch(
9515                    &mut g,
9516                    c1,
9517                    res,
9518                    &[r, s, t],
9519                    t,
9520                    BackendId::Cpu,
9521                )
9522                .expect("the region records a 2-arm branch")
9523            };
9524            let mut inputs = StorageCache::new();
9525            inputs.insert(
9526                c1,
9527                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9528                    -1.0_f32, 0.5, 2.0,
9529                ]))),
9530            );
9531            (Arc::new(RwLock::new(g)), res, branch, inputs)
9532        };
9533
9534        drop(global_bindings());
9535        let run = |pick_arm1: bool| -> Vec<f32> {
9536            // Another test registering a backend or kernels bumps the process-wide topology generation
9537            // (`bump_topology_generation`, shared by every concurrently running test), and the executor
9538            // then returns `TopologyChanged` ("rebuild and retry") for a plan stamped before the bump.
9539            // Measured: 1 in ~55 full-suite runs at 17 threads, 6 in 110, every one the message
9540            // "generation N ... generation M"; it is not arm choice. Follow the error's own contract
9541            // with a bounded rebuild, and fail loudly on anything else or on 20 stale stamps in a row.
9542            for _attempt in 0..20 {
9543                let (graph, res, branch, inputs) = build();
9544                let opt = OptimizedGraph {
9545                    roots: vec![res],
9546                    generation: crate::dispatch::topology_generation(),
9547                    placements: None,
9548                    eviction: None,
9549                };
9550                let mut route = PickedRoute::new();
9551                if pick_arm1 {
9552                    route.insert(branch, 1);
9553                }
9554                match PipelinedExecutor::realize_with_optimized_route(
9555                    graph, res, inputs, &opt, &route,
9556                ) {
9557                    Ok((arc, _)) => return read(&arc),
9558                    Err(e) if format!("{e}").contains("topology generation") => continue,
9559                    Err(e) => panic!("realize: {e}"),
9560                }
9561            }
9562            panic!("realize: topology generation changed on 20 consecutive attempts")
9563        };
9564        (run(false), run(true))
9565    }
9566
9567    // ===== Row 158: chained region branches with a NON-ZERO arm chosen. The first real run of arm 1 on a
9568    //        GPU failed with "reshape input NodeId(2) of NodeId(3) not realized"; it reproduces on CPU
9569    //        and was a lowering-order bug (`fuel-graph/src/run.rs`): the chosen arm's run was emitted
9570    //        after the reconverge that reads it whenever two or more branches were chained. =====
9571
9572    /// `ids, table -> IndexSelect -> Reshape -> block*` where each block is the residual stretch
9573    /// `relu -> silu -> tanh -> add(x, .)` recorded as a 2-arm branch (arm 1 = the clone), so block `i`'s
9574    /// reconverge is block `i + 1`'s diverge (the shape of the toy Llama graph). Returns
9575    /// `(graph, root, branches, ids_const, table_const, head nodes)`.
9576    #[cfg(test)]
9577    fn head_then_region_chain(
9578        blocks: usize,
9579    ) -> (Graph, NodeId, Vec<NodeId>, NodeId, NodeId, Vec<NodeId>) {
9580        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>, dims: &[usize], dt: DType| {
9581            let id = g.push(Node {
9582                op,
9583                inputs,
9584                shape: Shape::from_dims(dims),
9585                dtype: dt,
9586            });
9587            g.set_target_backend(id, BackendId::Cpu);
9588            id
9589        };
9590        let mut g = Graph::new();
9591        let ids = node(&mut g, Op::Const, vec![], &[3], DType::U32);
9592        let table = node(&mut g, Op::Const, vec![], &[8, 4], DType::F32);
9593        let gathered = node(
9594            &mut g,
9595            Op::IndexSelect { dim: 0 },
9596            vec![table, ids],
9597            &[3, 4],
9598            DType::F32,
9599        );
9600        let mut x = node(
9601            &mut g,
9602            Op::Reshape(Shape::from_dims(&[1, 3, 4])),
9603            vec![gathered],
9604            &[1, 3, 4],
9605            DType::F32,
9606        );
9607        let head = vec![gathered, x];
9608        let mut branches = Vec::new();
9609        for _ in 0..blocks {
9610            let r = node(&mut g, Op::Relu, vec![x], &[1, 3, 4], DType::F32);
9611            let s = node(&mut g, Op::Silu, vec![r], &[1, 3, 4], DType::F32);
9612            let t = node(&mut g, Op::Tanh, vec![s], &[1, 3, 4], DType::F32);
9613            let res = node(&mut g, Op::Add, vec![x, t], &[1, 3, 4], DType::F32);
9614            let branch = crate::region_pathfinder::record_branch(
9615                &mut g,
9616                x,
9617                res,
9618                &[r, s, t],
9619                t,
9620                BackendId::Cpu,
9621            )
9622            .expect("the block records a 2-arm branch");
9623            branches.push(branch);
9624            x = res;
9625        }
9626        (g, x, branches, ids, table, head)
9627    }
9628
9629    /// The route that sends branch `i` to arm 1 iff bit `i` of `mask` is set.
9630    #[cfg(test)]
9631    fn route_from_mask(branches: &[NodeId], mask: usize) -> PickedRoute {
9632        let mut route = PickedRoute::new();
9633        for (i, &b) in branches.iter().enumerate() {
9634            if mask >> i & 1 == 1 {
9635                route.insert(b, 1);
9636            }
9637        }
9638        route
9639    }
9640
9641    /// Why `order` is not a valid dispatch order for the route `mask`, or `None` when it is. Valid: every
9642    /// emitted node's inputs are emitted earlier, are leaves, or are an arm-0 exit whose branch chose
9643    /// arm 1 and whose arm-1 exit was emitted earlier (the alias the compiler thread inserts); the chosen
9644    /// arm's exit is emitted and the other arm's is not.
9645    #[cfg(test)]
9646    fn why_invalid_order(
9647        g: &Graph,
9648        branches: &[NodeId],
9649        mask: usize,
9650        order: &[NodeId],
9651    ) -> Option<String> {
9652        let mut alias: HashMap<NodeId, NodeId> = HashMap::new();
9653        for (i, &b) in branches.iter().enumerate() {
9654            if mask >> i & 1 == 1 {
9655                alias.insert(g.node(b).inputs[0], g.node(b).inputs[1]);
9656            }
9657        }
9658        let mut emitted: HashSet<NodeId> = HashSet::new();
9659        for &n in order {
9660            for &inp in &g.node(n).inputs {
9661                let ok = emitted.contains(&inp)
9662                    || matches!(g.node(inp).op, Op::Const)
9663                    || alias.get(&inp).is_some_and(|a| emitted.contains(a));
9664                if !ok {
9665                    return Some(format!(
9666                        "node {n:?} ({:?}) is emitted before its input {inp:?} ({:?})",
9667                        g.node(n).op,
9668                        g.node(inp).op
9669                    ));
9670                }
9671            }
9672            emitted.insert(n);
9673        }
9674        for (i, &b) in branches.iter().enumerate() {
9675            let arms = &g.node(b).inputs;
9676            let (chosen, other) = if mask >> i & 1 == 1 {
9677                (arms[1], arms[0])
9678            } else {
9679                (arms[0], arms[1])
9680            };
9681            if !emitted.contains(&chosen) {
9682                return Some(format!(
9683                    "branch {i}: the chosen arm exit {chosen:?} is not emitted"
9684                ));
9685            }
9686            if emitted.contains(&other) {
9687                return Some(format!(
9688                    "branch {i}: the other arm exit {other:?} is emitted"
9689                ));
9690            }
9691        }
9692        None
9693    }
9694
9695    /// LOWERING level (no executor): for 1 to 4 chained branches and EVERY combination of arms (not only
9696    /// all arm 1), the frozen and the streaming lowering each emit a valid order, and the two orders are
9697    /// identical for the same picks. Before the fix N=1 passed and every N >= 2 with an arm 1 failed.
9698    #[test]
9699    fn chained_branches_lower_to_a_valid_order_for_every_combination_of_arms() {
9700        for blocks in 1..=4usize {
9701            let (g, root, branches, _ids, _table, head) = head_then_region_chain(blocks);
9702            for mask in 0..(1usize << blocks) {
9703                let route = route_from_mask(&branches, mask);
9704                let frozen = fuel_graph::lower_picked_route(&g, &[root], &route);
9705                let streaming = fuel_graph::lower_picked_route_streaming(&g, &[root], |b| {
9706                    route.get(&b).copied().unwrap_or(0)
9707                });
9708                for (name, order) in [("frozen", &frozen), ("streaming", &streaming)] {
9709                    assert_eq!(
9710                        why_invalid_order(&g, &branches, mask, order),
9711                        None,
9712                        "{name} lowering, blocks={blocks} mask={mask:#b}: order={order:?}"
9713                    );
9714                    assert!(
9715                        head.iter().all(|h| order.contains(h)),
9716                        "{name}, blocks={blocks} mask={mask:#b}: the head must be emitted"
9717                    );
9718                }
9719                assert_eq!(
9720                    frozen, streaming,
9721                    "blocks={blocks} mask={mask:#b}: frozen and streaming differ"
9722                );
9723            }
9724        }
9725    }
9726
9727    /// ROW 158: a chain of CROSS-DEVICE region branches. Block `i` is `e = relu(x); d = silu(e);
9728    /// a = add(d, e); t = tanh(a); res = add(d, t)`, the stretch `a, t` is recorded with its alternative on
9729    /// `Cuda { gpu_id: 0 }` (arm 1) and its exit brought back to the host, and the residency pass inserts
9730    /// the inbound copies of BOTH external inputs (`d` and `e`) of the clone. `res` is the next block's `x`.
9731    /// Returns `(graph, root, branches)`.
9732    #[cfg(test)]
9733    fn cross_device_chain(blocks: usize) -> (Graph, NodeId, Vec<NodeId>) {
9734        use crate::region_pathfinder::try_record_branch;
9735        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
9736        let mut g = Graph::new();
9737        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9738            let id = g.push(Node {
9739                op,
9740                inputs,
9741                shape: Shape::from_dims(&[4]),
9742                dtype: DType::F32,
9743            });
9744            g.set_placement(id, DeviceLocation::Cpu);
9745            g.set_target_backend(id, BackendId::Cpu);
9746            id
9747        };
9748        let mut x = node(&mut g, Op::Const, vec![]);
9749        let mut branches = Vec::new();
9750        for _ in 0..blocks {
9751            let e = node(&mut g, Op::Relu, vec![x]);
9752            let d = node(&mut g, Op::Silu, vec![e]);
9753            let a = node(&mut g, Op::Add, vec![d, e]);
9754            let t = node(&mut g, Op::Tanh, vec![a]);
9755            let res = node(&mut g, Op::Add, vec![d, t]);
9756            let branch = try_record_branch(
9757                &mut g,
9758                d,
9759                res,
9760                &[a, t],
9761                t,
9762                BackendId::Cuda,
9763                cuda0,
9764                DeviceLocation::Cpu,
9765            )
9766            .expect("well-formed branch")
9767            .expect("two arms");
9768            branches.push(branch);
9769            x = res;
9770        }
9771        crate::optimize::insert_residency_copies(
9772            &mut g,
9773            &[x],
9774            &crate::plan::ExecutionPlan::empty(),
9775            DeviceLocation::Cpu,
9776            None,
9777        );
9778        (g, x, branches)
9779    }
9780
9781    /// LOWERING level: the cross-device chain (inbound copies, exit copies, two external inputs per arm)
9782    /// lowers to a valid order for 1 to 4 blocks and EVERY combination of arms, frozen and streaming
9783    /// identical. Found on a GPU run: with the chosen arm's runs moved to the slot of the first run that
9784    /// opens an arm, an inbound `Copy` ran before the main-chain node it reads (`Copy input NodeId(130) of
9785    /// NodeId(255) not realized`).
9786    #[test]
9787    fn cross_device_chains_lower_to_a_valid_order_for_every_combination_of_arms() {
9788        for blocks in 1..=4usize {
9789            let (g, root, branches) = cross_device_chain(blocks);
9790            for mask in 0..(1usize << blocks) {
9791                let route = route_from_mask(&branches, mask);
9792                let frozen = fuel_graph::lower_picked_route(&g, &[root], &route);
9793                let streaming = fuel_graph::lower_picked_route_streaming(&g, &[root], |b| {
9794                    route.get(&b).copied().unwrap_or(0)
9795                });
9796                for (name, order) in [("frozen", &frozen), ("streaming", &streaming)] {
9797                    assert_eq!(
9798                        why_invalid_order(&g, &branches, mask, order),
9799                        None,
9800                        "{name} lowering, blocks={blocks} mask={mask:#b}: order={order:?}"
9801                    );
9802                }
9803                assert_eq!(
9804                    frozen, streaming,
9805                    "blocks={blocks} mask={mask:#b}: frozen and streaming differ"
9806                );
9807            }
9808        }
9809    }
9810
9811    /// A chain of cross-device region branches whose stretch reads a SHARED EARLY value `h` (computed once,
9812    /// before any diverge) as well as its diverge `d`: `fillers` nodes sit between the previous block and
9813    /// `d`, and `h` enters the stretch at its first node (`second_in_middle == false`) or its second.
9814    /// The residency pass inserts ONE inbound copy of `h` onto the alternative device and CSEs it between
9815    /// every block's arm 1, so that copy is in branch 1's arm 1 and in branch 2's arm 1 at once.
9816    #[cfg(test)]
9817    fn shared_early_input_chain(
9818        blocks: usize,
9819        fillers: usize,
9820        second_in_middle: bool,
9821    ) -> (Graph, NodeId, Vec<NodeId>) {
9822        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
9823        let mut g = Graph::new();
9824        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9825            let id = g.push(Node {
9826                op,
9827                inputs,
9828                shape: Shape::from_dims(&[4]),
9829                dtype: DType::F32,
9830            });
9831            g.set_placement(id, DeviceLocation::Cpu);
9832            g.set_target_backend(id, BackendId::Cpu);
9833            id
9834        };
9835        let c1 = node(&mut g, Op::Const, vec![]);
9836        // The early value: NOT downstream of any diverge, so it is outside every stretch.
9837        let h = node(&mut g, Op::Relu, vec![c1]);
9838        let mut x = node(&mut g, Op::Const, vec![]);
9839        let mut branches = Vec::new();
9840        for _ in 0..blocks {
9841            let mut d = x;
9842            for _ in 0..fillers {
9843                d = node(&mut g, Op::Silu, vec![d]);
9844            }
9845            let (a, t) = if second_in_middle {
9846                let s1 = node(&mut g, Op::Tanh, vec![d]);
9847                let s2 = node(&mut g, Op::Add, vec![s1, h]);
9848                (s1, s2)
9849            } else {
9850                let s1 = node(&mut g, Op::Add, vec![d, h]);
9851                let s2 = node(&mut g, Op::Tanh, vec![s1]);
9852                (s1, s2)
9853            };
9854            let res = node(&mut g, Op::Add, vec![d, t]);
9855            let branch = crate::region_pathfinder::try_record_branch(
9856                &mut g,
9857                d,
9858                res,
9859                &[a, t],
9860                t,
9861                BackendId::Cuda,
9862                cuda0,
9863                DeviceLocation::Cpu,
9864            )
9865            .expect("well-formed branch")
9866            .expect("two arms");
9867            branches.push(branch);
9868            x = res;
9869        }
9870
9871        crate::optimize::insert_residency_copies(
9872            &mut g,
9873            &[x],
9874            &crate::plan::ExecutionPlan::empty(),
9875            DeviceLocation::Cpu,
9876            None,
9877        );
9878        (g, x, branches)
9879    }
9880
9881    /// LOWERING level, 140 shapes (1 to 3 blocks x 0 to 4 fillers x both entry positions x EVERY
9882    /// combination of arms; the frozen and the streaming order may differ here, as they may on any multi-device
9883    /// graph, but BOTH must be valid): a shared inbound copy must run when ANY branch's chosen arm reads it, and the
9884    /// chosen arm's runs must come before the reconverge. Under the first-slot relocation with per-branch
9885    /// skip sets, 80 of the 140 (a node emitted before its input) were invalid; this is the CPU form of the
9886    /// GPU failures `Copy input NodeId(130) of NodeId(255) not realized` and `cpu kernel wrapper called
9887    /// with non-CPU input` (ROADMAP row 158).
9888    #[test]
9889    fn cross_device_chains_with_a_shared_early_input_lower_to_a_valid_order_for_every_combination_of_arms()
9890     {
9891        let mut shapes = 0;
9892        for blocks in 1..=3usize {
9893            for fillers in 0..=4usize {
9894                for second_in_middle in [false, true] {
9895                    let (g, root, branches) =
9896                        shared_early_input_chain(blocks, fillers, second_in_middle);
9897                    for mask in 0..(1usize << blocks) {
9898                        shapes += 1;
9899                        let route = route_from_mask(&branches, mask);
9900                        let frozen = fuel_graph::lower_picked_route(&g, &[root], &route);
9901                        let streaming =
9902                            fuel_graph::lower_picked_route_streaming(&g, &[root], |b| {
9903                                route.get(&b).copied().unwrap_or(0)
9904                            });
9905                        for (name, order) in [("frozen", &frozen), ("streaming", &streaming)] {
9906                            assert_eq!(
9907                                why_invalid_order(&g, &branches, mask, order),
9908                                None,
9909                                "{name} lowering, blocks={blocks} fillers={fillers} second_in_middle={second_in_middle} mask={mask:#b}: order={order:?}"
9910                            );
9911                        }
9912                    }
9913                }
9914            }
9915        }
9916        assert_eq!(shapes, 140, "the family size changed: re-pin it");
9917    }
9918
9919    /// A chain of cross-device region branches whose stretch reads EXTERNAL values besides its diverge.
9920    /// `ext[i]` is what block `i`'s stretch reads: 0 = the shared early value `h`, 1 = the value two blocks
9921    /// back (a skip connection), 2 = both. `entry` is the stretch node that reads them (0 = the first, 1 =
9922    /// the second); `fillers` nodes sit between the previous block and the diverge. The residency pass
9923    /// inserts one inbound copy per (value, device) and CSEs it between regions, so a copy can sit in
9924    /// several branches' arm 1 at once and its natural position in the base order is set by whichever
9925    /// branch reaches it first. Lowering only: the ops are structural (an `Add` may have three inputs).
9926    #[cfg(test)]
9927    fn pattern_chain(ext: &[u8], entry: usize, fillers: usize) -> (Graph, NodeId, Vec<NodeId>) {
9928        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
9929        let mut g = Graph::new();
9930        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9931            let id = g.push(Node {
9932                op,
9933                inputs,
9934                shape: Shape::from_dims(&[4]),
9935                dtype: DType::F32,
9936            });
9937            g.set_placement(id, DeviceLocation::Cpu);
9938            g.set_target_backend(id, BackendId::Cpu);
9939            id
9940        };
9941        let c1 = node(&mut g, Op::Const, vec![]);
9942        let h = node(&mut g, Op::Relu, vec![c1]);
9943        let mut two_back = node(&mut g, Op::Const, vec![]);
9944        let mut x = node(&mut g, Op::Const, vec![]);
9945        let mut one_back = x;
9946        let mut branches = Vec::new();
9947        for &kind in ext {
9948            let mut d = x;
9949            for _ in 0..fillers {
9950                d = node(&mut g, Op::Silu, vec![d]);
9951            }
9952            let externals: Vec<NodeId> = match kind {
9953                0 => vec![h],
9954                1 => vec![two_back],
9955                _ => vec![h, two_back],
9956            };
9957            let (first, last) = if entry == 0 {
9958                let mut inputs = vec![d];
9959                inputs.extend(externals);
9960                let a = node(&mut g, Op::Add, inputs);
9961                let t = node(&mut g, Op::Tanh, vec![a]);
9962                (a, t)
9963            } else {
9964                let a = node(&mut g, Op::Tanh, vec![d]);
9965                let mut inputs = vec![a];
9966                inputs.extend(externals);
9967                let t = node(&mut g, Op::Add, inputs);
9968                (a, t)
9969            };
9970            let res = node(&mut g, Op::Add, vec![d, last]);
9971            let branch = crate::region_pathfinder::try_record_branch(
9972                &mut g,
9973                d,
9974                res,
9975                &[first, last],
9976                last,
9977                BackendId::Cuda,
9978                cuda0,
9979                DeviceLocation::Cpu,
9980            )
9981            .expect("well-formed branch")
9982            .expect("two arms");
9983            branches.push(branch);
9984            two_back = one_back;
9985            one_back = x;
9986            x = res;
9987        }
9988        crate::optimize::insert_residency_copies(
9989            &mut g,
9990            &[x],
9991            &crate::plan::ExecutionPlan::empty(),
9992            DeviceLocation::Cpu,
9993            None,
9994        );
9995        (g, x, branches)
9996    }
9997
9998    /// LOWERING level, 1548 (shape, arm combination) cases: 1 to 3 chained cross-device branches, every
9999    /// per-block external-input pattern (`h`, a skip connection, both), both entry positions, 0 to 2
10000    /// fillers, EVERY combination of arms; frozen and streaming lowering each valid. With the chosen arm's
10001    /// late runs moved to the FIRST arm slot, 644 checks failed with `Copy (onto Cuda) is emitted before
10002    /// its input`, the CPU form of the GPU failure `Copy input NodeId(130) of NodeId(255) not realized`:
10003    /// the first run opening an arm of the branch was an arm-1 inbound copy shared with another region and
10004    /// positioned early, and the other arm-1 runs were moved there, before the node they read.
10005    #[test]
10006    fn cross_device_chains_with_shared_and_skip_inputs_lower_to_a_valid_order_for_every_combination_of_arms()
10007     {
10008        let mut cases = 0;
10009        for blocks in 1..=3usize {
10010            for code in 0..3usize.pow(blocks as u32) {
10011                let ext: Vec<u8> = (0..blocks)
10012                    .map(|i| ((code / 3usize.pow(i as u32)) % 3) as u8)
10013                    .collect();
10014                for entry in 0..2usize {
10015                    for fillers in 0..=2usize {
10016                        let (g, root, branches) = pattern_chain(&ext, entry, fillers);
10017                        for mask in 0..(1usize << blocks) {
10018                            cases += 1;
10019                            let route = route_from_mask(&branches, mask);
10020                            let frozen = fuel_graph::lower_picked_route(&g, &[root], &route);
10021                            let streaming =
10022                                fuel_graph::lower_picked_route_streaming(&g, &[root], |b| {
10023                                    route.get(&b).copied().unwrap_or(0)
10024                                });
10025                            for (name, order) in [("frozen", &frozen), ("streaming", &streaming)] {
10026                                assert_eq!(
10027                                    why_invalid_order(&g, &branches, mask, order),
10028                                    None,
10029                                    "{name} lowering, ext={ext:?} entry={entry} fillers={fillers} mask={mask:#b}: order={order:?}"
10030                                );
10031                            }
10032                        }
10033                    }
10034                }
10035            }
10036        }
10037        assert_eq!(cases, 1548, "the family size changed: re-pin it");
10038    }
10039
10040    /// EXECUTOR level on CPU: the chain realized for every combination of arms (2 and 3 blocks, every
10041    /// mask, arm 1 = the clone on the same backend) equals arm 0. Before the fix any chain of two or more
10042    /// with an arm 1 failed with "input ... not realized".
10043    #[test]
10044    fn chained_branches_realize_equal_to_arm_zero_for_every_combination_of_arms_on_cpu() {
10045        use crate::optimize::OptimizedGraph;
10046        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
10047            match &arc.read().unwrap().inner {
10048                fuel_memory::BackendStorage::Cpu(c) => c.as_slice::<f32>().expect("f32").to_vec(),
10049                _ => panic!("expected CPU output"),
10050            }
10051        };
10052        drop(global_bindings());
10053        // Hold the generation still between building the stamp and realizing (ROADMAP row 165).
10054        let _gate = crate::dispatch::TOPOLOGY_TEST_GATE
10055            .write()
10056            .unwrap_or_else(|p| p.into_inner());
10057        let run = |blocks: usize, mask: usize| -> Vec<f32> {
10058            let (g, root, branches, ids, table, _head) = head_then_region_chain(blocks);
10059            let mut inputs = StorageCache::new();
10060            inputs.insert(
10061                ids,
10062                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[1_u32, 4, 6]))),
10063            );
10064            let table_vals: Vec<f32> = (0..32).map(|i| (i as f32 - 16.0) / 8.0).collect();
10065            inputs.insert(
10066                table,
10067                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&table_vals))),
10068            );
10069            let opt = OptimizedGraph {
10070                roots: vec![root],
10071                generation: crate::dispatch::topology_generation(),
10072                placements: None,
10073                eviction: None,
10074            };
10075            let route = route_from_mask(&branches, mask);
10076            let (arc, _) = PipelinedExecutor::realize_with_optimized_route(
10077                Arc::new(RwLock::new(g)),
10078                root,
10079                inputs,
10080                &opt,
10081                &route,
10082            )
10083            .unwrap_or_else(|e| panic!("realize (blocks={blocks}, mask={mask:#b}): {e}"));
10084            read(&arc)
10085        };
10086        for blocks in 1..=3usize {
10087            let arm0 = run(blocks, 0);
10088            assert_eq!(arm0.len(), 12);
10089            assert!(arm0.iter().all(|v| v.is_finite()));
10090            for mask in 1..(1usize << blocks) {
10091                assert_eq!(
10092                    run(blocks, mask),
10093                    arm0,
10094                    "blocks={blocks} mask={mask:#b}: a cloned stretch computes what arm 0 computes"
10095                );
10096            }
10097        }
10098    }
10099
10100    /// Realizing a node whose target_backend isn't set surfaces a
10101    /// typed error (no panic).
10102    #[test]
10103    fn pipelined_errors_on_unset_target_backend() {
10104        let graph = Arc::new(RwLock::new(Graph::new()));
10105        let (lhs_id, rhs_id, add_id) = {
10106            let mut g = graph.write().unwrap();
10107            let lhs = g.push(Node {
10108                op: Op::Const,
10109                inputs: vec![],
10110                shape: Shape::from_dims(&[2]),
10111                dtype: DType::F32,
10112            });
10113            let rhs = g.push(Node {
10114                op: Op::Const,
10115                inputs: vec![],
10116                shape: Shape::from_dims(&[2]),
10117                dtype: DType::F32,
10118            });
10119            // Deliberately do NOT call set_target_backend on the Add.
10120            let add = g.push(Node {
10121                op: Op::Add,
10122                inputs: vec![lhs, rhs],
10123                shape: Shape::from_dims(&[2]),
10124                dtype: DType::F32,
10125            });
10126            (lhs, rhs, add)
10127        };
10128
10129        let mut inputs = StorageCache::new();
10130        inputs.insert(
10131            lhs_id,
10132            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]))),
10133        );
10134        inputs.insert(
10135            rhs_id,
10136            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[3.0_f32, 4.0]))),
10137        );
10138
10139        let result = PipelinedExecutor::realize(graph, add_id, inputs);
10140        assert!(result.is_err(), "missing target_backend must error");
10141        let msg = result.unwrap_err().to_string();
10142        assert!(
10143            msg.contains("target_backend"),
10144            "error names the unmet precondition: {msg}"
10145        );
10146    }
10147
10148    /// Realizing a Const-only graph adopts the pre-seeded input
10149    /// without calling any kernel.
10150    #[test]
10151    fn pipelined_realize_const_only() {
10152        let storage = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0, 7.0]);
10153
10154        let graph = Arc::new(RwLock::new(Graph::new()));
10155        let const_id = {
10156            let mut g = graph.write().unwrap();
10157            g.push(Node {
10158                op: Op::Const,
10159                inputs: vec![],
10160                shape: Shape::from_dims(&[3]),
10161                dtype: DType::F32,
10162            })
10163        };
10164
10165        let mut inputs = StorageCache::new();
10166        inputs.insert(const_id, Arc::new(RwLock::new(storage)));
10167
10168        let (result_arc, _) =
10169            PipelinedExecutor::realize(graph, const_id, inputs).expect("realize const");
10170        let guard = result_arc.read().unwrap();
10171        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
10172            let typed: &[f32] = c.as_slice().unwrap();
10173            assert_eq!(typed, &[5.0, 6.0, 7.0]);
10174        }
10175    }
10176
10177    /// Missing input-cache entry for a Const surfaces a typed error.
10178    #[test]
10179    fn pipelined_errors_on_missing_const_input() {
10180        let graph = Arc::new(RwLock::new(Graph::new()));
10181        let const_id = {
10182            let mut g = graph.write().unwrap();
10183            g.push(Node {
10184                op: Op::Const,
10185                inputs: vec![],
10186                shape: Shape::from_dims(&[2]),
10187                dtype: DType::F32,
10188            })
10189        };
10190        // Deliberately empty input cache.
10191        let inputs = StorageCache::new();
10192        let result = PipelinedExecutor::realize(graph, const_id, inputs);
10193        assert!(result.is_err());
10194    }
10195
10196    /// E2E: 2-node graph (Const + Relu) — exercises the unary
10197    /// dispatch wrapper + kernel through the pipelined executor.
10198    #[test]
10199    fn pipelined_realize_const_relu() {
10200        let storage = fuel_memory::from_slice_cpu(&[-1.0_f32, 0.0, 0.5, -3.5, 7.25]);
10201        let graph = Arc::new(RwLock::new(Graph::new()));
10202        let (in_id, relu_id) = {
10203            let mut g = graph.write().unwrap();
10204            let in_id = g.push(Node {
10205                op: Op::Const,
10206                inputs: vec![],
10207                shape: Shape::from_dims(&[5]),
10208                dtype: DType::F32,
10209            });
10210            let relu_id = g.push(Node {
10211                op: Op::Relu,
10212                inputs: vec![in_id],
10213                shape: Shape::from_dims(&[5]),
10214                dtype: DType::F32,
10215            });
10216            g.set_target_backend(relu_id, BackendId::Cpu);
10217            (in_id, relu_id)
10218        };
10219        let mut inputs = StorageCache::new();
10220        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10221
10222        let (result_arc, _) = PipelinedExecutor::realize(graph, relu_id, inputs).expect("realize");
10223        let guard = result_arc.read().unwrap();
10224        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
10225            let typed: &[f32] = c.as_slice().expect("f32 cast");
10226            assert_eq!(typed, &[0.0, 0.0, 0.5, 0.0, 7.25]);
10227        }
10228    }
10229
10230    /// E2E: Const + Const + Sub + Mul + Div — exercises three more
10231    /// of the freshly-migrated binary kernels in one graph. Verifies
10232    /// that intermediates flow through the cache as expected.
10233    #[test]
10234    fn pipelined_realize_chained_binary_ops() {
10235        let a_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
10236        let b_storage = fuel_memory::from_slice_cpu(&[3.0_f32, 5.0]);
10237        let c_storage = fuel_memory::from_slice_cpu(&[2.0_f32, 4.0]);
10238
10239        let graph = Arc::new(RwLock::new(Graph::new()));
10240        let (a_id, b_id, c_id, sub_id, mul_id, div_id) = {
10241            let mut g = graph.write().unwrap();
10242            let a = g.push(Node {
10243                op: Op::Const,
10244                inputs: vec![],
10245                shape: Shape::from_dims(&[2]),
10246                dtype: DType::F32,
10247            });
10248            let b = g.push(Node {
10249                op: Op::Const,
10250                inputs: vec![],
10251                shape: Shape::from_dims(&[2]),
10252                dtype: DType::F32,
10253            });
10254            let c = g.push(Node {
10255                op: Op::Const,
10256                inputs: vec![],
10257                shape: Shape::from_dims(&[2]),
10258                dtype: DType::F32,
10259            });
10260            // (a - b)         = [7, 15]
10261            let sub = g.push(Node {
10262                op: Op::Sub,
10263                inputs: vec![a, b],
10264                shape: Shape::from_dims(&[2]),
10265                dtype: DType::F32,
10266            });
10267            // (a - b) * c     = [14, 60]
10268            let mul = g.push(Node {
10269                op: Op::Mul,
10270                inputs: vec![sub, c],
10271                shape: Shape::from_dims(&[2]),
10272                dtype: DType::F32,
10273            });
10274            // ((a-b)*c) / b   = [14/3, 12]
10275            let div = g.push(Node {
10276                op: Op::Div,
10277                inputs: vec![mul, b],
10278                shape: Shape::from_dims(&[2]),
10279                dtype: DType::F32,
10280            });
10281            g.set_target_backend(sub, BackendId::Cpu);
10282            g.set_target_backend(mul, BackendId::Cpu);
10283            g.set_target_backend(div, BackendId::Cpu);
10284            (a, b, c, sub, mul, div)
10285        };
10286
10287        let _ = (sub_id, mul_id);
10288        let mut inputs = StorageCache::new();
10289        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
10290        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
10291        inputs.insert(c_id, Arc::new(RwLock::new(c_storage)));
10292
10293        let (result_arc, _) = PipelinedExecutor::realize(graph, div_id, inputs).expect("realize");
10294        let guard = result_arc.read().unwrap();
10295        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
10296            let typed: &[f32] = c.as_slice().unwrap();
10297            assert!((typed[0] - (14.0_f32 / 3.0)).abs() < 1e-6);
10298            assert!((typed[1] - 12.0).abs() < 1e-6);
10299        }
10300    }
10301
10302    /// E2E: Const + Transpose — verifies metadata-only view ops
10303    /// share the input's Storage Arc and produce a strided Layout.
10304    /// Stage 3 of Layout-on-Node.
10305    #[test]
10306    fn pipelined_realize_transpose_is_metadata_only() {
10307        // shape [2, 3]; transpose → shape [3, 2], strided
10308        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
10309        let graph = Arc::new(RwLock::new(Graph::new()));
10310        let (in_id, t_id) = {
10311            let mut g = graph.write().unwrap();
10312            let in_id = g.push(Node {
10313                op: Op::Const,
10314                inputs: vec![],
10315                shape: Shape::from_dims(&[2, 3]),
10316                dtype: DType::F32,
10317            });
10318            let t_id = g.push(Node {
10319                op: Op::Transpose,
10320                inputs: vec![in_id],
10321                shape: Shape::from_dims(&[3, 2]),
10322                dtype: DType::F32,
10323            });
10324            // Note: NO set_target_backend — transpose is metadata-only
10325            // and doesn't run on a backend.
10326            (in_id, t_id)
10327        };
10328        let mut inputs = StorageCache::new();
10329        let in_arc = Arc::new(RwLock::new(storage));
10330        inputs.insert(in_id, Arc::clone(&in_arc));
10331
10332        let (result_arc, result_layout) =
10333            PipelinedExecutor::realize(graph, t_id, inputs).expect("realize");
10334
10335        // The output Storage Arc is the SAME Arc as the input —
10336        // metadata-only adoption shares bytes.
10337        assert!(
10338            Arc::ptr_eq(&result_arc, &in_arc),
10339            "transpose must share input bytes"
10340        );
10341
10342        // The output Layout is the transposed view.
10343        assert_eq!(result_layout.shape().dims(), &[3, 2]);
10344        assert_eq!(result_layout.stride(), &[1, 3]);
10345        assert!(!result_layout.is_contiguous());
10346    }
10347
10348    /// E2E: Const + Flip(dim=0) — verifies Op::Flip is metadata-only.
10349    /// The output Storage Arc must be the SAME Arc (no copy);
10350    /// the output Layout has a negated stride at dim 0 and a
10351    /// shifted start_offset.
10352    #[test]
10353    fn pipelined_realize_flip_is_metadata_only() {
10354        // shape [3, 4]; flip dim 0 → shape [3, 4], stride [-4, 1], offset 8.
10355        let data: Vec<f32> = (1..=12).map(|x| x as f32).collect();
10356        let storage = fuel_memory::from_slice_cpu(&data);
10357        let graph = Arc::new(RwLock::new(Graph::new()));
10358        let (in_id, f_id) = {
10359            let mut g = graph.write().unwrap();
10360            let in_id = g.push(Node {
10361                op: Op::Const,
10362                inputs: vec![],
10363                shape: Shape::from_dims(&[3, 4]),
10364                dtype: DType::F32,
10365            });
10366            let f_id = g.push(Node {
10367                op: Op::Flip { dim: 0 },
10368                inputs: vec![in_id],
10369                shape: Shape::from_dims(&[3, 4]),
10370                dtype: DType::F32,
10371            });
10372            (in_id, f_id)
10373        };
10374        let mut inputs = StorageCache::new();
10375        let in_arc = Arc::new(RwLock::new(storage));
10376        inputs.insert(in_id, Arc::clone(&in_arc));
10377
10378        let (result_arc, result_layout) =
10379            PipelinedExecutor::realize(graph, f_id, inputs).expect("realize");
10380
10381        assert!(
10382            Arc::ptr_eq(&result_arc, &in_arc),
10383            "flip must share input bytes"
10384        );
10385        assert_eq!(result_layout.shape().dims(), &[3, 4]);
10386        assert_eq!(result_layout.stride(), &[-4_isize, 1]);
10387        assert_eq!(result_layout.start_offset(), 8);
10388        assert!(!result_layout.is_contiguous());
10389    }
10390
10391    /// E2E: Const + Permute(rank-3 axes [2, 0, 1]) — verifies the
10392    /// general permute path through metadata-only adoption.
10393    #[test]
10394    fn pipelined_realize_permute_is_metadata_only() {
10395        // shape [2, 3, 4]; permute axes [2, 0, 1] → shape [4, 2, 3]
10396        let data: Vec<f32> = (1..=24).map(|x| x as f32).collect();
10397        let storage = fuel_memory::from_slice_cpu(&data);
10398        let graph = Arc::new(RwLock::new(Graph::new()));
10399        let (in_id, p_id) = {
10400            let mut g = graph.write().unwrap();
10401            let in_id = g.push(Node {
10402                op: Op::Const,
10403                inputs: vec![],
10404                shape: Shape::from_dims(&[2, 3, 4]),
10405                dtype: DType::F32,
10406            });
10407            let p_id = g.push(Node {
10408                op: Op::Permute(vec![2, 0, 1]),
10409                inputs: vec![in_id],
10410                shape: Shape::from_dims(&[4, 2, 3]),
10411                dtype: DType::F32,
10412            });
10413            (in_id, p_id)
10414        };
10415        let mut inputs = StorageCache::new();
10416        let in_arc = Arc::new(RwLock::new(storage));
10417        inputs.insert(in_id, Arc::clone(&in_arc));
10418
10419        let (result_arc, result_layout) =
10420            PipelinedExecutor::realize(graph, p_id, inputs).expect("realize");
10421
10422        assert!(Arc::ptr_eq(&result_arc, &in_arc));
10423        assert_eq!(result_layout.shape().dims(), &[4, 2, 3]);
10424        // Original strides for shape [2, 3, 4] are [12, 4, 1].
10425        // After permute axes [2, 0, 1]: [strides[2], strides[0], strides[1]] = [1, 12, 4].
10426        assert_eq!(result_layout.stride(), &[1, 12, 4]);
10427    }
10428
10429    /// E2E: Const + Cast(f32→f64) — verifies cast through the
10430    /// pipelined executor. Output Storage has the target dtype;
10431    /// bytes encode the widened values.
10432    #[test]
10433    fn pipelined_realize_cast_f32_to_f64() {
10434        let storage = fuel_memory::from_slice_cpu(&[1.5_f32, -2.25, 100.0]);
10435        let graph = Arc::new(RwLock::new(Graph::new()));
10436        let (in_id, c_id) = {
10437            let mut g = graph.write().unwrap();
10438            let in_id = g.push(Node {
10439                op: Op::Const,
10440                inputs: vec![],
10441                shape: Shape::from_dims(&[3]),
10442                dtype: DType::F32,
10443            });
10444            let c_id = g.push(Node {
10445                op: Op::Cast(DType::F64),
10446                inputs: vec![in_id],
10447                shape: Shape::from_dims(&[3]),
10448                dtype: DType::F64,
10449            });
10450            g.set_target_backend(c_id, BackendId::Cpu);
10451            (in_id, c_id)
10452        };
10453        let mut inputs = StorageCache::new();
10454        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10455
10456        let (result_arc, result_layout) =
10457            PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
10458        assert_eq!(result_layout.shape().dims(), &[3]);
10459
10460        let guard = result_arc.read().unwrap();
10461        assert_eq!(guard.dtype, DType::F64);
10462        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10463            panic!("expected Cpu storage");
10464        };
10465        assert_eq!(c.as_slice::<f64>().unwrap(), &[1.5_f64, -2.25, 100.0]);
10466    }
10467
10468    /// E2E: Const + Cast(f32→bf16) + Cast(bf16→f32) — round trip
10469    /// through bf16; verifies the Cast wrapper's source-dtype
10470    /// dispatch (different sources hit different match arms).
10471    /// Inputs chosen to round-trip exactly through bf16.
10472    #[test]
10473    fn pipelined_realize_cast_round_trip_via_bf16() {
10474        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, -3.0, 0.5]);
10475        let graph = Arc::new(RwLock::new(Graph::new()));
10476        let (in_id, c1_id, c2_id) = {
10477            let mut g = graph.write().unwrap();
10478            let in_id = g.push(Node {
10479                op: Op::Const,
10480                inputs: vec![],
10481                shape: Shape::from_dims(&[4]),
10482                dtype: DType::F32,
10483            });
10484            let c1_id = g.push(Node {
10485                op: Op::Cast(DType::BF16),
10486                inputs: vec![in_id],
10487                shape: Shape::from_dims(&[4]),
10488                dtype: DType::BF16,
10489            });
10490            let c2_id = g.push(Node {
10491                op: Op::Cast(DType::F32),
10492                inputs: vec![c1_id],
10493                shape: Shape::from_dims(&[4]),
10494                dtype: DType::F32,
10495            });
10496            g.set_target_backend(c1_id, BackendId::Cpu);
10497            g.set_target_backend(c2_id, BackendId::Cpu);
10498            (in_id, c1_id, c2_id)
10499        };
10500        let _ = c1_id;
10501        let mut inputs = StorageCache::new();
10502        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10503
10504        let (result_arc, _) = PipelinedExecutor::realize(graph, c2_id, inputs).expect("realize");
10505        let guard = result_arc.read().unwrap();
10506        assert_eq!(guard.dtype, DType::F32);
10507        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10508            panic!("expected Cpu storage");
10509        };
10510        assert_eq!(c.as_slice::<f32>().unwrap(), &[1.0_f32, 2.0, -3.0, 0.5]);
10511    }
10512
10513    /// E2E: Const + Slice — slice is metadata-only; the output Arc
10514    /// shares bytes with the input, and the Layout's start_offset
10515    /// + narrowed shape reflect the slice. Stage 3 of Layout-on-Node
10516    ///
10517    /// extended to cover Op::Slice via Layout::narrow.
10518    #[test]
10519    fn pipelined_realize_slice_is_metadata_only() {
10520        // shape [5]; slice dim 0 from index 1 with len 3 → shape [3]
10521        // Source: [10, 20, 30, 40, 50]; slice → [20, 30, 40]
10522        let storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0]);
10523        let graph = Arc::new(RwLock::new(Graph::new()));
10524        let (in_id, s_id) = {
10525            let mut g = graph.write().unwrap();
10526            let in_id = g.push(Node {
10527                op: Op::Const,
10528                inputs: vec![],
10529                shape: Shape::from_dims(&[5]),
10530                dtype: DType::F32,
10531            });
10532            let s_id = g.push(Node {
10533                op: Op::Slice {
10534                    dim: 0,
10535                    start: 1,
10536                    len: 3,
10537                },
10538                inputs: vec![in_id],
10539                shape: Shape::from_dims(&[3]),
10540                dtype: DType::F32,
10541            });
10542            (in_id, s_id)
10543        };
10544        let mut inputs = StorageCache::new();
10545        let in_arc = Arc::new(RwLock::new(storage));
10546        inputs.insert(in_id, Arc::clone(&in_arc));
10547
10548        let (result_arc, result_layout) =
10549            PipelinedExecutor::realize(graph, s_id, inputs).expect("realize");
10550
10551        // Bytes shared with the input.
10552        assert!(Arc::ptr_eq(&result_arc, &in_arc));
10553        assert_eq!(result_layout.shape().dims(), &[3]);
10554        // Slice into a contiguous source: the resulting layout has
10555        // start_offset = original_stride[0] * start = 1 * 1 = 1,
10556        // and stride [1] (still contiguous within the narrowed dim).
10557        assert_eq!(result_layout.start_offset(), 1);
10558        assert_eq!(result_layout.stride(), &[1]);
10559    }
10560
10561    /// E2E: Const + Slice + SumAll — slice is metadata-only, but
10562    /// sum needs contiguous bytes, so auto-Contiguize materializes
10563    /// the slice before reduce. Tests the stage 3+4 integration
10564    /// through Op::Slice. Sum of `[20, 30, 40]` is 90.
10565    #[test]
10566    fn pipelined_realize_slice_then_sum_all() {
10567        let storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0]);
10568        let graph = Arc::new(RwLock::new(Graph::new()));
10569        let (in_id, s_id, sum_id) = {
10570            let mut g = graph.write().unwrap();
10571            let in_id = g.push(Node {
10572                op: Op::Const,
10573                inputs: vec![],
10574                shape: Shape::from_dims(&[5]),
10575                dtype: DType::F32,
10576            });
10577            let s_id = g.push(Node {
10578                op: Op::Slice {
10579                    dim: 0,
10580                    start: 1,
10581                    len: 3,
10582                },
10583                inputs: vec![in_id],
10584                shape: Shape::from_dims(&[3]),
10585                dtype: DType::F32,
10586            });
10587            let sum_id = g.push(Node {
10588                op: Op::SumAll,
10589                inputs: vec![s_id],
10590                shape: Shape::from_dims(&[]),
10591                dtype: DType::F32,
10592            });
10593            g.set_target_backend(sum_id, BackendId::Cpu);
10594            (in_id, s_id, sum_id)
10595        };
10596        let _ = s_id;
10597        let mut inputs = StorageCache::new();
10598        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10599
10600        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
10601        let guard = result_arc.read().unwrap();
10602        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10603            panic!("expected Cpu storage");
10604        };
10605        assert_eq!(c.as_slice::<f32>().unwrap(), &[90.0]);
10606    }
10607
10608    /// E2E: Const + Flip + ReluElementwise — Flip is metadata-only,
10609    /// then a kernel that doesn't yet handle negative strides forces
10610    /// auto-Contiguize to materialize through StridedIndex (which
10611    /// handles signed strides natively). Verifies the post-flip
10612    /// data ordering ([4, 3, 2, 1]) is correctly seen by the kernel.
10613    #[test]
10614    fn pipelined_realize_flip_then_relu_materializes_in_reverse() {
10615        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
10616        let graph = Arc::new(RwLock::new(Graph::new()));
10617        let (in_id, _f_id, r_id) = {
10618            let mut g = graph.write().unwrap();
10619            let in_id = g.push(Node {
10620                op: Op::Const,
10621                inputs: vec![],
10622                shape: Shape::from_dims(&[4]),
10623                dtype: DType::F32,
10624            });
10625            let f_id = g.push(Node {
10626                op: Op::Flip { dim: 0 },
10627                inputs: vec![in_id],
10628                shape: Shape::from_dims(&[4]),
10629                dtype: DType::F32,
10630            });
10631            let r_id = g.push(Node {
10632                op: Op::Relu,
10633                inputs: vec![f_id],
10634                shape: Shape::from_dims(&[4]),
10635                dtype: DType::F32,
10636            });
10637            g.set_target_backend(r_id, BackendId::Cpu);
10638            (in_id, f_id, r_id)
10639        };
10640        let mut inputs = StorageCache::new();
10641        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10642
10643        let (result_arc, result_layout) =
10644            PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
10645        let guard = result_arc.read().unwrap();
10646        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10647            panic!("expected Cpu storage");
10648        };
10649        assert_eq!(c.as_slice::<f32>().unwrap(), &[4.0, 3.0, 2.0, 1.0]);
10650        assert_eq!(result_layout.shape().dims(), &[4]);
10651        assert!(result_layout.is_contiguous(), "relu output is contiguous");
10652    }
10653
10654    /// E2E: Const + BroadcastTo — verifies that broadcast layouts
10655    /// have stride 0 on the broadcast dim while sharing the input's
10656    /// bytes. Stage 3 of Layout-on-Node.
10657    #[test]
10658    fn pipelined_realize_broadcast_is_metadata_only() {
10659        // shape [3]; broadcast to [4, 3] — leading dim is 0-stride
10660        let storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
10661        let graph = Arc::new(RwLock::new(Graph::new()));
10662        let (in_id, b_id) = {
10663            let mut g = graph.write().unwrap();
10664            let in_id = g.push(Node {
10665                op: Op::Const,
10666                inputs: vec![],
10667                shape: Shape::from_dims(&[3]),
10668                dtype: DType::F32,
10669            });
10670            let b_id = g.push(Node {
10671                op: Op::BroadcastTo(Shape::from_dims(&[4, 3])),
10672                inputs: vec![in_id],
10673                shape: Shape::from_dims(&[4, 3]),
10674                dtype: DType::F32,
10675            });
10676            (in_id, b_id)
10677        };
10678        let mut inputs = StorageCache::new();
10679        let in_arc = Arc::new(RwLock::new(storage));
10680        inputs.insert(in_id, Arc::clone(&in_arc));
10681
10682        let (result_arc, result_layout) =
10683            PipelinedExecutor::realize(graph, b_id, inputs).expect("realize");
10684
10685        assert!(Arc::ptr_eq(&result_arc, &in_arc));
10686        assert_eq!(result_layout.shape().dims(), &[4, 3]);
10687        // Broadcasted leading dim has stride 0.
10688        assert_eq!(result_layout.stride(), &[0, 1]);
10689    }
10690
10691    /// E2E: Const + Const + MatMul — exercises rank-2 matmul
10692    /// through the pipelined executor. Inputs are contiguous (no
10693    /// auto-Contiguize needed); the kernel walks them via the
10694    /// (m, n, k) carried in OpParams::Matmul.
10695    #[test]
10696    fn pipelined_realize_matmul_2x3_times_3x2() {
10697        // [[1, 2, 3], [4, 5, 6]] @ [[7, 8], [9, 10], [11, 12]]
10698        //   = [[58, 64], [139, 154]]
10699        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
10700        let rhs_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0, 9.0, 10.0, 11.0, 12.0]);
10701
10702        let graph = Arc::new(RwLock::new(Graph::new()));
10703        let (lhs_id, rhs_id, mm_id) = {
10704            let mut g = graph.write().unwrap();
10705            let lhs = g.push(Node {
10706                op: Op::Const,
10707                inputs: vec![],
10708                shape: Shape::from_dims(&[2, 3]),
10709                dtype: DType::F32,
10710            });
10711            let rhs = g.push(Node {
10712                op: Op::Const,
10713                inputs: vec![],
10714                shape: Shape::from_dims(&[3, 2]),
10715                dtype: DType::F32,
10716            });
10717            let mm = g.push(Node {
10718                op: Op::MatMul,
10719                inputs: vec![lhs, rhs],
10720                shape: Shape::from_dims(&[2, 2]),
10721                dtype: DType::F32,
10722            });
10723            g.set_target_backend(mm, BackendId::Cpu);
10724            (lhs, rhs, mm)
10725        };
10726        let mut inputs = StorageCache::new();
10727        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
10728        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
10729
10730        let (result_arc, result_layout) =
10731            PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
10732        assert_eq!(result_layout.shape().dims(), &[2, 2]);
10733        assert!(result_layout.is_contiguous());
10734
10735        let guard = result_arc.read().unwrap();
10736        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10737            panic!("expected Cpu storage");
10738        };
10739        assert_eq!(c.as_slice::<f32>().unwrap(), &[58.0, 64.0, 139.0, 154.0]);
10740    }
10741
10742    /// E2E: batched matmul through the pipelined executor. Two
10743    /// batches of [2, 2] @ [2, 2]; the kernel iterates over
10744    /// `batch_count` and produces concatenated outputs.
10745    #[test]
10746    fn pipelined_realize_matmul_batched_2x_2x2_times_2x2() {
10747        let lhs_storage = fuel_memory::from_slice_cpu(&[
10748            1.0_f32, 2.0, 3.0, 4.0, // batch 0
10749            1.0, 0.0, 0.0, 1.0, // batch 1 (identity)
10750        ]);
10751        let rhs_storage = fuel_memory::from_slice_cpu(&[
10752            5.0_f32, 6.0, 7.0, 8.0, // batch 0
10753            10.0, 20.0, 30.0, 40.0, // batch 1
10754        ]);
10755
10756        let graph = Arc::new(RwLock::new(Graph::new()));
10757        let (lhs_id, rhs_id, mm_id) = {
10758            let mut g = graph.write().unwrap();
10759            let lhs = g.push(Node {
10760                op: Op::Const,
10761                inputs: vec![],
10762                shape: Shape::from_dims(&[2, 2, 2]),
10763                dtype: DType::F32,
10764            });
10765            let rhs = g.push(Node {
10766                op: Op::Const,
10767                inputs: vec![],
10768                shape: Shape::from_dims(&[2, 2, 2]),
10769                dtype: DType::F32,
10770            });
10771            let mm = g.push(Node {
10772                op: Op::MatMul,
10773                inputs: vec![lhs, rhs],
10774                shape: Shape::from_dims(&[2, 2, 2]),
10775                dtype: DType::F32,
10776            });
10777            g.set_target_backend(mm, BackendId::Cpu);
10778            (lhs, rhs, mm)
10779        };
10780        let mut inputs = StorageCache::new();
10781        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
10782        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
10783
10784        let (result_arc, result_layout) =
10785            PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
10786        assert_eq!(result_layout.shape().dims(), &[2, 2, 2]);
10787        assert!(result_layout.is_contiguous());
10788
10789        let guard = result_arc.read().unwrap();
10790        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10791            panic!("expected Cpu storage");
10792        };
10793        // batch 0: [[1,2],[3,4]] @ [[5,6],[7,8]] = [[19,22],[43,50]]
10794        // batch 1: identity @ [[10,20],[30,40]]   = [[10,20],[30,40]]
10795        assert_eq!(
10796            c.as_slice::<f32>().unwrap(),
10797            &[19.0, 22.0, 43.0, 50.0, 10.0, 20.0, 30.0, 40.0]
10798        );
10799    }
10800
10801    /// E2E: F64 elementwise add through the pipelined executor.
10802    /// Verifies that capability-driven dispatch correctly routes
10803    /// (AddElementwise, F64) to the f64 wrapper/kernel.
10804    #[test]
10805    fn pipelined_realize_add_f64() {
10806        let lhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0]);
10807        let rhs = fuel_memory::from_slice_cpu(&[10.0_f64, 20.0, 30.0]);
10808        let graph = Arc::new(RwLock::new(Graph::new()));
10809        let (l_id, r_id, op_id) = {
10810            let mut g = graph.write().unwrap();
10811            let l = g.push(Node {
10812                op: Op::Const,
10813                inputs: vec![],
10814                shape: Shape::from_dims(&[3]),
10815                dtype: DType::F64,
10816            });
10817            let r = g.push(Node {
10818                op: Op::Const,
10819                inputs: vec![],
10820                shape: Shape::from_dims(&[3]),
10821                dtype: DType::F64,
10822            });
10823            let op = g.push(Node {
10824                op: Op::Add,
10825                inputs: vec![l, r],
10826                shape: Shape::from_dims(&[3]),
10827                dtype: DType::F64,
10828            });
10829            g.set_target_backend(op, BackendId::Cpu);
10830            (l, r, op)
10831        };
10832        let mut inputs = StorageCache::new();
10833        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10834        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10835        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
10836        let guard = result_arc.read().unwrap();
10837        assert_eq!(guard.dtype, DType::F64);
10838        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10839            panic!("expected Cpu storage");
10840        };
10841        assert_eq!(c.as_slice::<f64>().unwrap(), &[11.0_f64, 22.0, 33.0]);
10842    }
10843
10844    /// E2E: Op::Equal F32 → Bool mask through the pipelined executor (GAP-168c).
10845    /// Verifies (a) the binding-table key `(EqualElementwise, [F32, F32, U8],
10846    /// Cpu)` resolves, (b) the executor allocates a U8-sized output
10847    /// buffer (1 byte per element, not 4), (c) the kernel writes the
10848    /// expected mask bits including IEEE-754 NaN handling
10849    /// (`NaN == NaN` is false).
10850    #[test]
10851    fn pipelined_realize_eq_f32_to_bool_mask() {
10852        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, f32::NAN, 0.0]);
10853        let rhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -0.0]);
10854        let graph = Arc::new(RwLock::new(Graph::new()));
10855        let (l_id, r_id, eq_id) = {
10856            let mut g = graph.write().unwrap();
10857            let l = g.push(Node {
10858                op: Op::Const,
10859                inputs: vec![],
10860                shape: Shape::from_dims(&[5]),
10861                dtype: DType::F32,
10862            });
10863            let r = g.push(Node {
10864                op: Op::Const,
10865                inputs: vec![],
10866                shape: Shape::from_dims(&[5]),
10867                dtype: DType::F32,
10868            });
10869            let eq = g.push(Node {
10870                op: Op::Equal,
10871                inputs: vec![l, r],
10872                shape: Shape::from_dims(&[5]),
10873                dtype: DType::Bool,
10874            });
10875            g.set_target_backend(eq, BackendId::Cpu);
10876            (l, r, eq)
10877        };
10878        let mut inputs = StorageCache::new();
10879        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10880        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10881        let (result_arc, _) = PipelinedExecutor::realize(graph, eq_id, inputs).expect("realize");
10882        let guard = result_arc.read().unwrap();
10883        assert_eq!(guard.dtype, DType::Bool);
10884        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10885            panic!("expected Cpu storage");
10886        };
10887        let mask: &[u8] = c.as_slice().expect("u8 view");
10888        // Index 0: 1.0 == 1.0 → 1.
10889        // Index 1: 2.0 != 5.0 → 0.
10890        // Index 2: 3.0 == 3.0 → 1.
10891        // Index 3: NaN == NaN → 0 (IEEE-754).
10892        // Index 4: 0.0 == -0.0 → 1 (IEEE-754 zero equality).
10893        assert_eq!(mask, &[1, 0, 1, 0, 1]);
10894    }
10895
10896    /// E2E: Op::Ne F32 → Bool mask. Mirrors the Eq F32 test with
10897    /// inverted predicate; NaN-vs-NaN slot now yields `1` (since
10898    /// `NaN != NaN` per IEEE-754).
10899    #[test]
10900    fn pipelined_realize_ne_f32_to_bool_mask() {
10901        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, f32::NAN, 0.0]);
10902        let rhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -0.0]);
10903        let graph = Arc::new(RwLock::new(Graph::new()));
10904        let (l_id, r_id, ne_id) = {
10905            let mut g = graph.write().unwrap();
10906            let l = g.push(Node {
10907                op: Op::Const,
10908                inputs: vec![],
10909                shape: Shape::from_dims(&[5]),
10910                dtype: DType::F32,
10911            });
10912            let r = g.push(Node {
10913                op: Op::Const,
10914                inputs: vec![],
10915                shape: Shape::from_dims(&[5]),
10916                dtype: DType::F32,
10917            });
10918            let ne = g.push(Node {
10919                op: Op::Ne,
10920                inputs: vec![l, r],
10921                shape: Shape::from_dims(&[5]),
10922                dtype: DType::Bool,
10923            });
10924            g.set_target_backend(ne, BackendId::Cpu);
10925            (l, r, ne)
10926        };
10927        let mut inputs = StorageCache::new();
10928        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10929        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10930        let (result_arc, _) = PipelinedExecutor::realize(graph, ne_id, inputs).expect("realize");
10931        let guard = result_arc.read().unwrap();
10932        assert_eq!(guard.dtype, DType::Bool);
10933        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10934            panic!("expected Cpu storage");
10935        };
10936        let mask: &[u8] = c.as_slice().expect("u8 view");
10937        // Inverse of the Eq test:
10938        // 1.0 != 1.0 → 0;  2.0 != 5.0 → 1;  3.0 != 3.0 → 0;
10939        // NaN != NaN → 1 (IEEE-754);  0.0 != -0.0 → 0 (IEEE-754).
10940        assert_eq!(mask, &[0, 1, 0, 1, 0]);
10941    }
10942
10943    /// E2E: Op::Lt F32 → Bool mask. Confirms strict-less-than semantics
10944    /// + IEEE-754 NaN handling (any comparison with NaN is unordered →
10945    ///
10946    /// `0`).
10947    #[test]
10948    fn pipelined_realize_lt_f32_to_bool_mask() {
10949        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -1.0]);
10950        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 3.0, 0.0, 0.0]);
10951        let graph = Arc::new(RwLock::new(Graph::new()));
10952        let (l_id, r_id, lt_id) = {
10953            let mut g = graph.write().unwrap();
10954            let l = g.push(Node {
10955                op: Op::Const,
10956                inputs: vec![],
10957                shape: Shape::from_dims(&[5]),
10958                dtype: DType::F32,
10959            });
10960            let r = g.push(Node {
10961                op: Op::Const,
10962                inputs: vec![],
10963                shape: Shape::from_dims(&[5]),
10964                dtype: DType::F32,
10965            });
10966            let lt = g.push(Node {
10967                op: Op::Lt,
10968                inputs: vec![l, r],
10969                shape: Shape::from_dims(&[5]),
10970                dtype: DType::Bool,
10971            });
10972            g.set_target_backend(lt, BackendId::Cpu);
10973            (l, r, lt)
10974        };
10975        let mut inputs = StorageCache::new();
10976        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10977        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10978        let (result_arc, _) = PipelinedExecutor::realize(graph, lt_id, inputs).expect("realize");
10979        let guard = result_arc.read().unwrap();
10980        assert_eq!(guard.dtype, DType::Bool);
10981        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10982            panic!("expected Cpu storage");
10983        };
10984        let mask: &[u8] = c.as_slice().expect("u8 view");
10985        // 1.0 < 2.0 → 1;  5.0 < 5.0 → 0 (strict);  3.0 < 3.0 → 0;
10986        // NaN < 0.0 → 0 (unordered);  -1.0 < 0.0 → 1.
10987        assert_eq!(mask, &[1, 0, 0, 0, 1]);
10988    }
10989
10990    /// E2E: Op::Le F32 → Bool mask. Distinct from Lt at the equal slot
10991    /// (`5.0 <= 5.0` = 1, vs Lt's `5.0 < 5.0` = 0). NaN unordered → 0.
10992    #[test]
10993    fn pipelined_realize_le_f32_to_bool_mask() {
10994        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -1.0]);
10995        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 2.0, 0.0, 0.0]);
10996        let graph = Arc::new(RwLock::new(Graph::new()));
10997        let (l_id, r_id, le_id) = {
10998            let mut g = graph.write().unwrap();
10999            let l = g.push(Node {
11000                op: Op::Const,
11001                inputs: vec![],
11002                shape: Shape::from_dims(&[5]),
11003                dtype: DType::F32,
11004            });
11005            let r = g.push(Node {
11006                op: Op::Const,
11007                inputs: vec![],
11008                shape: Shape::from_dims(&[5]),
11009                dtype: DType::F32,
11010            });
11011            let le = g.push(Node {
11012                op: Op::Le,
11013                inputs: vec![l, r],
11014                shape: Shape::from_dims(&[5]),
11015                dtype: DType::Bool,
11016            });
11017            g.set_target_backend(le, BackendId::Cpu);
11018            (l, r, le)
11019        };
11020        let mut inputs = StorageCache::new();
11021        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11022        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11023        let (result_arc, _) = PipelinedExecutor::realize(graph, le_id, inputs).expect("realize");
11024        let guard = result_arc.read().unwrap();
11025        assert_eq!(guard.dtype, DType::Bool);
11026        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11027            panic!("expected Cpu storage");
11028        };
11029        let mask: &[u8] = c.as_slice().expect("u8 view");
11030        // 1.0 <= 2.0 → 1;  5.0 <= 5.0 → 1 (key Lt difference);
11031        // 3.0 <= 2.0 → 0;  NaN <= 0.0 → 0 (unordered);  -1.0 <= 0.0 → 1.
11032        assert_eq!(mask, &[1, 1, 0, 0, 1]);
11033    }
11034
11035    /// E2E: Op::Gt F32 → Bool mask. Strict-greater: equality slot is
11036    /// `0`. NaN unordered → `0`.
11037    #[test]
11038    fn pipelined_realize_gt_f32_to_bool_mask() {
11039        let lhs = fuel_memory::from_slice_cpu(&[3.0_f32, 5.0, 2.0, f32::NAN, 1.0]);
11040        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 3.0, 0.0, 0.0]);
11041        let graph = Arc::new(RwLock::new(Graph::new()));
11042        let (l_id, r_id, gt_id) = {
11043            let mut g = graph.write().unwrap();
11044            let l = g.push(Node {
11045                op: Op::Const,
11046                inputs: vec![],
11047                shape: Shape::from_dims(&[5]),
11048                dtype: DType::F32,
11049            });
11050            let r = g.push(Node {
11051                op: Op::Const,
11052                inputs: vec![],
11053                shape: Shape::from_dims(&[5]),
11054                dtype: DType::F32,
11055            });
11056            let gt = g.push(Node {
11057                op: Op::Gt,
11058                inputs: vec![l, r],
11059                shape: Shape::from_dims(&[5]),
11060                dtype: DType::Bool,
11061            });
11062            g.set_target_backend(gt, BackendId::Cpu);
11063            (l, r, gt)
11064        };
11065        let mut inputs = StorageCache::new();
11066        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11067        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11068        let (result_arc, _) = PipelinedExecutor::realize(graph, gt_id, inputs).expect("realize");
11069        let guard = result_arc.read().unwrap();
11070        assert_eq!(guard.dtype, DType::Bool);
11071        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11072            panic!("expected Cpu storage");
11073        };
11074        let mask: &[u8] = c.as_slice().expect("u8 view");
11075        // 3.0 > 2.0 → 1;  5.0 > 5.0 → 0 (strict);  2.0 > 3.0 → 0;
11076        // NaN > 0.0 → 0 (unordered);  1.0 > 0.0 → 1.
11077        assert_eq!(mask, &[1, 0, 0, 0, 1]);
11078    }
11079
11080    /// E2E: Op::Ge F32 → Bool mask. Greater-or-equal: equality slot
11081    /// is `1` (distinguishes from Gt). NaN unordered → `0`. Closes
11082    /// the comparison family with full `[Eq, Ne, Lt, Le, Gt, Ge]`
11083    /// coverage.
11084    #[test]
11085    fn pipelined_realize_ge_f32_to_bool_mask() {
11086        let lhs = fuel_memory::from_slice_cpu(&[3.0_f32, 5.0, 2.0, f32::NAN, 0.0]);
11087        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 3.0, 0.0, 0.0]);
11088        let graph = Arc::new(RwLock::new(Graph::new()));
11089        let (l_id, r_id, ge_id) = {
11090            let mut g = graph.write().unwrap();
11091            let l = g.push(Node {
11092                op: Op::Const,
11093                inputs: vec![],
11094                shape: Shape::from_dims(&[5]),
11095                dtype: DType::F32,
11096            });
11097            let r = g.push(Node {
11098                op: Op::Const,
11099                inputs: vec![],
11100                shape: Shape::from_dims(&[5]),
11101                dtype: DType::F32,
11102            });
11103            let ge = g.push(Node {
11104                op: Op::Ge,
11105                inputs: vec![l, r],
11106                shape: Shape::from_dims(&[5]),
11107                dtype: DType::Bool,
11108            });
11109            g.set_target_backend(ge, BackendId::Cpu);
11110            (l, r, ge)
11111        };
11112        let mut inputs = StorageCache::new();
11113        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11114        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11115        let (result_arc, _) = PipelinedExecutor::realize(graph, ge_id, inputs).expect("realize");
11116        let guard = result_arc.read().unwrap();
11117        assert_eq!(guard.dtype, DType::Bool);
11118        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11119            panic!("expected Cpu storage");
11120        };
11121        let mask: &[u8] = c.as_slice().expect("u8 view");
11122        // 3.0 >= 2.0 → 1;  5.0 >= 5.0 → 1 (key Gt difference);
11123        // 2.0 >= 3.0 → 0;  NaN >= 0.0 → 0 (unordered);  0.0 >= 0.0 → 1.
11124        assert_eq!(mask, &[1, 1, 0, 0, 1]);
11125    }
11126
11127    /// E2E: Op::Equal F64 → Bool mask. Confirms the F64 wrapper is
11128    /// independently registered and routed (binding-table key
11129    /// `(EqualElementwise, [F64, F64, U8], Cpu)`).
11130    #[test]
11131    fn pipelined_realize_eq_f64_to_bool_mask() {
11132        let lhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0]);
11133        let rhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 4.0]);
11134        let graph = Arc::new(RwLock::new(Graph::new()));
11135        let (l_id, r_id, eq_id) = {
11136            let mut g = graph.write().unwrap();
11137            let l = g.push(Node {
11138                op: Op::Const,
11139                inputs: vec![],
11140                shape: Shape::from_dims(&[3]),
11141                dtype: DType::F64,
11142            });
11143            let r = g.push(Node {
11144                op: Op::Const,
11145                inputs: vec![],
11146                shape: Shape::from_dims(&[3]),
11147                dtype: DType::F64,
11148            });
11149            let eq = g.push(Node {
11150                op: Op::Equal,
11151                inputs: vec![l, r],
11152                shape: Shape::from_dims(&[3]),
11153                dtype: DType::Bool,
11154            });
11155            g.set_target_backend(eq, BackendId::Cpu);
11156            (l, r, eq)
11157        };
11158        let mut inputs = StorageCache::new();
11159        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11160        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11161        let (result_arc, _) = PipelinedExecutor::realize(graph, eq_id, inputs).expect("realize");
11162        let guard = result_arc.read().unwrap();
11163        assert_eq!(guard.dtype, DType::Bool);
11164        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11165            panic!("expected Cpu storage");
11166        };
11167        let mask: &[u8] = c.as_slice().expect("u8 view");
11168        assert_eq!(mask, &[1, 1, 0]);
11169    }
11170
11171    /// E2E: Op::Where ternary select — `out[i] = if cond[i] != 0 { a[i] } else { b[i] }`.
11172    /// Validates (a) the binding-table key `(Where, [Bool, F32, F32, F32], Cpu)`
11173    /// resolves to the where_f32 wrapper, (b) the Bool cond input drives
11174    /// the per-slot pick, (c) outputs preserve the input dtype.
11175    ///
11176    /// GAP-168(c): the cond STORAGE is tagged Bool, not merely the graph node.
11177    /// Bool and U8 are byte-identical, so leaving the storage U8 under a Bool
11178    /// node is exactly the mismatch this cut exists to make visible.
11179    #[test]
11180    fn pipelined_realize_where_f32_picks_per_slot_from_bool_mask() {
11181        // cond = [1, 0, 1, 0, 1]; a = [1, 2, 3, 4, 5]; b = [10, 20, 30, 40, 50]
11182        // expected = [1, 20, 3, 40, 5]
11183        let mut cond_storage = fuel_memory::from_slice_cpu(&[1u8, 0, 1, 0, 1]);
11184        cond_storage.dtype = DType::Bool; // GAP-168(c): a Bool mask, not U8 bytes
11185        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0]);
11186        let b_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0]);
11187        let graph = Arc::new(RwLock::new(Graph::new()));
11188        let (cond_id, a_id, b_id, where_id) = {
11189            let mut g = graph.write().unwrap();
11190            let cond = g.push(Node {
11191                op: Op::Const,
11192                inputs: vec![],
11193                shape: Shape::from_dims(&[5]),
11194                dtype: DType::Bool,
11195            });
11196            let a = g.push(Node {
11197                op: Op::Const,
11198                inputs: vec![],
11199                shape: Shape::from_dims(&[5]),
11200                dtype: DType::F32,
11201            });
11202            let b = g.push(Node {
11203                op: Op::Const,
11204                inputs: vec![],
11205                shape: Shape::from_dims(&[5]),
11206                dtype: DType::F32,
11207            });
11208            let w = g.push(Node {
11209                op: Op::Where,
11210                inputs: vec![cond, a, b],
11211                shape: Shape::from_dims(&[5]),
11212                dtype: DType::F32,
11213            });
11214            g.set_target_backend(w, BackendId::Cpu);
11215            (cond, a, b, w)
11216        };
11217        let mut inputs = StorageCache::new();
11218        inputs.insert(cond_id, Arc::new(RwLock::new(cond_storage)));
11219        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
11220        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
11221        let (result_arc, _) = PipelinedExecutor::realize(graph, where_id, inputs).expect("realize");
11222        let guard = result_arc.read().unwrap();
11223        assert_eq!(guard.dtype, DType::F32);
11224        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11225            panic!("expected Cpu storage");
11226        };
11227        let out: &[f32] = c.as_slice().expect("f32 view");
11228        assert_eq!(out, &[1.0, 20.0, 3.0, 40.0, 5.0]);
11229    }
11230
11231    /// E2E: full chain `eq → where`. Compares two f32 vectors, then
11232    /// uses the resulting Bool mask to pick from a third tensor (or a
11233    /// fallback). Validates the comparison-family + Where ops compose
11234    /// end-to-end.
11235    #[test]
11236    fn pipelined_realize_eq_then_where_full_chain() {
11237        // a = [1, 2, 3]; b = [1, 5, 3] → eq = [1, 0, 1]
11238        // pick = [10, 20, 30]; fallback = [99, 99, 99]
11239        // result = [10, 99, 30]
11240        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
11241        let b_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0]);
11242        let pick_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
11243        let fb_storage = fuel_memory::from_slice_cpu(&[99.0_f32, 99.0, 99.0]);
11244        let graph = Arc::new(RwLock::new(Graph::new()));
11245        let (a_id, b_id, pick_id, fb_id, where_id) = {
11246            let mut g = graph.write().unwrap();
11247            let a = g.push(Node {
11248                op: Op::Const,
11249                inputs: vec![],
11250                shape: Shape::from_dims(&[3]),
11251                dtype: DType::F32,
11252            });
11253            let b = g.push(Node {
11254                op: Op::Const,
11255                inputs: vec![],
11256                shape: Shape::from_dims(&[3]),
11257                dtype: DType::F32,
11258            });
11259            let pick = g.push(Node {
11260                op: Op::Const,
11261                inputs: vec![],
11262                shape: Shape::from_dims(&[3]),
11263                dtype: DType::F32,
11264            });
11265            let fb = g.push(Node {
11266                op: Op::Const,
11267                inputs: vec![],
11268                shape: Shape::from_dims(&[3]),
11269                dtype: DType::F32,
11270            });
11271            let eq = g.push(Node {
11272                op: Op::Equal,
11273                inputs: vec![a, b],
11274                shape: Shape::from_dims(&[3]),
11275                dtype: DType::Bool,
11276            });
11277            let w = g.push(Node {
11278                op: Op::Where,
11279                inputs: vec![eq, pick, fb],
11280                shape: Shape::from_dims(&[3]),
11281                dtype: DType::F32,
11282            });
11283            g.set_target_backend(eq, BackendId::Cpu);
11284            g.set_target_backend(w, BackendId::Cpu);
11285            (a, b, pick, fb, w)
11286        };
11287        let mut inputs = StorageCache::new();
11288        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
11289        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
11290        inputs.insert(pick_id, Arc::new(RwLock::new(pick_storage)));
11291        inputs.insert(fb_id, Arc::new(RwLock::new(fb_storage)));
11292        let (result_arc, _) = PipelinedExecutor::realize(graph, where_id, inputs).expect("realize");
11293        let guard = result_arc.read().unwrap();
11294        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11295            panic!("expected Cpu storage");
11296        };
11297        let out: &[f32] = c.as_slice().expect("f32 view");
11298        assert_eq!(out, &[10.0, 99.0, 30.0]);
11299    }
11300
11301    /// E2E: Q4_0 QMatMul through the pipelined executor — proves
11302    /// quantized weights can flow into the unified path. Activations
11303    /// are F32, weights are U32-typed (raw block bytes).
11304    /// Construct a Q4_0 weight tensor where every weight = 1.0
11305    /// (d=1.0, every nibble=9 → 1*(9-8)=1), so A @ W^T computes
11306    /// the per-row sum of activations.
11307    #[test]
11308    fn pipelined_realize_qmatmul_q4_0_unit_weight_sums_activations() {
11309        use fuel_graph::QuantType;
11310        use half::f16;
11311        let block_size = std::mem::size_of::<fuel_quantized::BlockQ4_0>();
11312        let mut w_bytes = vec![0u8; 2 * block_size];
11313        for block_idx in 0..2 {
11314            let off = block_idx * block_size;
11315            let d_bytes = f16::from_f32(1.0).to_le_bytes();
11316            w_bytes[off..off + 2].copy_from_slice(&d_bytes);
11317            for i in 0..16 {
11318                w_bytes[off + 2 + i] = 0x99;
11319            }
11320        }
11321        // Weight tensor is U32-typed (rank-1, length = bytes/4)
11322        let w_storage = fuel_memory::Storage::new(
11323            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
11324                &w_bytes,
11325            )),
11326            DType::U32,
11327        );
11328
11329        let act_vec: Vec<f32> = (1..=32).map(|x| x as f32).collect();
11330        let act_storage = fuel_memory::from_slice_cpu(&act_vec);
11331
11332        let graph = Arc::new(RwLock::new(Graph::new()));
11333        let (act_id, w_id, mm_id) = {
11334            let mut g = graph.write().unwrap();
11335            let act = g.push(Node {
11336                op: Op::Const,
11337                inputs: vec![],
11338                shape: Shape::from_dims(&[1, 32]),
11339                dtype: DType::F32,
11340            });
11341            let w = g.push(Node {
11342                op: Op::Const,
11343                inputs: vec![],
11344                shape: Shape::from_dims(&[w_bytes.len() / 4]),
11345                dtype: DType::U32,
11346            });
11347            let mm = g.push(Node {
11348                op: Op::Fused(
11349                    fuel_graph::registry::FusedOps::QMATMUL,
11350                    fuel_graph::registry::FusedOpParams::QMatMul {
11351                        quant_type: QuantType::Q4_0,
11352                        k: 32,
11353                        n: 2,
11354                    },
11355                ),
11356                inputs: vec![act, w],
11357                shape: Shape::from_dims(&[1, 2]),
11358                dtype: DType::F32,
11359            });
11360            g.set_target_backend(mm, BackendId::Cpu);
11361            (act, w, mm)
11362        };
11363        let mut inputs = StorageCache::new();
11364        inputs.insert(act_id, Arc::new(RwLock::new(act_storage)));
11365        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
11366        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11367        let guard = result_arc.read().unwrap();
11368        assert_eq!(guard.dtype, DType::F32);
11369        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11370            panic!("expected Cpu storage");
11371        };
11372        let r: &[f32] = c.as_slice().unwrap();
11373        // Both rows = sum(1..=32) = 528, within Q8_1 round-trip
11374        // tolerance.
11375        assert!((r[0] - 528.0).abs() < 0.5, "got {}, want 528", r[0]);
11376        assert!((r[1] - 528.0).abs() < 0.5, "got {}, want 528", r[1]);
11377    }
11378
11379    /// E2E: QMatMul with Q5_0 weights — verifies the new quant
11380    /// dispatch arm picks `qmatmul_q5_0_f32`. We build weights by
11381    /// quantizing all-ones via `BlockQ5_0::from_float`, then
11382    /// compare pipelined output against the direct fuel_quantized
11383    /// matmul on the same blocks.
11384    #[test]
11385    fn pipelined_realize_qmatmul_q5_0_against_reference() {
11386        use fuel_graph::QuantType;
11387        use fuel_quantized::{BlockQ5_0, GgmlType};
11388        let n = 2;
11389        let k = 64; // 2 blocks per row
11390        // Quantize an all-ones [n, k] weight matrix.
11391        let w_f32 = vec![1.0_f32; n * k];
11392        let blocks_per_row = k / BlockQ5_0::BLCK_SIZE;
11393        let mut w_blocks = vec![BlockQ5_0::zeros(); n * blocks_per_row];
11394        BlockQ5_0::from_float(&w_f32, &mut w_blocks);
11395        // Reinterpret block slice as bytes (BlockQ5_0 is #[repr(C)]).
11396        let bytes_per_block = std::mem::size_of::<BlockQ5_0>();
11397        let w_bytes: Vec<u8> = unsafe {
11398            std::slice::from_raw_parts(
11399                w_blocks.as_ptr() as *const u8,
11400                w_blocks.len() * bytes_per_block,
11401            )
11402        }
11403        .to_vec();
11404        let w_storage = fuel_memory::Storage::new(
11405            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
11406                &w_bytes,
11407            )),
11408            DType::U32,
11409        );
11410        let act_vec: Vec<f32> = (1..=k).map(|x| x as f32).collect();
11411        let act_storage = fuel_memory::from_slice_cpu(&act_vec);
11412        // Reference: direct matmul through fuel_quantized.
11413        let mut ref_out = vec![0.0_f32; n];
11414        fuel_quantized::matmul::<BlockQ5_0>((1, k, n), &act_vec, &w_blocks, &mut ref_out)
11415            .expect("ref matmul");
11416
11417        let graph = Arc::new(RwLock::new(Graph::new()));
11418        let (act_id, w_id, mm_id) = {
11419            let mut g = graph.write().unwrap();
11420            let act = g.push(Node {
11421                op: Op::Const,
11422                inputs: vec![],
11423                shape: Shape::from_dims(&[1, k]),
11424                dtype: DType::F32,
11425            });
11426            let w = g.push(Node {
11427                op: Op::Const,
11428                inputs: vec![],
11429                shape: Shape::from_dims(&[w_bytes.len() / 4]),
11430                dtype: DType::U32,
11431            });
11432            let mm = g.push(Node {
11433                op: Op::Fused(
11434                    fuel_graph::registry::FusedOps::QMATMUL,
11435                    fuel_graph::registry::FusedOpParams::QMatMul {
11436                        quant_type: QuantType::Q5_0,
11437                        k,
11438                        n,
11439                    },
11440                ),
11441                inputs: vec![act, w],
11442                shape: Shape::from_dims(&[1, n]),
11443                dtype: DType::F32,
11444            });
11445            g.set_target_backend(mm, BackendId::Cpu);
11446            (act, w, mm)
11447        };
11448        let mut inputs = StorageCache::new();
11449        inputs.insert(act_id, Arc::new(RwLock::new(act_storage)));
11450        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
11451        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11452        let guard = result_arc.read().unwrap();
11453        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11454            panic!("expected Cpu storage");
11455        };
11456        let r: &[f32] = c.as_slice().unwrap();
11457        // Bit-exact against same kernel via the trait, since both
11458        // paths run fuel_quantized::matmul<BlockQ5_0>.
11459        assert_eq!(
11460            r,
11461            ref_out.as_slice(),
11462            "pipelined Q5_0 differs from reference: got {r:?}, want {ref_out:?}"
11463        );
11464    }
11465
11466    /// E2E: QMatMul with Q6K (256-element super-block k-quant).
11467    /// Same idea as the Q5_0 test — bit-exact against the
11468    /// reference fuel_quantized::matmul<BlockQ6K>. Confirms the
11469    /// dispatch arm wires `qmatmul_q6k_f32` correctly.
11470    #[test]
11471    fn pipelined_realize_qmatmul_q6k_against_reference() {
11472        use fuel_graph::QuantType;
11473        use fuel_quantized::{BlockQ6K, GgmlType};
11474        let n = 2;
11475        let k = 256; // 1 super-block per row
11476        let w_f32 = vec![1.0_f32; n * k];
11477        let blocks_per_row = k / BlockQ6K::BLCK_SIZE;
11478        let mut w_blocks = vec![BlockQ6K::zeros(); n * blocks_per_row];
11479        BlockQ6K::from_float(&w_f32, &mut w_blocks);
11480        let bytes_per_block = std::mem::size_of::<BlockQ6K>();
11481        let w_bytes: Vec<u8> = unsafe {
11482            std::slice::from_raw_parts(
11483                w_blocks.as_ptr() as *const u8,
11484                w_blocks.len() * bytes_per_block,
11485            )
11486        }
11487        .to_vec();
11488        let w_storage = fuel_memory::Storage::new(
11489            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
11490                &w_bytes,
11491            )),
11492            DType::U32,
11493        );
11494        let act_vec: Vec<f32> = (1..=k).map(|x| x as f32 / 100.0).collect();
11495        let act_storage = fuel_memory::from_slice_cpu(&act_vec);
11496        let mut ref_out = vec![0.0_f32; n];
11497        fuel_quantized::matmul::<BlockQ6K>((1, k, n), &act_vec, &w_blocks, &mut ref_out)
11498            .expect("ref matmul");
11499
11500        let graph = Arc::new(RwLock::new(Graph::new()));
11501        let (act_id, w_id, mm_id) = {
11502            let mut g = graph.write().unwrap();
11503            let act = g.push(Node {
11504                op: Op::Const,
11505                inputs: vec![],
11506                shape: Shape::from_dims(&[1, k]),
11507                dtype: DType::F32,
11508            });
11509            let w = g.push(Node {
11510                op: Op::Const,
11511                inputs: vec![],
11512                shape: Shape::from_dims(&[w_bytes.len() / 4]),
11513                dtype: DType::U32,
11514            });
11515            let mm = g.push(Node {
11516                op: Op::Fused(
11517                    fuel_graph::registry::FusedOps::QMATMUL,
11518                    fuel_graph::registry::FusedOpParams::QMatMul {
11519                        quant_type: QuantType::Q6K,
11520                        k,
11521                        n,
11522                    },
11523                ),
11524                inputs: vec![act, w],
11525                shape: Shape::from_dims(&[1, n]),
11526                dtype: DType::F32,
11527            });
11528            g.set_target_backend(mm, BackendId::Cpu);
11529            (act, w, mm)
11530        };
11531        let mut inputs = StorageCache::new();
11532        inputs.insert(act_id, Arc::new(RwLock::new(act_storage)));
11533        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
11534        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11535        let guard = result_arc.read().unwrap();
11536        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11537            panic!("expected Cpu storage");
11538        };
11539        let r: &[f32] = c.as_slice().unwrap();
11540        assert_eq!(
11541            r,
11542            ref_out.as_slice(),
11543            "pipelined Q6K differs from reference: got {r:?}, want {ref_out:?}"
11544        );
11545    }
11546
11547    /// E2E: `QMatMul` through the pipelined executor for the formats added with the float route
11548    /// (Q3_K, Q5_K, IQ4_NL, IQ4_XS, IQ3_S; board 307: dequantized tile by tile, multiplied in
11549    /// float). The weights are the type's own blocks from random bytes (a small finite `d`), the
11550    /// reference is `fuel_quantized::matmul`, and the dispatch arm must be the one for that type:
11551    /// a wrong `quant_type` arm decodes the same bytes differently and is far from the reference.
11552    fn qmatmul_e2e_random_blocks<T: fuel_quantized::GgmlType>(quant_type: fuel_graph::QuantType) {
11553        let (m, n, k) = (3, 5, 512);
11554        let size = std::mem::size_of::<T>();
11555        let count = n * k / T::BLCK_SIZE;
11556        let mut seed = 0x9E37_79B9_u32;
11557        let mut w_bytes: Vec<u8> = (0..count * size)
11558            .map(|_| {
11559                seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
11560                (seed >> 24) as u8
11561            })
11562            .collect();
11563        let d = half::f16::from_f32(0.02).to_le_bytes();
11564        for b in 0..count {
11565            w_bytes[b * size..b * size + 2].copy_from_slice(&d);
11566        }
11567        let mut w_blocks = vec![T::zeros(); count];
11568        bytemuck::cast_slice_mut::<T, u8>(&mut w_blocks).copy_from_slice(&w_bytes);
11569        let act_vec: Vec<f32> = (0..m * k).map(|x| ((x % 17) as f32 - 8.0) / 8.0).collect();
11570        let mut ref_out = vec![0.0_f32; m * n];
11571        fuel_quantized::matmul::<T>((m, k, n), &act_vec, &w_blocks, &mut ref_out).expect("ref");
11572
11573        let w_storage = fuel_memory::Storage::new(
11574            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
11575                &w_bytes,
11576            )),
11577            DType::U32,
11578        );
11579        let graph = Arc::new(RwLock::new(Graph::new()));
11580        let (act_id, w_id, mm_id) = {
11581            let mut g = graph.write().unwrap();
11582            let act = g.push(Node {
11583                op: Op::Const,
11584                inputs: vec![],
11585                shape: Shape::from_dims(&[m, k]),
11586                dtype: DType::F32,
11587            });
11588            let w = g.push(Node {
11589                op: Op::Const,
11590                inputs: vec![],
11591                shape: Shape::from_dims(&[w_bytes.len() / 4]),
11592                dtype: DType::U32,
11593            });
11594            let mm = g.push(Node {
11595                op: Op::Fused(
11596                    fuel_graph::registry::FusedOps::QMATMUL,
11597                    fuel_graph::registry::FusedOpParams::QMatMul { quant_type, k, n },
11598                ),
11599                inputs: vec![act, w],
11600                shape: Shape::from_dims(&[m, n]),
11601                dtype: DType::F32,
11602            });
11603            g.set_target_backend(mm, BackendId::Cpu);
11604            (act, w, mm)
11605        };
11606        let mut inputs = StorageCache::new();
11607        inputs.insert(
11608            act_id,
11609            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&act_vec))),
11610        );
11611        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
11612        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11613        let guard = result_arc.read().unwrap();
11614        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11615            panic!("expected Cpu storage");
11616        };
11617        let r: &[f32] = c.as_slice().unwrap();
11618        let scale = ref_out.iter().fold(1e-6_f32, |a, v| a.max(v.abs()));
11619        let worst = r
11620            .iter()
11621            .zip(&ref_out)
11622            .fold(0.0_f32, |a, (x, y)| a.max((x - y).abs()));
11623        assert!(
11624            worst <= 1e-5 * scale,
11625            "{quant_type:?}: pipelined differs from the reference by {worst} (scale {scale})"
11626        );
11627        assert!(
11628            scale > 1e-3,
11629            "{quant_type:?}: the product is all zeros, the test is vacuous"
11630        );
11631    }
11632
11633    #[test]
11634    fn pipelined_realize_qmatmul_float_route_formats_against_reference() {
11635        use fuel_graph::QuantType;
11636        use fuel_quantized::iq_grid_types::BlockIq3S;
11637        use fuel_quantized::iq4::{BlockIq4Nl, BlockIq4Xs};
11638        use fuel_quantized::{BlockQ3K, BlockQ5K};
11639        qmatmul_e2e_random_blocks::<BlockQ3K>(QuantType::Q3K);
11640        qmatmul_e2e_random_blocks::<BlockQ5K>(QuantType::Q5K);
11641        qmatmul_e2e_random_blocks::<BlockIq4Nl>(QuantType::Iq4Nl);
11642        qmatmul_e2e_random_blocks::<BlockIq4Xs>(QuantType::Iq4Xs);
11643        qmatmul_e2e_random_blocks::<BlockIq3S>(QuantType::Iq3S);
11644    }
11645
11646    /// E2E: BF16 RmsNormLastDim through the pipelined executor.
11647    /// Verifies that capability-driven dispatch routes the
11648    /// half-float norm op to the bf16-specific kernel (which
11649    /// accumulates in f32 internally).
11650    #[test]
11651    fn pipelined_realize_rms_norm_bf16() {
11652        let v: Vec<half::bf16> = [3.0_f32, 4.0]
11653            .iter()
11654            .map(|&x| half::bf16::from_f32(x))
11655            .collect();
11656        let storage = fuel_memory::from_slice_cpu(&v);
11657        let graph = Arc::new(RwLock::new(Graph::new()));
11658        let (in_id, op_id) = {
11659            let mut g = graph.write().unwrap();
11660            let in_id = g.push(Node {
11661                op: Op::Const,
11662                inputs: vec![],
11663                shape: Shape::from_dims(&[1, 2]),
11664                dtype: DType::BF16,
11665            });
11666            let op_id = g.push(Node {
11667                op: Op::Fused(
11668                    fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM,
11669                    fuel_graph::registry::FusedOpParams::RmsNormLastDim { eps: 0.0 },
11670                ),
11671                inputs: vec![in_id],
11672                shape: Shape::from_dims(&[1, 2]),
11673                dtype: DType::BF16,
11674            });
11675            g.set_target_backend(op_id, BackendId::Cpu);
11676            (in_id, op_id)
11677        };
11678        let mut inputs = StorageCache::new();
11679        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11680        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
11681        let guard = result_arc.read().unwrap();
11682        assert_eq!(guard.dtype, DType::BF16);
11683        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11684            panic!("expected Cpu storage");
11685        };
11686        let r: &[half::bf16] = c.as_slice().unwrap();
11687        let rms = (12.5_f32).sqrt();
11688        // bf16's ~3-digit mantissa absorbs the divisor; allow ~5%.
11689        assert!((r[0].to_f32() - 3.0 / rms).abs() < 0.05);
11690        assert!((r[1].to_f32() - 4.0 / rms).abs() < 0.05);
11691    }
11692
11693    /// E2E: BF16 matmul through the pipelined executor — proves
11694    /// the LLM forward-pass blocker (every transformer layer
11695    /// is dominated by matmul). Identity matmul on bf16 round-
11696    /// trips small integers exactly.
11697    #[test]
11698    fn pipelined_realize_matmul_bf16_identity() {
11699        let lhs_v: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0]
11700            .iter()
11701            .map(|&x| half::bf16::from_f32(x))
11702            .collect();
11703        let rhs_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0]
11704            .iter()
11705            .map(|&x| half::bf16::from_f32(x))
11706            .collect();
11707        let lhs = fuel_memory::from_slice_cpu(&lhs_v);
11708        let rhs = fuel_memory::from_slice_cpu(&rhs_v);
11709        let graph = Arc::new(RwLock::new(Graph::new()));
11710        let (l_id, r_id, mm_id) = {
11711            let mut g = graph.write().unwrap();
11712            let l = g.push(Node {
11713                op: Op::Const,
11714                inputs: vec![],
11715                shape: Shape::from_dims(&[2, 2]),
11716                dtype: DType::BF16,
11717            });
11718            let r = g.push(Node {
11719                op: Op::Const,
11720                inputs: vec![],
11721                shape: Shape::from_dims(&[2, 2]),
11722                dtype: DType::BF16,
11723            });
11724            let mm = g.push(Node {
11725                op: Op::MatMul,
11726                inputs: vec![l, r],
11727                shape: Shape::from_dims(&[2, 2]),
11728                dtype: DType::BF16,
11729            });
11730            g.set_target_backend(mm, BackendId::Cpu);
11731            (l, r, mm)
11732        };
11733        let mut inputs = StorageCache::new();
11734        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11735        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11736        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11737        let guard = result_arc.read().unwrap();
11738        assert_eq!(guard.dtype, DType::BF16);
11739        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11740            panic!("expected Cpu storage");
11741        };
11742        let r: &[half::bf16] = c.as_slice().unwrap();
11743        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
11744        assert_eq!(result_f32, vec![1.0, 2.0, 3.0, 4.0]);
11745    }
11746
11747    /// E2E (ROADMAP row 34): a mixed `[F32, W, F32]` matmul (f32 activation, half weight) runs on
11748    /// the CPU through the NATIVE kernel, with the weight left half-width: the output is f32 and
11749    /// equals the f64 matmul over the widened weights to f32 accumulation error. The weight is
11750    /// rounded to its stored half type first.
11751    fn mixed_cpu_matmul_matches_f64(weight_dtype: DType) {
11752        let (m, n, k) = (3_usize, 5_usize, 7_usize);
11753        let a: Vec<f32> = (0..m * k)
11754            .map(|i| ((i * 37 % 19) as f32 - 9.0) / 8.0)
11755            .collect();
11756        let w_f32: Vec<f32> = (0..k * n)
11757            .map(|i| ((i * 53 % 23) as f32 - 11.0) / 10.0)
11758            .collect();
11759        let (w_storage, widened): (_, Vec<f32>) = if weight_dtype == DType::BF16 {
11760            let h: Vec<half::bf16> = w_f32.iter().map(|&x| half::bf16::from_f32(x)).collect();
11761            let wide = h.iter().map(|x| x.to_f32()).collect();
11762            (fuel_memory::from_slice_cpu(&h), wide)
11763        } else {
11764            let h: Vec<half::f16> = w_f32.iter().map(|&x| half::f16::from_f32(x)).collect();
11765            let wide = h.iter().map(|x| x.to_f32()).collect();
11766            (fuel_memory::from_slice_cpu(&h), wide)
11767        };
11768        let graph = Arc::new(RwLock::new(Graph::new()));
11769        let (l_id, r_id, mm_id) = {
11770            let mut g = graph.write().unwrap();
11771            let l = g.push(Node {
11772                op: Op::Const,
11773                inputs: vec![],
11774                shape: Shape::from_dims(&[m, k]),
11775                dtype: DType::F32,
11776            });
11777            let r = g.push(Node {
11778                op: Op::Const,
11779                inputs: vec![],
11780                shape: Shape::from_dims(&[k, n]),
11781                dtype: weight_dtype,
11782            });
11783            let mm = g.push(Node {
11784                op: Op::MatMul,
11785                inputs: vec![l, r],
11786                shape: Shape::from_dims(&[m, n]),
11787                dtype: DType::F32,
11788            });
11789            g.set_target_backend(mm, BackendId::Cpu);
11790            (l, r, mm)
11791        };
11792        let mut inputs = StorageCache::new();
11793        inputs.insert(l_id, Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&a))));
11794        inputs.insert(r_id, Arc::new(RwLock::new(w_storage)));
11795        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11796        let guard = result_arc.read().unwrap();
11797        assert_eq!(guard.dtype, DType::F32);
11798        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11799            panic!("expected Cpu storage");
11800        };
11801        let got: &[f32] = c.as_slice().unwrap();
11802        for i in 0..m {
11803            for j in 0..n {
11804                let want: f64 = (0..k)
11805                    .map(|kk| a[i * k + kk] as f64 * widened[kk * n + j] as f64)
11806                    .sum();
11807                let err = (got[i * n + j] as f64 - want).abs();
11808                assert!(
11809                    err < 1e-5,
11810                    "{weight_dtype:?} [{i},{j}]: got {}, want {want}",
11811                    got[i * n + j]
11812                );
11813            }
11814        }
11815    }
11816
11817    #[test]
11818    fn pipelined_realize_mixed_f32_bf16_matmul_is_native_on_cpu() {
11819        mixed_cpu_matmul_matches_f64(DType::BF16);
11820    }
11821
11822    #[test]
11823    fn pipelined_realize_mixed_f32_f16_matmul_is_native_on_cpu() {
11824        mixed_cpu_matmul_matches_f64(DType::F16);
11825    }
11826
11827    /// E2E: F16 sum-reduce — verifies bf16/f16 reduction dispatch
11828    /// works through the executor.
11829    #[test]
11830    fn pipelined_realize_sum_dim_f16() {
11831        let v: Vec<half::f16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]
11832            .iter()
11833            .map(|&x| half::f16::from_f32(x))
11834            .collect();
11835        let storage = fuel_memory::from_slice_cpu(&v);
11836        let graph = Arc::new(RwLock::new(Graph::new()));
11837        let (in_id, sum_id) = {
11838            let mut g = graph.write().unwrap();
11839            let in_id = g.push(Node {
11840                op: Op::Const,
11841                inputs: vec![],
11842                shape: Shape::from_dims(&[2, 3]),
11843                dtype: DType::F16,
11844            });
11845            let sum_id = g.push(Node {
11846                op: Op::SumDim(1),
11847                inputs: vec![in_id],
11848                shape: Shape::from_dims(&[2]),
11849                dtype: DType::F16,
11850            });
11851            g.set_target_backend(sum_id, BackendId::Cpu);
11852            (in_id, sum_id)
11853        };
11854        let mut inputs = StorageCache::new();
11855        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11856        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
11857        let guard = result_arc.read().unwrap();
11858        assert_eq!(guard.dtype, DType::F16);
11859        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11860            panic!("expected Cpu storage");
11861        };
11862        let r: &[half::f16] = c.as_slice().unwrap();
11863        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
11864        assert_eq!(result_f32, vec![6.0, 15.0]);
11865    }
11866
11867    /// E2E: BF16 elementwise add through the pipelined executor.
11868    #[test]
11869    fn pipelined_realize_add_bf16() {
11870        let lhs_vec: Vec<half::bf16> = [1.0_f32, 2.0, 3.0]
11871            .iter()
11872            .map(|&x| half::bf16::from_f32(x))
11873            .collect();
11874        let rhs_vec: Vec<half::bf16> = [10.0_f32, 20.0, 30.0]
11875            .iter()
11876            .map(|&x| half::bf16::from_f32(x))
11877            .collect();
11878        let lhs = fuel_memory::from_slice_cpu(&lhs_vec);
11879        let rhs = fuel_memory::from_slice_cpu(&rhs_vec);
11880        let graph = Arc::new(RwLock::new(Graph::new()));
11881        let (l_id, r_id, op_id) = {
11882            let mut g = graph.write().unwrap();
11883            let l = g.push(Node {
11884                op: Op::Const,
11885                inputs: vec![],
11886                shape: Shape::from_dims(&[3]),
11887                dtype: DType::BF16,
11888            });
11889            let r = g.push(Node {
11890                op: Op::Const,
11891                inputs: vec![],
11892                shape: Shape::from_dims(&[3]),
11893                dtype: DType::BF16,
11894            });
11895            let op = g.push(Node {
11896                op: Op::Add,
11897                inputs: vec![l, r],
11898                shape: Shape::from_dims(&[3]),
11899                dtype: DType::BF16,
11900            });
11901            g.set_target_backend(op, BackendId::Cpu);
11902            (l, r, op)
11903        };
11904        let mut inputs = StorageCache::new();
11905        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11906        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11907        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
11908        let guard = result_arc.read().unwrap();
11909        assert_eq!(guard.dtype, DType::BF16);
11910        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11911            panic!("expected Cpu storage");
11912        };
11913        let r: &[half::bf16] = c.as_slice().unwrap();
11914        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
11915        assert_eq!(result_f32, vec![11.0, 22.0, 33.0]);
11916    }
11917
11918    /// E2E: F16 unary chain — Const + Sqr + Sqrt — verifies F16
11919    /// dispatch works and the via-f32 round-trip kernels behave
11920    /// correctly through the executor.
11921    #[test]
11922    fn pipelined_realize_sqr_then_sqrt_f16() {
11923        let v: Vec<half::f16> = [1.0_f32, 4.0, 9.0]
11924            .iter()
11925            .map(|&x| half::f16::from_f32(x))
11926            .collect();
11927        let storage = fuel_memory::from_slice_cpu(&v);
11928        let graph = Arc::new(RwLock::new(Graph::new()));
11929        let (in_id, sqrt_id) = {
11930            let mut g = graph.write().unwrap();
11931            let in_id = g.push(Node {
11932                op: Op::Const,
11933                inputs: vec![],
11934                shape: Shape::from_dims(&[3]),
11935                dtype: DType::F16,
11936            });
11937            let sqr_id = g.push(Node {
11938                op: Op::Sqr,
11939                inputs: vec![in_id],
11940                shape: Shape::from_dims(&[3]),
11941                dtype: DType::F16,
11942            });
11943            let sqrt_id = g.push(Node {
11944                op: Op::Sqrt,
11945                inputs: vec![sqr_id],
11946                shape: Shape::from_dims(&[3]),
11947                dtype: DType::F16,
11948            });
11949            g.set_target_backend(sqr_id, BackendId::Cpu);
11950            g.set_target_backend(sqrt_id, BackendId::Cpu);
11951            (in_id, sqrt_id)
11952        };
11953        let mut inputs = StorageCache::new();
11954        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11955        let (result_arc, _) = PipelinedExecutor::realize(graph, sqrt_id, inputs).expect("realize");
11956        let guard = result_arc.read().unwrap();
11957        assert_eq!(guard.dtype, DType::F16);
11958        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11959            panic!("expected Cpu storage");
11960        };
11961        let r: &[half::f16] = c.as_slice().unwrap();
11962        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
11963        // f16 has ~3 decimal digits; sqrt(sqr(x)) = |x| within rounding.
11964        for (got, want) in result_f32.iter().zip(&[1.0_f32, 4.0, 9.0]) {
11965            assert!((got - want).abs() < 0.05, "got {got}, want {want}");
11966        }
11967    }
11968
11969    /// E2E: F64 sum-reduce along one dim through the pipelined
11970    /// executor.
11971    #[test]
11972    fn pipelined_realize_sum_dim_f64() {
11973        let storage = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
11974        let graph = Arc::new(RwLock::new(Graph::new()));
11975        let (in_id, sum_id) = {
11976            let mut g = graph.write().unwrap();
11977            let in_id = g.push(Node {
11978                op: Op::Const,
11979                inputs: vec![],
11980                shape: Shape::from_dims(&[2, 3]),
11981                dtype: DType::F64,
11982            });
11983            let sum_id = g.push(Node {
11984                op: Op::SumDim(1),
11985                inputs: vec![in_id],
11986                shape: Shape::from_dims(&[2]),
11987                dtype: DType::F64,
11988            });
11989            g.set_target_backend(sum_id, BackendId::Cpu);
11990            (in_id, sum_id)
11991        };
11992        let mut inputs = StorageCache::new();
11993        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11994        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
11995        let guard = result_arc.read().unwrap();
11996        assert_eq!(guard.dtype, DType::F64);
11997        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11998            panic!("expected Cpu storage");
11999        };
12000        assert_eq!(c.as_slice::<f64>().unwrap(), &[6.0_f64, 15.0]);
12001    }
12002
12003    /// E2E: F64 matmul through the pipelined executor.
12004    #[test]
12005    fn pipelined_realize_matmul_2x3_times_3x2_f64() {
12006        let lhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
12007        let rhs = fuel_memory::from_slice_cpu(&[7.0_f64, 8.0, 9.0, 10.0, 11.0, 12.0]);
12008        let graph = Arc::new(RwLock::new(Graph::new()));
12009        let (l_id, r_id, mm_id) = {
12010            let mut g = graph.write().unwrap();
12011            let l = g.push(Node {
12012                op: Op::Const,
12013                inputs: vec![],
12014                shape: Shape::from_dims(&[2, 3]),
12015                dtype: DType::F64,
12016            });
12017            let r = g.push(Node {
12018                op: Op::Const,
12019                inputs: vec![],
12020                shape: Shape::from_dims(&[3, 2]),
12021                dtype: DType::F64,
12022            });
12023            let mm = g.push(Node {
12024                op: Op::MatMul,
12025                inputs: vec![l, r],
12026                shape: Shape::from_dims(&[2, 2]),
12027                dtype: DType::F64,
12028            });
12029            g.set_target_backend(mm, BackendId::Cpu);
12030            (l, r, mm)
12031        };
12032        let mut inputs = StorageCache::new();
12033        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
12034        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
12035        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
12036        let guard = result_arc.read().unwrap();
12037        assert_eq!(guard.dtype, DType::F64);
12038        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12039            panic!("expected Cpu storage");
12040        };
12041        assert_eq!(
12042            c.as_slice::<f64>().unwrap(),
12043            &[58.0_f64, 64.0, 139.0, 154.0]
12044        );
12045    }
12046
12047    /// E2E: F64 unary chain — Const + Sqr + Sqrt — verifies that
12048    /// the kernel-binding lookup picks the f64 entries when the
12049    /// graph nodes carry DType::F64.
12050    #[test]
12051    fn pipelined_realize_sqr_then_sqrt_f64() {
12052        let storage = fuel_memory::from_slice_cpu(&[1.0_f64, 4.0, 9.0]);
12053        let graph = Arc::new(RwLock::new(Graph::new()));
12054        let (in_id, sqrt_id) = {
12055            let mut g = graph.write().unwrap();
12056            let in_id = g.push(Node {
12057                op: Op::Const,
12058                inputs: vec![],
12059                shape: Shape::from_dims(&[3]),
12060                dtype: DType::F64,
12061            });
12062            let sqr_id = g.push(Node {
12063                op: Op::Sqr,
12064                inputs: vec![in_id],
12065                shape: Shape::from_dims(&[3]),
12066                dtype: DType::F64,
12067            });
12068            let sqrt_id = g.push(Node {
12069                op: Op::Sqrt,
12070                inputs: vec![sqr_id],
12071                shape: Shape::from_dims(&[3]),
12072                dtype: DType::F64,
12073            });
12074            g.set_target_backend(sqr_id, BackendId::Cpu);
12075            g.set_target_backend(sqrt_id, BackendId::Cpu);
12076            (in_id, sqrt_id)
12077        };
12078        let mut inputs = StorageCache::new();
12079        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12080        let (result_arc, _) = PipelinedExecutor::realize(graph, sqrt_id, inputs).expect("realize");
12081        let guard = result_arc.read().unwrap();
12082        assert_eq!(guard.dtype, DType::F64);
12083        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12084            panic!("expected Cpu storage");
12085        };
12086        assert_eq!(c.as_slice::<f64>().unwrap(), &[1.0_f64, 4.0, 9.0]);
12087    }
12088
12089    /// E2E: ArgMaxDim — produces U32 output indices.
12090    #[test]
12091    fn pipelined_realize_argmax_dim() {
12092        // input [2, 3] = [[1, 5, 2], [9, 0, 4]]
12093        // argmax dim=1 → [1, 0]
12094        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 2.0, 9.0, 0.0, 4.0]);
12095        let graph = Arc::new(RwLock::new(Graph::new()));
12096        let (in_id, op_id) = {
12097            let mut g = graph.write().unwrap();
12098            let in_id = g.push(Node {
12099                op: Op::Const,
12100                inputs: vec![],
12101                shape: Shape::from_dims(&[2, 3]),
12102                dtype: DType::F32,
12103            });
12104            let op_id = g.push(Node {
12105                op: Op::ArgMaxDim(1),
12106                inputs: vec![in_id],
12107                shape: Shape::from_dims(&[2]),
12108                dtype: DType::U32,
12109            });
12110            g.set_target_backend(op_id, BackendId::Cpu);
12111            (in_id, op_id)
12112        };
12113        let mut inputs = StorageCache::new();
12114        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12115        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12116        let guard = result_arc.read().unwrap();
12117        assert_eq!(guard.dtype, DType::U32);
12118        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12119            panic!("expected Cpu storage");
12120        };
12121        assert_eq!(c.as_slice::<u32>().unwrap(), &[1u32, 0]);
12122    }
12123
12124    /// E2E: IndexAdd along outer dim — accumulate updates into a
12125    /// rank-1 base tensor at indexed positions.
12126    #[test]
12127    fn pipelined_realize_index_add_simple() {
12128        let base = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
12129        let indices = fuel_memory::from_slice_cpu(&[0u32, 0]);
12130        let src = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
12131        let graph = Arc::new(RwLock::new(Graph::new()));
12132        let (b_id, i_id, s_id, op_id) = {
12133            let mut g = graph.write().unwrap();
12134            let b = g.push(Node {
12135                op: Op::Const,
12136                inputs: vec![],
12137                shape: Shape::from_dims(&[3]),
12138                dtype: DType::F32,
12139            });
12140            let i = g.push(Node {
12141                op: Op::Const,
12142                inputs: vec![],
12143                shape: Shape::from_dims(&[2]),
12144                dtype: DType::U32,
12145            });
12146            let s = g.push(Node {
12147                op: Op::Const,
12148                inputs: vec![],
12149                shape: Shape::from_dims(&[2]),
12150                dtype: DType::F32,
12151            });
12152            let op = g.push(Node {
12153                op: Op::IndexAdd { dim: 0 },
12154                inputs: vec![b, i, s],
12155                shape: Shape::from_dims(&[3]),
12156                dtype: DType::F32,
12157            });
12158            g.set_target_backend(op, BackendId::Cpu);
12159            (b, i, s, op)
12160        };
12161        let mut inputs = StorageCache::new();
12162        inputs.insert(b_id, Arc::new(RwLock::new(base)));
12163        inputs.insert(i_id, Arc::new(RwLock::new(indices)));
12164        inputs.insert(s_id, Arc::new(RwLock::new(src)));
12165        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12166        let guard = result_arc.read().unwrap();
12167        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12168            panic!("expected Cpu storage");
12169        };
12170        // 10 + 1 + 2 = 13; 20 untouched; 30 untouched.
12171        assert_eq!(c.as_slice::<f32>().unwrap(), &[13.0, 20.0, 30.0]);
12172    }
12173
12174    /// E2E: ScatterAdd along outer dim — same-rank indices, base
12175    /// starts as zeros, src adds values at scatter positions.
12176    #[test]
12177    fn pipelined_realize_scatter_add_outer_dim() {
12178        // base [3, 2] = zeros; indices [2, 2] = [[0, 1], [2, 0]];
12179        // src [2, 2] = [[1, 2], [3, 4]]; dim=0
12180        // → out = [[1, 4], [0, 2], [3, 0]]
12181        let base = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
12182        let indices = fuel_memory::from_slice_cpu(&[0u32, 1, 2, 0]);
12183        let src = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
12184        let graph = Arc::new(RwLock::new(Graph::new()));
12185        let (b_id, i_id, s_id, op_id) = {
12186            let mut g = graph.write().unwrap();
12187            let b = g.push(Node {
12188                op: Op::Const,
12189                inputs: vec![],
12190                shape: Shape::from_dims(&[3, 2]),
12191                dtype: DType::F32,
12192            });
12193            let i = g.push(Node {
12194                op: Op::Const,
12195                inputs: vec![],
12196                shape: Shape::from_dims(&[2, 2]),
12197                dtype: DType::U32,
12198            });
12199            let s = g.push(Node {
12200                op: Op::Const,
12201                inputs: vec![],
12202                shape: Shape::from_dims(&[2, 2]),
12203                dtype: DType::F32,
12204            });
12205            let op = g.push(Node {
12206                op: Op::ScatterAdd { dim: 0 },
12207                inputs: vec![b, i, s],
12208                shape: Shape::from_dims(&[3, 2]),
12209                dtype: DType::F32,
12210            });
12211            g.set_target_backend(op, BackendId::Cpu);
12212            (b, i, s, op)
12213        };
12214        let mut inputs = StorageCache::new();
12215        inputs.insert(b_id, Arc::new(RwLock::new(base)));
12216        inputs.insert(i_id, Arc::new(RwLock::new(indices)));
12217        inputs.insert(s_id, Arc::new(RwLock::new(src)));
12218        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12219        let guard = result_arc.read().unwrap();
12220        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12221            panic!("expected Cpu storage");
12222        };
12223        assert_eq!(
12224            c.as_slice::<f32>().unwrap(),
12225            &[1.0, 4.0, 0.0, 2.0, 3.0, 0.0]
12226        );
12227    }
12228
12229    /// E2E: Rope through the pipelined executor. cos=0, sin=1
12230    /// rotates the head_dim halves with sign per the rotate_half
12231    /// convention.
12232    #[test]
12233    fn pipelined_realize_rope_pi_over_two() {
12234        // x [1, 1, 4] = [1, 2, 3, 4]. cos=[0,0,0,0], sin=[1,1,1,1].
12235        // Expected: [-3, -4, 1, 2].
12236        let x = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
12237        let cos = fuel_memory::from_slice_cpu(&[0.0_f32, 0.0, 0.0, 0.0]);
12238        let sin = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
12239        let graph = Arc::new(RwLock::new(Graph::new()));
12240        let (x_id, cos_id, sin_id, r_id) = {
12241            let mut g = graph.write().unwrap();
12242            let x = g.push(Node {
12243                op: Op::Const,
12244                inputs: vec![],
12245                shape: Shape::from_dims(&[1, 1, 4]),
12246                dtype: DType::F32,
12247            });
12248            let c = g.push(Node {
12249                op: Op::Const,
12250                inputs: vec![],
12251                shape: Shape::from_dims(&[1, 4]),
12252                dtype: DType::F32,
12253            });
12254            let s = g.push(Node {
12255                op: Op::Const,
12256                inputs: vec![],
12257                shape: Shape::from_dims(&[1, 4]),
12258                dtype: DType::F32,
12259            });
12260            let r = g.push(Node {
12261                op: Op::Fused(
12262                    fuel_graph::registry::FusedOps::ROPE,
12263                    fuel_graph::registry::FusedOpParams::Rope,
12264                ),
12265                inputs: vec![x, c, s],
12266                shape: Shape::from_dims(&[1, 1, 4]),
12267                dtype: DType::F32,
12268            });
12269            g.set_target_backend(r, BackendId::Cpu);
12270            (x, c, s, r)
12271        };
12272        let mut inputs = StorageCache::new();
12273        inputs.insert(x_id, Arc::new(RwLock::new(x)));
12274        inputs.insert(cos_id, Arc::new(RwLock::new(cos)));
12275        inputs.insert(sin_id, Arc::new(RwLock::new(sin)));
12276        let (result_arc, _) = PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
12277        let guard = result_arc.read().unwrap();
12278        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12279            panic!("expected Cpu storage");
12280        };
12281        assert_eq!(c.as_slice::<f32>().unwrap(), &[-3.0, -4.0, 1.0, 2.0]);
12282    }
12283
12284    /// E2E: Gather along inner dim. Source [2, 4]; indices [2, 3];
12285    /// output [2, 3] = picks from each row by per-row indices.
12286    #[test]
12287    fn pipelined_realize_gather_inner_dim() {
12288        let source =
12289            fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0]);
12290        let indices = fuel_memory::from_slice_cpu(&[0u32, 2, 1, 3, 0, 0]);
12291        let graph = Arc::new(RwLock::new(Graph::new()));
12292        let (src_id, idx_id, g_id) = {
12293            let mut g = graph.write().unwrap();
12294            let s = g.push(Node {
12295                op: Op::Const,
12296                inputs: vec![],
12297                shape: Shape::from_dims(&[2, 4]),
12298                dtype: DType::F32,
12299            });
12300            let i = g.push(Node {
12301                op: Op::Const,
12302                inputs: vec![],
12303                shape: Shape::from_dims(&[2, 3]),
12304                dtype: DType::U32,
12305            });
12306            let g_id = g.push(Node {
12307                op: Op::Gather { dim: 1 },
12308                inputs: vec![s, i],
12309                shape: Shape::from_dims(&[2, 3]),
12310                dtype: DType::F32,
12311            });
12312            g.set_target_backend(g_id, BackendId::Cpu);
12313            (s, i, g_id)
12314        };
12315        let mut inputs = StorageCache::new();
12316        inputs.insert(src_id, Arc::new(RwLock::new(source)));
12317        inputs.insert(idx_id, Arc::new(RwLock::new(indices)));
12318        let (result_arc, _) = PipelinedExecutor::realize(graph, g_id, inputs).expect("realize");
12319        let guard = result_arc.read().unwrap();
12320        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12321            panic!("expected Cpu storage");
12322        };
12323        assert_eq!(
12324            c.as_slice::<f32>().unwrap(),
12325            &[10.0, 30.0, 20.0, 80.0, 50.0, 50.0]
12326        );
12327    }
12328
12329    /// E2E: IndexSelect — embedding-table lookup. Source is a
12330    /// `[vocab=4, d_model=3]` table; indices are token IDs;
12331    /// output is `[seq=3, d_model=3]` with the picked rows.
12332    #[test]
12333    fn pipelined_realize_index_select_embedding_lookup() {
12334        let table = fuel_memory::from_slice_cpu(&[
12335            10.0_f32, 11.0, 12.0, // row 0
12336            20.0, 21.0, 22.0, // row 1
12337            30.0, 31.0, 32.0, // row 2
12338            40.0, 41.0, 42.0, // row 3
12339        ]);
12340        let indices = fuel_memory::from_slice_cpu(&[2u32, 0, 2]);
12341        let graph = Arc::new(RwLock::new(Graph::new()));
12342        let (table_id, idx_id, sel_id) = {
12343            let mut g = graph.write().unwrap();
12344            let t = g.push(Node {
12345                op: Op::Const,
12346                inputs: vec![],
12347                shape: Shape::from_dims(&[4, 3]),
12348                dtype: DType::F32,
12349            });
12350            let i = g.push(Node {
12351                op: Op::Const,
12352                inputs: vec![],
12353                shape: Shape::from_dims(&[3]),
12354                dtype: DType::U32,
12355            });
12356            let s = g.push(Node {
12357                op: Op::IndexSelect { dim: 0 },
12358                inputs: vec![t, i],
12359                shape: Shape::from_dims(&[3, 3]),
12360                dtype: DType::F32,
12361            });
12362            g.set_target_backend(s, BackendId::Cpu);
12363            (t, i, s)
12364        };
12365        let mut inputs = StorageCache::new();
12366        inputs.insert(table_id, Arc::new(RwLock::new(table)));
12367        inputs.insert(idx_id, Arc::new(RwLock::new(indices)));
12368        let (result_arc, result_layout) =
12369            PipelinedExecutor::realize(graph, sel_id, inputs).expect("realize");
12370        assert_eq!(result_layout.shape().dims(), &[3, 3]);
12371        let guard = result_arc.read().unwrap();
12372        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12373            panic!("expected Cpu storage");
12374        };
12375        assert_eq!(
12376            c.as_slice::<f32>().unwrap(),
12377            &[30.0, 31.0, 32.0, 10.0, 11.0, 12.0, 30.0, 31.0, 32.0]
12378        );
12379    }
12380
12381    /// E2E: RmsNormLastDim on a 2-row input. Each row's output
12382    /// has unit RMS up to the eps-induced bias.
12383    #[test]
12384    fn pipelined_realize_rms_norm_last_dim() {
12385        let storage = fuel_memory::from_slice_cpu(&[
12386            3.0_f32, 4.0, // row 0: rms = sqrt(12.5)
12387            6.0, 8.0, // row 1: rms = sqrt(50.0) = 5*sqrt(2)
12388        ]);
12389        let graph = Arc::new(RwLock::new(Graph::new()));
12390        let (in_id, op_id) = {
12391            let mut g = graph.write().unwrap();
12392            let in_id = g.push(Node {
12393                op: Op::Const,
12394                inputs: vec![],
12395                shape: Shape::from_dims(&[2, 2]),
12396                dtype: DType::F32,
12397            });
12398            let op_id = g.push(Node {
12399                op: Op::Fused(
12400                    fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM,
12401                    fuel_graph::registry::FusedOpParams::RmsNormLastDim { eps: 0.0 },
12402                ),
12403                inputs: vec![in_id],
12404                shape: Shape::from_dims(&[2, 2]),
12405                dtype: DType::F32,
12406            });
12407            g.set_target_backend(op_id, BackendId::Cpu);
12408            (in_id, op_id)
12409        };
12410        let mut inputs = StorageCache::new();
12411        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12412        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12413        let guard = result_arc.read().unwrap();
12414        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12415            panic!("expected Cpu storage");
12416        };
12417        let result: &[f32] = c.as_slice().unwrap();
12418        // Row 0: rms = sqrt(12.5). Output = [3, 4] / sqrt(12.5).
12419        let rms0 = (12.5_f32).sqrt();
12420        assert!((result[0] - 3.0 / rms0).abs() < 1e-6);
12421        assert!((result[1] - 4.0 / rms0).abs() < 1e-6);
12422        // Row 1: rms = sqrt(50). Output = [6, 8] / sqrt(50).
12423        let rms1 = (50.0_f32).sqrt();
12424        assert!((result[2] - 6.0 / rms1).abs() < 1e-6);
12425        assert!((result[3] - 8.0 / rms1).abs() < 1e-6);
12426    }
12427
12428    /// E2E: LayerNormLastDim — each row's output has zero mean and
12429    /// unit variance.
12430    #[test]
12431    fn pipelined_realize_layer_norm_last_dim() {
12432        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 10.0, 20.0, 30.0]);
12433        let graph = Arc::new(RwLock::new(Graph::new()));
12434        let (in_id, op_id) = {
12435            let mut g = graph.write().unwrap();
12436            let in_id = g.push(Node {
12437                op: Op::Const,
12438                inputs: vec![],
12439                shape: Shape::from_dims(&[2, 3]),
12440                dtype: DType::F32,
12441            });
12442            let op_id = g.push(Node {
12443                op: Op::Fused(
12444                    fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM,
12445                    fuel_graph::registry::FusedOpParams::LayerNormLastDim { eps: 0.0 },
12446                ),
12447                inputs: vec![in_id],
12448                shape: Shape::from_dims(&[2, 3]),
12449                dtype: DType::F32,
12450            });
12451            g.set_target_backend(op_id, BackendId::Cpu);
12452            (in_id, op_id)
12453        };
12454        let mut inputs = StorageCache::new();
12455        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12456        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12457        let guard = result_arc.read().unwrap();
12458        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12459            panic!("expected Cpu storage");
12460        };
12461        let result: &[f32] = c.as_slice().unwrap();
12462        // Each row should have mean ~0 and var ~1.
12463        for row in 0..2 {
12464            let off = row * 3;
12465            let sum: f32 = result[off..off + 3].iter().sum();
12466            let mean = sum / 3.0;
12467            assert!(mean.abs() < 1e-6, "row {row} mean should be 0, got {mean}");
12468            let var: f32 = result[off..off + 3]
12469                .iter()
12470                .map(|v| (v - mean).powi(2))
12471                .sum::<f32>()
12472                / 3.0;
12473            assert!(
12474                (var - 1.0).abs() < 1e-6,
12475                "row {row} var should be 1, got {var}"
12476            );
12477        }
12478    }
12479
12480    /// E2E: SoftmaxLastDim on a 2-row input. Each row should sum
12481    /// to 1; uniform row gives uniform output.
12482    #[test]
12483    fn pipelined_realize_softmax_last_dim() {
12484        // Row 0: [1, 1, 1, 1] → uniform 0.25 each
12485        // Row 1: [0, 0, 0, 100] → effectively a one-hot at position 3
12486        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 100.0]);
12487        let graph = Arc::new(RwLock::new(Graph::new()));
12488        let (in_id, op_id) = {
12489            let mut g = graph.write().unwrap();
12490            let in_id = g.push(Node {
12491                op: Op::Const,
12492                inputs: vec![],
12493                shape: Shape::from_dims(&[2, 4]),
12494                dtype: DType::F32,
12495            });
12496            let op_id = g.push(Node {
12497                op: Op::Fused(
12498                    fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM,
12499                    fuel_graph::registry::FusedOpParams::SoftmaxLastDim,
12500                ),
12501                inputs: vec![in_id],
12502                shape: Shape::from_dims(&[2, 4]),
12503                dtype: DType::F32,
12504            });
12505            g.set_target_backend(op_id, BackendId::Cpu);
12506            (in_id, op_id)
12507        };
12508        let mut inputs = StorageCache::new();
12509        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12510        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12511        let guard = result_arc.read().unwrap();
12512        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12513            panic!("expected Cpu storage");
12514        };
12515        let result: &[f32] = c.as_slice().unwrap();
12516
12517        // Row 0: uniform 0.25
12518        for v in &result[..4] {
12519            assert!((v - 0.25).abs() < 1e-7);
12520        }
12521        // Row 1: positions 0..3 ≈ 0, position 4 (= last column) ≈ 1
12522        // (e^100 dominates).
12523        for v in &result[4..7] {
12524            assert!(
12525                *v < 1e-30,
12526                "row-1 leading positions should be near 0, got {v}"
12527            );
12528        }
12529        assert!(
12530            result[7] > 0.999,
12531            "row-1 last position should dominate, got {}",
12532            result[7]
12533        );
12534        // Each row sums to 1.
12535        let row0_sum: f32 = result[..4].iter().sum();
12536        let row1_sum: f32 = result[4..].iter().sum();
12537        assert!((row0_sum - 1.0).abs() < 1e-6);
12538        assert!((row1_sum - 1.0).abs() < 1e-6);
12539    }
12540
12541    /// E2E: Concat along inner dim — two [2, 3] tensors → [2, 6].
12542    #[test]
12543    fn pipelined_realize_concat_inner_dim() {
12544        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
12545        let b = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0, 9.0, 10.0, 11.0, 12.0]);
12546        let graph = Arc::new(RwLock::new(Graph::new()));
12547        let (a_id, b_id, c_id) = {
12548            let mut g = graph.write().unwrap();
12549            let a = g.push(Node {
12550                op: Op::Const,
12551                inputs: vec![],
12552                shape: Shape::from_dims(&[2, 3]),
12553                dtype: DType::F32,
12554            });
12555            let b = g.push(Node {
12556                op: Op::Const,
12557                inputs: vec![],
12558                shape: Shape::from_dims(&[2, 3]),
12559                dtype: DType::F32,
12560            });
12561            let c = g.push(Node {
12562                op: Op::Concat { dim: 1 },
12563                inputs: vec![a, b],
12564                shape: Shape::from_dims(&[2, 6]),
12565                dtype: DType::F32,
12566            });
12567            g.set_target_backend(c, BackendId::Cpu);
12568            (a, b, c)
12569        };
12570        let mut inputs = StorageCache::new();
12571        inputs.insert(a_id, Arc::new(RwLock::new(a)));
12572        inputs.insert(b_id, Arc::new(RwLock::new(b)));
12573        let (result_arc, result_layout) =
12574            PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12575        assert_eq!(result_layout.shape().dims(), &[2, 6]);
12576        let guard = result_arc.read().unwrap();
12577        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12578            panic!("expected Cpu storage");
12579        };
12580        assert_eq!(
12581            c.as_slice::<f32>().unwrap(),
12582            &[
12583                1.0, 2.0, 3.0, 7.0, 8.0, 9.0, 4.0, 5.0, 6.0, 10.0, 11.0, 12.0
12584            ]
12585        );
12586    }
12587
12588    /// E2E: Concat with three inputs along outer dim — verifies
12589    /// variable-arity input handling through the executor.
12590    #[test]
12591    fn pipelined_realize_concat_three_inputs_outer() {
12592        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
12593        let b = fuel_memory::from_slice_cpu(&[3.0_f32, 4.0]);
12594        let c = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0]);
12595        let graph = Arc::new(RwLock::new(Graph::new()));
12596        let (a_id, b_id, c_id, cat_id) = {
12597            let mut g = graph.write().unwrap();
12598            let a = g.push(Node {
12599                op: Op::Const,
12600                inputs: vec![],
12601                shape: Shape::from_dims(&[2]),
12602                dtype: DType::F32,
12603            });
12604            let b = g.push(Node {
12605                op: Op::Const,
12606                inputs: vec![],
12607                shape: Shape::from_dims(&[2]),
12608                dtype: DType::F32,
12609            });
12610            let c = g.push(Node {
12611                op: Op::Const,
12612                inputs: vec![],
12613                shape: Shape::from_dims(&[2]),
12614                dtype: DType::F32,
12615            });
12616            let cat = g.push(Node {
12617                op: Op::Concat { dim: 0 },
12618                inputs: vec![a, b, c],
12619                shape: Shape::from_dims(&[6]),
12620                dtype: DType::F32,
12621            });
12622            g.set_target_backend(cat, BackendId::Cpu);
12623            (a, b, c, cat)
12624        };
12625        let mut inputs = StorageCache::new();
12626        inputs.insert(a_id, Arc::new(RwLock::new(a)));
12627        inputs.insert(b_id, Arc::new(RwLock::new(b)));
12628        inputs.insert(c_id, Arc::new(RwLock::new(c)));
12629        let (result_arc, _) = PipelinedExecutor::realize(graph, cat_id, inputs).expect("realize");
12630        let guard = result_arc.read().unwrap();
12631        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12632            panic!("expected Cpu storage");
12633        };
12634        assert_eq!(
12635            c.as_slice::<f32>().unwrap(),
12636            &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
12637        );
12638    }
12639
12640    /// E2E: AddScalar — graph emits Op::AddScalar; the executor
12641    /// maps it to OpKind::Affine with mul=1, add=c.
12642    #[test]
12643    fn pipelined_realize_add_scalar() {
12644        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
12645        let graph = Arc::new(RwLock::new(Graph::new()));
12646        let (in_id, op_id) = {
12647            let mut g = graph.write().unwrap();
12648            let in_id = g.push(Node {
12649                op: Op::Const,
12650                inputs: vec![],
12651                shape: Shape::from_dims(&[3]),
12652                dtype: DType::F32,
12653            });
12654            let op_id = g.push(Node {
12655                op: Op::AddScalar(10.0),
12656                inputs: vec![in_id],
12657                shape: Shape::from_dims(&[3]),
12658                dtype: DType::F32,
12659            });
12660            g.set_target_backend(op_id, BackendId::Cpu);
12661            (in_id, op_id)
12662        };
12663        let mut inputs = StorageCache::new();
12664        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12665        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12666        let guard = result_arc.read().unwrap();
12667        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12668            panic!("expected Cpu storage");
12669        };
12670        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 12.0, 13.0]);
12671    }
12672
12673    /// E2E: Clamp — clamp values to [-2, 2].
12674    #[test]
12675    fn pipelined_realize_clamp() {
12676        let storage = fuel_memory::from_slice_cpu(&[-5.0_f32, 0.5, 100.0]);
12677        let graph = Arc::new(RwLock::new(Graph::new()));
12678        let (in_id, op_id) = {
12679            let mut g = graph.write().unwrap();
12680            let in_id = g.push(Node {
12681                op: Op::Const,
12682                inputs: vec![],
12683                shape: Shape::from_dims(&[3]),
12684                dtype: DType::F32,
12685            });
12686            let op_id = g.push(Node {
12687                op: Op::Clamp {
12688                    min: -2.0,
12689                    max: 2.0,
12690                },
12691                inputs: vec![in_id],
12692                shape: Shape::from_dims(&[3]),
12693                dtype: DType::F32,
12694            });
12695            g.set_target_backend(op_id, BackendId::Cpu);
12696            (in_id, op_id)
12697        };
12698        let mut inputs = StorageCache::new();
12699        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12700        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12701        let guard = result_arc.read().unwrap();
12702        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12703            panic!("expected Cpu storage");
12704        };
12705        assert_eq!(c.as_slice::<f32>().unwrap(), &[-2.0, 0.5, 2.0]);
12706    }
12707
12708    /// E2E: Maximum — elementwise tensor max.
12709    #[test]
12710    fn pipelined_realize_maximum_elementwise() {
12711        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, -3.0]);
12712        let rhs_storage = fuel_memory::from_slice_cpu(&[2.0_f32, 1.0, -1.0]);
12713        let graph = Arc::new(RwLock::new(Graph::new()));
12714        let (lhs_id, rhs_id, op_id) = {
12715            let mut g = graph.write().unwrap();
12716            let lhs = g.push(Node {
12717                op: Op::Const,
12718                inputs: vec![],
12719                shape: Shape::from_dims(&[3]),
12720                dtype: DType::F32,
12721            });
12722            let rhs = g.push(Node {
12723                op: Op::Const,
12724                inputs: vec![],
12725                shape: Shape::from_dims(&[3]),
12726                dtype: DType::F32,
12727            });
12728            let op = g.push(Node {
12729                op: Op::Maximum,
12730                inputs: vec![lhs, rhs],
12731                shape: Shape::from_dims(&[3]),
12732                dtype: DType::F32,
12733            });
12734            g.set_target_backend(op, BackendId::Cpu);
12735            (lhs, rhs, op)
12736        };
12737        let mut inputs = StorageCache::new();
12738        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
12739        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
12740        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12741        let guard = result_arc.read().unwrap();
12742        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12743            panic!("expected Cpu storage");
12744        };
12745        assert_eq!(c.as_slice::<f32>().unwrap(), &[2.0, 5.0, -1.0]);
12746    }
12747
12748    /// E2E: Const + Const + Conv2D — the 2×2 sum-kernel test from
12749    /// byte_kernels driven through the pipelined executor.
12750    #[test]
12751    fn pipelined_realize_conv2d_2x2_sum_kernel() {
12752        // x [1, 1, 3, 3]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
12753        // weight [1, 1, 2, 2]: all-ones
12754        // → out [1, 1, 2, 2]: [[12, 16], [24, 28]]
12755        let x_storage =
12756            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
12757        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
12758
12759        let graph = Arc::new(RwLock::new(Graph::new()));
12760        let (x_id, w_id, c_id) = {
12761            let mut g = graph.write().unwrap();
12762            let x = g.push(Node {
12763                op: Op::Const,
12764                inputs: vec![],
12765                shape: Shape::from_dims(&[1, 1, 3, 3]),
12766                dtype: DType::F32,
12767            });
12768            let w = g.push(Node {
12769                op: Op::Const,
12770                inputs: vec![],
12771                shape: Shape::from_dims(&[1, 1, 2, 2]),
12772                dtype: DType::F32,
12773            });
12774            let c = g.push(Node {
12775                op: Op::Fused(
12776                    fuel_graph::registry::FusedOps::CONV2D,
12777                    fuel_graph::registry::FusedOpParams::Conv2D {
12778                        stride: (1, 1),
12779                        padding: (0, 0),
12780                        groups: 1,
12781                    },
12782                ),
12783                inputs: vec![x, w],
12784                shape: Shape::from_dims(&[1, 1, 2, 2]),
12785                dtype: DType::F32,
12786            });
12787            g.set_target_backend(c, BackendId::Cpu);
12788            (x, w, c)
12789        };
12790        let mut inputs = StorageCache::new();
12791        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12792        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12793
12794        let (result_arc, result_layout) =
12795            PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12796        assert_eq!(result_layout.shape().dims(), &[1, 1, 2, 2]);
12797
12798        let guard = result_arc.read().unwrap();
12799        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12800            panic!("expected Cpu storage");
12801        };
12802        assert_eq!(c.as_slice::<f32>().unwrap(), &[12.0, 16.0, 24.0, 28.0]);
12803    }
12804
12805    /// E2E: Conv2D with bias (3 inputs).
12806    #[test]
12807    fn pipelined_realize_conv2d_with_bias() {
12808        let x_storage =
12809            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
12810        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
12811        let bias_storage = fuel_memory::from_slice_cpu(&[100.0_f32]);
12812
12813        let graph = Arc::new(RwLock::new(Graph::new()));
12814        let (x_id, w_id, b_id, c_id) = {
12815            let mut g = graph.write().unwrap();
12816            let x = g.push(Node {
12817                op: Op::Const,
12818                inputs: vec![],
12819                shape: Shape::from_dims(&[1, 1, 3, 3]),
12820                dtype: DType::F32,
12821            });
12822            let w = g.push(Node {
12823                op: Op::Const,
12824                inputs: vec![],
12825                shape: Shape::from_dims(&[1, 1, 2, 2]),
12826                dtype: DType::F32,
12827            });
12828            let b = g.push(Node {
12829                op: Op::Const,
12830                inputs: vec![],
12831                shape: Shape::from_dims(&[1]),
12832                dtype: DType::F32,
12833            });
12834            let c = g.push(Node {
12835                op: Op::Fused(
12836                    fuel_graph::registry::FusedOps::CONV2D,
12837                    fuel_graph::registry::FusedOpParams::Conv2D {
12838                        stride: (1, 1),
12839                        padding: (0, 0),
12840                        groups: 1,
12841                    },
12842                ),
12843                inputs: vec![x, w, b],
12844                shape: Shape::from_dims(&[1, 1, 2, 2]),
12845                dtype: DType::F32,
12846            });
12847            g.set_target_backend(c, BackendId::Cpu);
12848            (x, w, b, c)
12849        };
12850        let mut inputs = StorageCache::new();
12851        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12852        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12853        inputs.insert(b_id, Arc::new(RwLock::new(bias_storage)));
12854
12855        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12856        let guard = result_arc.read().unwrap();
12857        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12858            panic!("expected Cpu storage");
12859        };
12860        assert_eq!(c.as_slice::<f32>().unwrap(), &[112.0, 116.0, 124.0, 128.0]);
12861    }
12862
12863    /// E2E: Conv2D in F64 — same 2x2 sum-kernel test as F32, on doubles.
12864    #[test]
12865    fn pipelined_realize_conv2d_f64() {
12866        let x_storage =
12867            fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
12868        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f64, 1.0, 1.0, 1.0]);
12869
12870        let graph = Arc::new(RwLock::new(Graph::new()));
12871        let (x_id, w_id, c_id) = {
12872            let mut g = graph.write().unwrap();
12873            let x = g.push(Node {
12874                op: Op::Const,
12875                inputs: vec![],
12876                shape: Shape::from_dims(&[1, 1, 3, 3]),
12877                dtype: DType::F64,
12878            });
12879            let w = g.push(Node {
12880                op: Op::Const,
12881                inputs: vec![],
12882                shape: Shape::from_dims(&[1, 1, 2, 2]),
12883                dtype: DType::F64,
12884            });
12885            let c = g.push(Node {
12886                op: Op::Fused(
12887                    fuel_graph::registry::FusedOps::CONV2D,
12888                    fuel_graph::registry::FusedOpParams::Conv2D {
12889                        stride: (1, 1),
12890                        padding: (0, 0),
12891                        groups: 1,
12892                    },
12893                ),
12894                inputs: vec![x, w],
12895                shape: Shape::from_dims(&[1, 1, 2, 2]),
12896                dtype: DType::F64,
12897            });
12898            g.set_target_backend(c, BackendId::Cpu);
12899            (x, w, c)
12900        };
12901        let mut inputs = StorageCache::new();
12902        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12903        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12904        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12905        let guard = result_arc.read().unwrap();
12906        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12907            panic!("expected Cpu storage");
12908        };
12909        assert_eq!(c.as_slice::<f64>().unwrap(), &[12.0, 16.0, 24.0, 28.0]);
12910    }
12911
12912    /// E2E: Conv2D in BF16 — f32-accumulator path. Tolerant compare.
12913    #[test]
12914    fn pipelined_realize_conv2d_bf16() {
12915        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]
12916            .iter()
12917            .map(|v| half::bf16::from_f32(*v))
12918            .collect();
12919        let w_data: Vec<half::bf16> = [1.0_f32, 1.0, 1.0, 1.0]
12920            .iter()
12921            .map(|v| half::bf16::from_f32(*v))
12922            .collect();
12923        let x_storage = fuel_memory::from_slice_cpu(&x_data);
12924        let w_storage = fuel_memory::from_slice_cpu(&w_data);
12925
12926        let graph = Arc::new(RwLock::new(Graph::new()));
12927        let (x_id, w_id, c_id) = {
12928            let mut g = graph.write().unwrap();
12929            let x = g.push(Node {
12930                op: Op::Const,
12931                inputs: vec![],
12932                shape: Shape::from_dims(&[1, 1, 3, 3]),
12933                dtype: DType::BF16,
12934            });
12935            let w = g.push(Node {
12936                op: Op::Const,
12937                inputs: vec![],
12938                shape: Shape::from_dims(&[1, 1, 2, 2]),
12939                dtype: DType::BF16,
12940            });
12941            let c = g.push(Node {
12942                op: Op::Fused(
12943                    fuel_graph::registry::FusedOps::CONV2D,
12944                    fuel_graph::registry::FusedOpParams::Conv2D {
12945                        stride: (1, 1),
12946                        padding: (0, 0),
12947                        groups: 1,
12948                    },
12949                ),
12950                inputs: vec![x, w],
12951                shape: Shape::from_dims(&[1, 1, 2, 2]),
12952                dtype: DType::BF16,
12953            });
12954            g.set_target_backend(c, BackendId::Cpu);
12955            (x, w, c)
12956        };
12957        let mut inputs = StorageCache::new();
12958        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12959        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12960        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12961        let guard = result_arc.read().unwrap();
12962        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12963            panic!("expected Cpu storage");
12964        };
12965        let got: Vec<f32> = c
12966            .as_slice::<half::bf16>()
12967            .unwrap()
12968            .iter()
12969            .map(|v| v.to_f32())
12970            .collect();
12971        let want = [12.0_f32, 16.0, 24.0, 28.0];
12972        for (g, w) in got.iter().zip(want.iter()) {
12973            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
12974        }
12975    }
12976
12977    /// E2E: Conv2D in F16 — f32-accumulator path. Tolerant compare.
12978    #[test]
12979    fn pipelined_realize_conv2d_f16() {
12980        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]
12981            .iter()
12982            .map(|v| half::f16::from_f32(*v))
12983            .collect();
12984        let w_data: Vec<half::f16> = [1.0_f32, 1.0, 1.0, 1.0]
12985            .iter()
12986            .map(|v| half::f16::from_f32(*v))
12987            .collect();
12988        let x_storage = fuel_memory::from_slice_cpu(&x_data);
12989        let w_storage = fuel_memory::from_slice_cpu(&w_data);
12990
12991        let graph = Arc::new(RwLock::new(Graph::new()));
12992        let (x_id, w_id, c_id) = {
12993            let mut g = graph.write().unwrap();
12994            let x = g.push(Node {
12995                op: Op::Const,
12996                inputs: vec![],
12997                shape: Shape::from_dims(&[1, 1, 3, 3]),
12998                dtype: DType::F16,
12999            });
13000            let w = g.push(Node {
13001                op: Op::Const,
13002                inputs: vec![],
13003                shape: Shape::from_dims(&[1, 1, 2, 2]),
13004                dtype: DType::F16,
13005            });
13006            let c = g.push(Node {
13007                op: Op::Fused(
13008                    fuel_graph::registry::FusedOps::CONV2D,
13009                    fuel_graph::registry::FusedOpParams::Conv2D {
13010                        stride: (1, 1),
13011                        padding: (0, 0),
13012                        groups: 1,
13013                    },
13014                ),
13015                inputs: vec![x, w],
13016                shape: Shape::from_dims(&[1, 1, 2, 2]),
13017                dtype: DType::F16,
13018            });
13019            g.set_target_backend(c, BackendId::Cpu);
13020            (x, w, c)
13021        };
13022        let mut inputs = StorageCache::new();
13023        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
13024        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
13025        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
13026        let guard = result_arc.read().unwrap();
13027        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13028            panic!("expected Cpu storage");
13029        };
13030        let got: Vec<f32> = c
13031            .as_slice::<half::f16>()
13032            .unwrap()
13033            .iter()
13034            .map(|v| v.to_f32())
13035            .collect();
13036        let want = [12.0_f32, 16.0, 24.0, 28.0];
13037        for (g, w) in got.iter().zip(want.iter()) {
13038            assert!((g - w).abs() < 0.05, "got {got:?} want {want:?}");
13039        }
13040    }
13041
13042    /// E2E: Op::PagedAttn — F32, single-head, B=1, Sq=1.
13043    /// Same setup as the FlashAttn smoke test, but the K/V live in a
13044    /// paged cache that we look up via block_table.
13045    /// Layout:
13046    ///   block_size=2, num_blocks=1, max_blocks_per_seq=1.
13047    ///   k_cache shape [1, 2, 1, 2] = num_blocks × block_size × Hkv × D.
13048    ///   k_cache[block 0, slot 0, h 0] = [1, 0]
13049    ///   k_cache[block 0, slot 1, h 0] = [0, 1]
13050    ///   v_cache values: [10, 0] / [0, 10]
13051    ///   block_table[b=0, logical_block 0] = 0 (physical)
13052    ///   context_lens[0] = 2
13053    ///   q[0, 0, 0] = [2, 0]
13054    /// Causal is implicit (q_pos = ctx_len - Sq + sq = 2 - 1 + 0 = 1, both keys admissible).
13055    /// Same softmax math as FlashAttn → ~[8.808, 1.192].
13056    #[test]
13057    fn pipelined_realize_paged_attn_f32() {
13058        let q = fuel_memory::from_slice_cpu(&[2.0_f32, 0.0]);
13059        let k_cache = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13060        let v_cache = fuel_memory::from_slice_cpu(&[10.0_f32, 0.0, 0.0, 10.0]);
13061        let block_table_u32 = fuel_memory::Storage::new(
13062            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
13063                0_u32,
13064            ])),
13065            DType::U32,
13066        );
13067        let context_lens_u32 = fuel_memory::Storage::new(
13068            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
13069                2_u32,
13070            ])),
13071            DType::U32,
13072        );
13073        let graph = Arc::new(RwLock::new(Graph::new()));
13074        let (q_id, kc_id, vc_id, bt_id, cl_id, op_id) = {
13075            let mut g = graph.write().unwrap();
13076            let q = g.push(Node {
13077                op: Op::Const,
13078                inputs: vec![],
13079                shape: Shape::from_dims(&[1, 1, 1, 2]),
13080                dtype: DType::F32,
13081            });
13082            let kc = g.push(Node {
13083                op: Op::Const,
13084                inputs: vec![],
13085                shape: Shape::from_dims(&[1, 2, 1, 2]),
13086                dtype: DType::F32,
13087            });
13088            let vc = g.push(Node {
13089                op: Op::Const,
13090                inputs: vec![],
13091                shape: Shape::from_dims(&[1, 2, 1, 2]),
13092                dtype: DType::F32,
13093            });
13094            let bt = g.push(Node {
13095                op: Op::Const,
13096                inputs: vec![],
13097                shape: Shape::from_dims(&[1, 1]),
13098                dtype: DType::U32,
13099            });
13100            let cl = g.push(Node {
13101                op: Op::Const,
13102                inputs: vec![],
13103                shape: Shape::from_dims(&[1]),
13104                dtype: DType::U32,
13105            });
13106            let op = g.push(Node {
13107                op: Op::Fused(
13108                    fuel_graph::registry::FusedOps::PAGED_ATTN,
13109                    fuel_graph::registry::FusedOpParams::PagedAttn {
13110                        softmax_scale: 1.0,
13111                        block_size: 2,
13112                        softcap: None,
13113                    },
13114                ),
13115                inputs: vec![q, kc, vc, bt, cl],
13116                shape: Shape::from_dims(&[1, 1, 1, 2]),
13117                dtype: DType::F32,
13118            });
13119            g.set_target_backend(op, BackendId::Cpu);
13120            (q, kc, vc, bt, cl, op)
13121        };
13122        let mut inputs = StorageCache::new();
13123        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13124        inputs.insert(kc_id, Arc::new(RwLock::new(k_cache)));
13125        inputs.insert(vc_id, Arc::new(RwLock::new(v_cache)));
13126        inputs.insert(bt_id, Arc::new(RwLock::new(block_table_u32)));
13127        inputs.insert(cl_id, Arc::new(RwLock::new(context_lens_u32)));
13128        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13129        let guard = result_arc.read().unwrap();
13130        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13131            panic!("expected Cpu storage");
13132        };
13133        let r = c.as_slice::<f32>().unwrap();
13134        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
13135        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
13136        assert!(
13137            (r[0] - 10.0 * expected_p0).abs() < 1e-5,
13138            "row[0]: got {} expected {}",
13139            r[0],
13140            10.0 * expected_p0
13141        );
13142        assert!(
13143            (r[1] - 10.0 * expected_p1).abs() < 1e-5,
13144            "row[1]: got {} expected {}",
13145            r[1],
13146            10.0 * expected_p1
13147        );
13148    }
13149
13150    /// E2E: PagedAttn BF16 — same single-row test, tolerant.
13151    #[test]
13152    fn pipelined_realize_paged_attn_bf16() {
13153        let q_v: Vec<half::bf16> = [2.0_f32, 0.0]
13154            .iter()
13155            .map(|x| half::bf16::from_f32(*x))
13156            .collect();
13157        let kc_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0]
13158            .iter()
13159            .map(|x| half::bf16::from_f32(*x))
13160            .collect();
13161        let vc_v: Vec<half::bf16> = [10.0_f32, 0.0, 0.0, 10.0]
13162            .iter()
13163            .map(|x| half::bf16::from_f32(*x))
13164            .collect();
13165        let q = fuel_memory::from_slice_cpu(&q_v);
13166        let k_cache = fuel_memory::from_slice_cpu(&kc_v);
13167        let v_cache = fuel_memory::from_slice_cpu(&vc_v);
13168        let bt = fuel_memory::Storage::new(
13169            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
13170                0_u32,
13171            ])),
13172            DType::U32,
13173        );
13174        let cl = fuel_memory::Storage::new(
13175            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
13176                2_u32,
13177            ])),
13178            DType::U32,
13179        );
13180        let graph = Arc::new(RwLock::new(Graph::new()));
13181        let (q_id, kc_id, vc_id, bt_id, cl_id, op_id) = {
13182            let mut g = graph.write().unwrap();
13183            let q = g.push(Node {
13184                op: Op::Const,
13185                inputs: vec![],
13186                shape: Shape::from_dims(&[1, 1, 1, 2]),
13187                dtype: DType::BF16,
13188            });
13189            let kc = g.push(Node {
13190                op: Op::Const,
13191                inputs: vec![],
13192                shape: Shape::from_dims(&[1, 2, 1, 2]),
13193                dtype: DType::BF16,
13194            });
13195            let vc = g.push(Node {
13196                op: Op::Const,
13197                inputs: vec![],
13198                shape: Shape::from_dims(&[1, 2, 1, 2]),
13199                dtype: DType::BF16,
13200            });
13201            let bt = g.push(Node {
13202                op: Op::Const,
13203                inputs: vec![],
13204                shape: Shape::from_dims(&[1, 1]),
13205                dtype: DType::U32,
13206            });
13207            let cl = g.push(Node {
13208                op: Op::Const,
13209                inputs: vec![],
13210                shape: Shape::from_dims(&[1]),
13211                dtype: DType::U32,
13212            });
13213            let op = g.push(Node {
13214                op: Op::Fused(
13215                    fuel_graph::registry::FusedOps::PAGED_ATTN,
13216                    fuel_graph::registry::FusedOpParams::PagedAttn {
13217                        softmax_scale: 1.0,
13218                        block_size: 2,
13219                        softcap: None,
13220                    },
13221                ),
13222                inputs: vec![q, kc, vc, bt, cl],
13223                shape: Shape::from_dims(&[1, 1, 1, 2]),
13224                dtype: DType::BF16,
13225            });
13226            g.set_target_backend(op, BackendId::Cpu);
13227            (q, kc, vc, bt, cl, op)
13228        };
13229        let mut inputs = StorageCache::new();
13230        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13231        inputs.insert(kc_id, Arc::new(RwLock::new(k_cache)));
13232        inputs.insert(vc_id, Arc::new(RwLock::new(v_cache)));
13233        inputs.insert(bt_id, Arc::new(RwLock::new(bt)));
13234        inputs.insert(cl_id, Arc::new(RwLock::new(cl)));
13235        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13236        let guard = result_arc.read().unwrap();
13237        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13238            panic!("expected Cpu storage");
13239        };
13240        let got: Vec<f32> = c
13241            .as_slice::<half::bf16>()
13242            .unwrap()
13243            .iter()
13244            .map(|v| v.to_f32())
13245            .collect();
13246        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
13247        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
13248        let want = [10.0 * expected_p0, 10.0 * expected_p1];
13249        for (g, w) in got.iter().zip(want.iter()) {
13250            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
13251        }
13252    }
13253
13254    /// E2E: Op::FlashAttn — F32 single-head, single-batch, no mask.
13255    /// q = [[2.0, 0.0]], k = [[1.0, 0.0], [0.0, 1.0]], v = [[10, 0], [0, 10]]
13256    /// scale = 1.0
13257    /// scores = q · kᵀ = [2.0, 0.0]
13258    /// softmax = [e^2/(e^2+1), 1/(e^2+1)] ≈ [0.8808, 0.1192]
13259    /// out = softmax @ v = [10*0.8808, 10*0.1192] ≈ [8.808, 1.192]
13260    #[test]
13261    fn pipelined_realize_flash_attn_f32() {
13262        // [B=1, H=1, S=1or2, D=2]
13263        let q = fuel_memory::from_slice_cpu(&[2.0_f32, 0.0]);
13264        let k = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13265        let v = fuel_memory::from_slice_cpu(&[10.0_f32, 0.0, 0.0, 10.0]);
13266        let graph = Arc::new(RwLock::new(Graph::new()));
13267        let (q_id, k_id, v_id, op_id) = {
13268            let mut g = graph.write().unwrap();
13269            let q = g.push(Node {
13270                op: Op::Const,
13271                inputs: vec![],
13272                shape: Shape::from_dims(&[1, 1, 1, 2]),
13273                dtype: DType::F32,
13274            });
13275            let k = g.push(Node {
13276                op: Op::Const,
13277                inputs: vec![],
13278                shape: Shape::from_dims(&[1, 1, 2, 2]),
13279                dtype: DType::F32,
13280            });
13281            let v = g.push(Node {
13282                op: Op::Const,
13283                inputs: vec![],
13284                shape: Shape::from_dims(&[1, 1, 2, 2]),
13285                dtype: DType::F32,
13286            });
13287            let op = g.push(Node {
13288                op: Op::Fused(
13289                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13290                    fuel_graph::registry::FusedOpParams::FlashAttn {
13291                        softmax_scale: 1.0,
13292                        causal: false,
13293                        window_size_left: None,
13294                        window_size_right: None,
13295                        softcap: None,
13296                        k_len: None,
13297                    },
13298                ),
13299                inputs: vec![q, k, v],
13300                shape: Shape::from_dims(&[1, 1, 1, 2]),
13301                dtype: DType::F32,
13302            });
13303            g.set_target_backend(op, BackendId::Cpu);
13304            (q, k, v, op)
13305        };
13306        let mut inputs = StorageCache::new();
13307        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13308        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13309        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13310        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13311        let guard = result_arc.read().unwrap();
13312        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13313            panic!("expected Cpu storage");
13314        };
13315        let r = c.as_slice::<f32>().unwrap();
13316        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
13317        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
13318        assert!(
13319            (r[0] - 10.0 * expected_p0).abs() < 1e-5,
13320            "row[0]: got {} expected {}",
13321            r[0],
13322            10.0 * expected_p0
13323        );
13324        assert!(
13325            (r[1] - 10.0 * expected_p1).abs() < 1e-5,
13326            "row[1]: got {} expected {}",
13327            r[1],
13328            10.0 * expected_p1
13329        );
13330    }
13331
13332    /// E2E: FlashAttn with causal mask — second query position
13333    /// attends to both keys (positions 0 and 1), first only attends
13334    /// to key 0 (everything beyond is masked).
13335    #[test]
13336    fn pipelined_realize_flash_attn_causal_f32() {
13337        // q [1,1,2,2]: query 0 = [1, 0], query 1 = [0, 1]
13338        // k [1,1,2,2]: keys = [[1, 0], [0, 1]]
13339        // v [1,1,2,2]: values = [[5, 6], [7, 8]]
13340        // softmax_scale=1, causal:
13341        //   query 0: only key 0 admissible → out = v[0] = [5, 6]
13342        //   query 1: both admissible. scores = q1·k = [0, 1]
13343        //            softmax = [1/(e+1), e/(e+1)]
13344        //            out = scores · v = [(5)/(e+1) + 7e/(e+1), 6/(e+1) + 8e/(e+1)]
13345        let q = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13346        let k = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13347        let v = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0, 7.0, 8.0]);
13348        let graph = Arc::new(RwLock::new(Graph::new()));
13349        let (q_id, k_id, v_id, op_id) = {
13350            let mut g = graph.write().unwrap();
13351            let q = g.push(Node {
13352                op: Op::Const,
13353                inputs: vec![],
13354                shape: Shape::from_dims(&[1, 1, 2, 2]),
13355                dtype: DType::F32,
13356            });
13357            let k = g.push(Node {
13358                op: Op::Const,
13359                inputs: vec![],
13360                shape: Shape::from_dims(&[1, 1, 2, 2]),
13361                dtype: DType::F32,
13362            });
13363            let v = g.push(Node {
13364                op: Op::Const,
13365                inputs: vec![],
13366                shape: Shape::from_dims(&[1, 1, 2, 2]),
13367                dtype: DType::F32,
13368            });
13369            let op = g.push(Node {
13370                op: Op::Fused(
13371                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13372                    fuel_graph::registry::FusedOpParams::FlashAttn {
13373                        softmax_scale: 1.0,
13374                        causal: true,
13375                        window_size_left: None,
13376                        window_size_right: None,
13377                        softcap: None,
13378                        k_len: None,
13379                    },
13380                ),
13381                inputs: vec![q, k, v],
13382                shape: Shape::from_dims(&[1, 1, 2, 2]),
13383                dtype: DType::F32,
13384            });
13385            g.set_target_backend(op, BackendId::Cpu);
13386            (q, k, v, op)
13387        };
13388        let mut inputs = StorageCache::new();
13389        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13390        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13391        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13392        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13393        let guard = result_arc.read().unwrap();
13394        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13395            panic!("expected Cpu storage");
13396        };
13397        let r = c.as_slice::<f32>().unwrap();
13398        // Query 0 sees only key 0 → output = v[0]
13399        assert!((r[0] - 5.0).abs() < 1e-5, "got {}", r[0]);
13400        assert!((r[1] - 6.0).abs() < 1e-5, "got {}", r[1]);
13401        // Query 1 sees both. softmax([0, 1]) = [1/(e+1), e/(e+1)]
13402        let denom = (1.0_f32).exp() + 1.0;
13403        let expected_a = 5.0 / denom + 7.0 * (1.0_f32).exp() / denom;
13404        let expected_b = 6.0 / denom + 8.0 * (1.0_f32).exp() / denom;
13405        assert!(
13406            (r[2] - expected_a).abs() < 1e-5,
13407            "row1[0]: got {} expected {}",
13408            r[2],
13409            expected_a
13410        );
13411        assert!(
13412            (r[3] - expected_b).abs() < 1e-5,
13413            "row1[1]: got {} expected {}",
13414            r[3],
13415            expected_b
13416        );
13417    }
13418
13419    /// E2E: FlashAttn over a fixed-**capacity** K/V with a runtime
13420    /// `k_len` resolved through a `SymEnv` (Phase D symbolic extents).
13421    /// Only the first `k_len` rows are attended; trailing "poison" rows
13422    /// in the capacity buffer are ignored, and the causal mask is
13423    /// bottom-right-aligned at offset `k_len - Sq`. This is flash decode
13424    /// over a persistent KV-cache: K/V are `[.., max_seq, ..]` capacity
13425    /// and the live prefix grows per token.
13426    #[test]
13427    fn pipelined_realize_flash_attn_dynamic_k_len() {
13428        use fuel_ir::{DynScalar, SymId};
13429        // q [1,1,2,2]; K/V capacity [1,1,4,2]; bind k_len = 3 so row 3
13430        // (the "poison" row) is never attended.
13431        let q = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13432        let k = fuel_memory::from_slice_cpu(&[
13433            1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0, 100.0,
13434            100.0, // poison row 3 — must be ignored (k_len=3)
13435        ]);
13436        let v = fuel_memory::from_slice_cpu(&[
13437            5.0_f32, 6.0, 7.0, 8.0, 9.0, 10.0, 999.0,
13438            999.0, // poison row 3 — must be ignored
13439        ]);
13440        let sym = SymId(0);
13441        let graph = Arc::new(RwLock::new(Graph::new()));
13442        let (q_id, k_id, v_id, op_id) = {
13443            let mut g = graph.write().unwrap();
13444            let q = g.push(Node {
13445                op: Op::Const,
13446                inputs: vec![],
13447                shape: Shape::from_dims(&[1, 1, 2, 2]),
13448                dtype: DType::F32,
13449            });
13450            let k = g.push(Node {
13451                op: Op::Const,
13452                inputs: vec![],
13453                shape: Shape::from_dims(&[1, 1, 4, 2]),
13454                dtype: DType::F32,
13455            });
13456            let v = g.push(Node {
13457                op: Op::Const,
13458                inputs: vec![],
13459                shape: Shape::from_dims(&[1, 1, 4, 2]),
13460                dtype: DType::F32,
13461            });
13462            let op = g.push(Node {
13463                op: Op::Fused(
13464                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13465                    fuel_graph::registry::FusedOpParams::FlashAttn {
13466                        softmax_scale: 1.0,
13467                        causal: true,
13468                        window_size_left: None,
13469                        window_size_right: None,
13470                        softcap: None,
13471                        k_len: Some(DynScalar::Sym(sym)),
13472                    },
13473                ),
13474                inputs: vec![q, k, v],
13475                shape: Shape::from_dims(&[1, 1, 2, 2]),
13476                dtype: DType::F32,
13477            });
13478            g.set_target_backend(op, BackendId::Cpu);
13479            (q, k, v, op)
13480        };
13481        let mut inputs = StorageCache::new();
13482        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13483        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13484        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13485        let mut env = SymEnv::new();
13486        env.bind(sym, 3).unwrap();
13487        let (result_arc, _) = PipelinedExecutor::realize_with_env(graph, op_id, inputs, env)
13488            .expect("realize_with_env");
13489        let guard = result_arc.read().unwrap();
13490        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13491            panic!("expected Cpu storage");
13492        };
13493        let r = c.as_slice::<f32>().unwrap();
13494        let e = 1.0_f32.exp();
13495        // causal_offset = k_len - Sq = 3 - 2 = 1.
13496        // Query 0 (abs pos 1): keys {0,1}. scores [1,0] → softmax [e,1]/(e+1).
13497        let d0 = e + 1.0;
13498        let e0x = (5.0 * e + 7.0) / d0;
13499        let e0y = (6.0 * e + 8.0) / d0;
13500        // Query 1 (abs pos 2): keys {0,1,2}. scores [0,1,1] → [1,e,e]/(1+2e).
13501        let d1 = 1.0 + 2.0 * e;
13502        let e1x = (5.0 + 7.0 * e + 9.0 * e) / d1;
13503        let e1y = (6.0 + 8.0 * e + 10.0 * e) / d1;
13504        for (got, want) in r.iter().zip([e0x, e0y, e1x, e1y].iter()) {
13505            assert!(
13506                (got - want).abs() < 1e-4,
13507                "flash dyn k_len: got {got}, want {want} (full output {r:?}); \
13508                 a poison-contaminated value means the capacity rows past k_len leaked in",
13509            );
13510        }
13511    }
13512
13513    /// A flash `k_len` symbol unbound in the `SymEnv` surfaces a typed
13514    /// error at realize (never a panic).
13515    #[test]
13516    fn pipelined_realize_flash_attn_dynamic_k_len_unbound_errors() {
13517        use fuel_ir::{DynScalar, SymId};
13518        let q = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13519        let k = fuel_memory::from_slice_cpu(&[0.0_f32; 16]);
13520        let v = fuel_memory::from_slice_cpu(&[0.0_f32; 16]);
13521        let graph = Arc::new(RwLock::new(Graph::new()));
13522        let (q_id, k_id, v_id, op_id) = {
13523            let mut g = graph.write().unwrap();
13524            let q = g.push(Node {
13525                op: Op::Const,
13526                inputs: vec![],
13527                shape: Shape::from_dims(&[1, 1, 2, 2]),
13528                dtype: DType::F32,
13529            });
13530            let k = g.push(Node {
13531                op: Op::Const,
13532                inputs: vec![],
13533                shape: Shape::from_dims(&[1, 1, 4, 2]),
13534                dtype: DType::F32,
13535            });
13536            let v = g.push(Node {
13537                op: Op::Const,
13538                inputs: vec![],
13539                shape: Shape::from_dims(&[1, 1, 4, 2]),
13540                dtype: DType::F32,
13541            });
13542            let op = g.push(Node {
13543                op: Op::Fused(
13544                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13545                    fuel_graph::registry::FusedOpParams::FlashAttn {
13546                        softmax_scale: 1.0,
13547                        causal: true,
13548                        window_size_left: None,
13549                        window_size_right: None,
13550                        softcap: None,
13551                        k_len: Some(DynScalar::Sym(SymId(0))),
13552                    },
13553                ),
13554                inputs: vec![q, k, v],
13555                shape: Shape::from_dims(&[1, 1, 2, 2]),
13556                dtype: DType::F32,
13557            });
13558            g.set_target_backend(op, BackendId::Cpu);
13559            (q, k, v, op)
13560        };
13561        let mut inputs = StorageCache::new();
13562        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13563        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13564        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13565        // Empty env — the k_len symbol is unbound.
13566        let result = PipelinedExecutor::realize_with_env(graph, op_id, inputs, SymEnv::new());
13567        assert!(
13568            result.is_err(),
13569            "unbound flash k_len symbol must surface a typed error"
13570        );
13571    }
13572
13573    /// E2E: FlashAttn BF16 — same single-row test as f32, tolerant.
13574    #[test]
13575    fn pipelined_realize_flash_attn_bf16() {
13576        let q_v: Vec<half::bf16> = [2.0_f32, 0.0]
13577            .iter()
13578            .map(|x| half::bf16::from_f32(*x))
13579            .collect();
13580        let k_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0]
13581            .iter()
13582            .map(|x| half::bf16::from_f32(*x))
13583            .collect();
13584        let v_v: Vec<half::bf16> = [10.0_f32, 0.0, 0.0, 10.0]
13585            .iter()
13586            .map(|x| half::bf16::from_f32(*x))
13587            .collect();
13588        let q = fuel_memory::from_slice_cpu(&q_v);
13589        let k = fuel_memory::from_slice_cpu(&k_v);
13590        let v = fuel_memory::from_slice_cpu(&v_v);
13591        let graph = Arc::new(RwLock::new(Graph::new()));
13592        let (q_id, k_id, v_id, op_id) = {
13593            let mut g = graph.write().unwrap();
13594            let q = g.push(Node {
13595                op: Op::Const,
13596                inputs: vec![],
13597                shape: Shape::from_dims(&[1, 1, 1, 2]),
13598                dtype: DType::BF16,
13599            });
13600            let k = g.push(Node {
13601                op: Op::Const,
13602                inputs: vec![],
13603                shape: Shape::from_dims(&[1, 1, 2, 2]),
13604                dtype: DType::BF16,
13605            });
13606            let v = g.push(Node {
13607                op: Op::Const,
13608                inputs: vec![],
13609                shape: Shape::from_dims(&[1, 1, 2, 2]),
13610                dtype: DType::BF16,
13611            });
13612            let op = g.push(Node {
13613                op: Op::Fused(
13614                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13615                    fuel_graph::registry::FusedOpParams::FlashAttn {
13616                        softmax_scale: 1.0,
13617                        causal: false,
13618                        window_size_left: None,
13619                        window_size_right: None,
13620                        softcap: None,
13621                        k_len: None,
13622                    },
13623                ),
13624                inputs: vec![q, k, v],
13625                shape: Shape::from_dims(&[1, 1, 1, 2]),
13626                dtype: DType::BF16,
13627            });
13628            g.set_target_backend(op, BackendId::Cpu);
13629            (q, k, v, op)
13630        };
13631        let mut inputs = StorageCache::new();
13632        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13633        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13634        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13635        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13636        let guard = result_arc.read().unwrap();
13637        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13638            panic!("expected Cpu storage");
13639        };
13640        let got: Vec<f32> = c
13641            .as_slice::<half::bf16>()
13642            .unwrap()
13643            .iter()
13644            .map(|v| v.to_f32())
13645            .collect();
13646        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
13647        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
13648        let want = [10.0 * expected_p0, 10.0 * expected_p1];
13649        for (g, w) in got.iter().zip(want.iter()) {
13650            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
13651        }
13652    }
13653
13654    /// E2E: Op::FusedLinear — F32. a[1,2,3] @ b[1,3,2] + bias[2].
13655    /// a = [[[1,2,3],[4,5,6]]], b = [[[1,0],[0,1],[1,1]]], bias=[10,20]
13656    /// matmul = [[1+0+3, 0+2+3], [4+0+6, 0+5+6]] = [[4, 5], [10, 11]]
13657    /// + bias = [[14, 25], [20, 31]]
13658    #[test]
13659    fn pipelined_realize_fused_linear_f32() {
13660        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
13661        let b = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0]);
13662        let bias = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
13663        let graph = Arc::new(RwLock::new(Graph::new()));
13664        let (a_id, b_id, bias_id, op_id) = {
13665            let mut g = graph.write().unwrap();
13666            let a = g.push(Node {
13667                op: Op::Const,
13668                inputs: vec![],
13669                shape: Shape::from_dims(&[1, 2, 3]),
13670                dtype: DType::F32,
13671            });
13672            let b = g.push(Node {
13673                op: Op::Const,
13674                inputs: vec![],
13675                shape: Shape::from_dims(&[1, 3, 2]),
13676                dtype: DType::F32,
13677            });
13678            let bias = g.push(Node {
13679                op: Op::Const,
13680                inputs: vec![],
13681                shape: Shape::from_dims(&[2]),
13682                dtype: DType::F32,
13683            });
13684            let op = g.push(Node {
13685                op: Op::Fused(
13686                    fuel_graph::registry::FusedOps::FUSED_LINEAR,
13687                    fuel_graph::registry::FusedOpParams::FusedLinear,
13688                ),
13689                inputs: vec![a, b, bias],
13690                shape: Shape::from_dims(&[1, 2, 2]),
13691                dtype: DType::F32,
13692            });
13693            g.set_target_backend(op, BackendId::Cpu);
13694            (a, b, bias, op)
13695        };
13696        let mut inputs = StorageCache::new();
13697        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13698        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13699        inputs.insert(bias_id, Arc::new(RwLock::new(bias)));
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(), &[14.0, 25.0, 20.0, 31.0]);
13706    }
13707
13708    /// E2E: FusedLinear F64 — same shape test on doubles.
13709    #[test]
13710    fn pipelined_realize_fused_linear_f64() {
13711        let a = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
13712        let b = fuel_memory::from_slice_cpu(&[1.0_f64, 0.0, 0.0, 1.0, 1.0, 1.0]);
13713        let bias = fuel_memory::from_slice_cpu(&[10.0_f64, 20.0]);
13714        let graph = Arc::new(RwLock::new(Graph::new()));
13715        let (a_id, b_id, bias_id, op_id) = {
13716            let mut g = graph.write().unwrap();
13717            let a = g.push(Node {
13718                op: Op::Const,
13719                inputs: vec![],
13720                shape: Shape::from_dims(&[1, 2, 3]),
13721                dtype: DType::F64,
13722            });
13723            let b = g.push(Node {
13724                op: Op::Const,
13725                inputs: vec![],
13726                shape: Shape::from_dims(&[1, 3, 2]),
13727                dtype: DType::F64,
13728            });
13729            let bias = g.push(Node {
13730                op: Op::Const,
13731                inputs: vec![],
13732                shape: Shape::from_dims(&[2]),
13733                dtype: DType::F64,
13734            });
13735            let op = g.push(Node {
13736                op: Op::Fused(
13737                    fuel_graph::registry::FusedOps::FUSED_LINEAR,
13738                    fuel_graph::registry::FusedOpParams::FusedLinear,
13739                ),
13740                inputs: vec![a, b, bias],
13741                shape: Shape::from_dims(&[1, 2, 2]),
13742                dtype: DType::F64,
13743            });
13744            g.set_target_backend(op, BackendId::Cpu);
13745            (a, b, bias, op)
13746        };
13747        let mut inputs = StorageCache::new();
13748        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13749        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13750        inputs.insert(bias_id, Arc::new(RwLock::new(bias)));
13751        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13752        let guard = result_arc.read().unwrap();
13753        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13754            panic!("expected Cpu storage");
13755        };
13756        assert_eq!(c.as_slice::<f64>().unwrap(), &[14.0, 25.0, 20.0, 31.0]);
13757    }
13758
13759    /// E2E (row 172 item 1): RowScaledMatMul F32 on CPU. a [1,2,3] @ b [1,3,2]
13760    /// = [[4, 5], [10, 11]]... computed by hand below; each row is scaled by its
13761    /// own entry of row_scale [1,2,1] = [2, 10]. A per-column or unscaled result
13762    /// would differ, so this discriminates the epilogue.
13763    #[test]
13764    fn pipelined_realize_row_scaled_matmul_f32() {
13765        // a rows: [1,2,3], [4,5,6]; b = [[1,0],[0,1],[1,1]].
13766        // a@b = [[1+3, 2+3], [4+6, 5+6]] = [[4, 5], [10, 11]].
13767        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
13768        let b = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0]);
13769        let scale = fuel_memory::from_slice_cpu(&[2.0_f32, 10.0]);
13770        let graph = Arc::new(RwLock::new(Graph::new()));
13771        let (a_id, b_id, s_id, op_id) = {
13772            let mut g = graph.write().unwrap();
13773            let mut konst = |dims: &[usize]| {
13774                g.push(Node {
13775                    op: Op::Const,
13776                    inputs: vec![],
13777                    shape: Shape::from_dims(dims),
13778                    dtype: DType::F32,
13779                })
13780            };
13781            let (a, b, s) = (konst(&[1, 2, 3]), konst(&[1, 3, 2]), konst(&[1, 2, 1]));
13782            let op = g.push(Node {
13783                op: Op::Fused(
13784                    fuel_graph::registry::FusedOps::ROW_SCALED_MATMUL,
13785                    fuel_graph::registry::FusedOpParams::RowScaledMatMul,
13786                ),
13787                inputs: vec![a, b, s],
13788                shape: Shape::from_dims(&[1, 2, 2]),
13789                dtype: DType::F32,
13790            });
13791            g.set_target_backend(op, BackendId::Cpu);
13792            (a, b, s, op)
13793        };
13794        let mut inputs = StorageCache::new();
13795        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13796        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13797        inputs.insert(s_id, Arc::new(RwLock::new(scale)));
13798        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13799        let guard = result_arc.read().unwrap();
13800        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13801            panic!("expected Cpu storage");
13802        };
13803        assert_eq!(c.as_slice::<f32>().unwrap(), &[8.0, 10.0, 100.0, 110.0]);
13804    }
13805
13806    /// E2E: FusedLinear BF16 — tolerant compare.
13807    #[test]
13808    fn pipelined_realize_fused_linear_bf16() {
13809        let a_v: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]
13810            .iter()
13811            .map(|x| half::bf16::from_f32(*x))
13812            .collect();
13813        let b_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0]
13814            .iter()
13815            .map(|x| half::bf16::from_f32(*x))
13816            .collect();
13817        let bias_v: Vec<half::bf16> = [10.0_f32, 20.0]
13818            .iter()
13819            .map(|x| half::bf16::from_f32(*x))
13820            .collect();
13821        let a = fuel_memory::from_slice_cpu(&a_v);
13822        let b = fuel_memory::from_slice_cpu(&b_v);
13823        let bias = fuel_memory::from_slice_cpu(&bias_v);
13824        let graph = Arc::new(RwLock::new(Graph::new()));
13825        let (a_id, b_id, bias_id, op_id) = {
13826            let mut g = graph.write().unwrap();
13827            let a = g.push(Node {
13828                op: Op::Const,
13829                inputs: vec![],
13830                shape: Shape::from_dims(&[1, 2, 3]),
13831                dtype: DType::BF16,
13832            });
13833            let b = g.push(Node {
13834                op: Op::Const,
13835                inputs: vec![],
13836                shape: Shape::from_dims(&[1, 3, 2]),
13837                dtype: DType::BF16,
13838            });
13839            let bias = g.push(Node {
13840                op: Op::Const,
13841                inputs: vec![],
13842                shape: Shape::from_dims(&[2]),
13843                dtype: DType::BF16,
13844            });
13845            let op = g.push(Node {
13846                op: Op::Fused(
13847                    fuel_graph::registry::FusedOps::FUSED_LINEAR,
13848                    fuel_graph::registry::FusedOpParams::FusedLinear,
13849                ),
13850                inputs: vec![a, b, bias],
13851                shape: Shape::from_dims(&[1, 2, 2]),
13852                dtype: DType::BF16,
13853            });
13854            g.set_target_backend(op, BackendId::Cpu);
13855            (a, b, bias, op)
13856        };
13857        let mut inputs = StorageCache::new();
13858        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13859        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13860        inputs.insert(bias_id, Arc::new(RwLock::new(bias)));
13861        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13862        let guard = result_arc.read().unwrap();
13863        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13864            panic!("expected Cpu storage");
13865        };
13866        let got: Vec<f32> = c
13867            .as_slice::<half::bf16>()
13868            .unwrap()
13869            .iter()
13870            .map(|v| v.to_f32())
13871            .collect();
13872        let want = [14.0_f32, 25.0, 20.0, 31.0];
13873        for (g, w) in got.iter().zip(want.iter()) {
13874            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
13875        }
13876    }
13877
13878    /// E2E: Op::ReduceSumTo — sum the leading axis of a [2,3] tensor.
13879    /// Input [[1,2,3],[4,5,6]] → output [5,7,9].
13880    #[test]
13881    fn pipelined_realize_reduce_sum_to_f32_drops_leading_axis() {
13882        let v = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
13883        let graph = Arc::new(RwLock::new(Graph::new()));
13884        let (in_id, op_id) = {
13885            let mut g = graph.write().unwrap();
13886            let in_id = g.push(Node {
13887                op: Op::Const,
13888                inputs: vec![],
13889                shape: Shape::from_dims(&[2, 3]),
13890                dtype: DType::F32,
13891            });
13892            let op_id = g.push(Node {
13893                op: Op::ReduceSumTo(Shape::from_dims(&[3])),
13894                inputs: vec![in_id],
13895                shape: Shape::from_dims(&[3]),
13896                dtype: DType::F32,
13897            });
13898            g.set_target_backend(op_id, BackendId::Cpu);
13899            (in_id, op_id)
13900        };
13901        let mut inputs = StorageCache::new();
13902        inputs.insert(in_id, Arc::new(RwLock::new(v)));
13903        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13904        let guard = result_arc.read().unwrap();
13905        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13906            panic!("expected Cpu storage");
13907        };
13908        assert_eq!(c.as_slice::<f32>().unwrap(), &[5.0, 7.0, 9.0]);
13909    }
13910
13911    /// E2E: Op::ReduceSumTo — keep-dim with 1 in the middle.
13912    /// Input [2,3,4] → [2,1,4] sums along dim 1.
13913    #[test]
13914    fn pipelined_realize_reduce_sum_to_f32_keepdim_middle() {
13915        // [2,3,4]: layer 0 = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
13916        //          layer 1 = [[13..16],[17..20],[21..24]]
13917        let mut v: Vec<f32> = (1..=24).map(|x| x as f32).collect();
13918        let _ = &mut v;
13919        let s = fuel_memory::from_slice_cpu(&v);
13920        let graph = Arc::new(RwLock::new(Graph::new()));
13921        let (in_id, op_id) = {
13922            let mut g = graph.write().unwrap();
13923            let in_id = g.push(Node {
13924                op: Op::Const,
13925                inputs: vec![],
13926                shape: Shape::from_dims(&[2, 3, 4]),
13927                dtype: DType::F32,
13928            });
13929            let op_id = g.push(Node {
13930                op: Op::ReduceSumTo(Shape::from_dims(&[2, 1, 4])),
13931                inputs: vec![in_id],
13932                shape: Shape::from_dims(&[2, 1, 4]),
13933                dtype: DType::F32,
13934            });
13935            g.set_target_backend(op_id, BackendId::Cpu);
13936            (in_id, op_id)
13937        };
13938        let mut inputs = StorageCache::new();
13939        inputs.insert(in_id, Arc::new(RwLock::new(s)));
13940        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13941        let guard = result_arc.read().unwrap();
13942        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13943            panic!("expected Cpu storage");
13944        };
13945        // layer0 dim1-sum: col j = 1+5+9, 2+6+10, 3+7+11, 4+8+12 = [15,18,21,24]
13946        // layer1 dim1-sum: col j = 13+17+21, 14+18+22, 15+19+23, 16+20+24 = [51,54,57,60]
13947        assert_eq!(
13948            c.as_slice::<f32>().unwrap(),
13949            &[15.0, 18.0, 21.0, 24.0, 51.0, 54.0, 57.0, 60.0],
13950        );
13951    }
13952
13953    /// E2E: ReduceSumTo F64 — same drop-leading-axis test on doubles.
13954    #[test]
13955    fn pipelined_realize_reduce_sum_to_f64() {
13956        let v = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
13957        let graph = Arc::new(RwLock::new(Graph::new()));
13958        let (in_id, op_id) = {
13959            let mut g = graph.write().unwrap();
13960            let in_id = g.push(Node {
13961                op: Op::Const,
13962                inputs: vec![],
13963                shape: Shape::from_dims(&[2, 3]),
13964                dtype: DType::F64,
13965            });
13966            let op_id = g.push(Node {
13967                op: Op::ReduceSumTo(Shape::from_dims(&[3])),
13968                inputs: vec![in_id],
13969                shape: Shape::from_dims(&[3]),
13970                dtype: DType::F64,
13971            });
13972            g.set_target_backend(op_id, BackendId::Cpu);
13973            (in_id, op_id)
13974        };
13975        let mut inputs = StorageCache::new();
13976        inputs.insert(in_id, Arc::new(RwLock::new(v)));
13977        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13978        let guard = result_arc.read().unwrap();
13979        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13980            panic!("expected Cpu storage");
13981        };
13982        assert_eq!(c.as_slice::<f64>().unwrap(), &[5.0, 7.0, 9.0]);
13983    }
13984
13985    /// E2E: Op::ReduceMaxTo F32 — drop the leading axis with max-reduce.
13986    #[test]
13987    fn pipelined_realize_reduce_max_to_f32_drops_leading_axis() {
13988        // Input [2,3]: row 0 = [1, 7, 3], row 1 = [4, 2, 6]. Max along
13989        // dim 0: [4, 7, 6].
13990        let v = fuel_memory::from_slice_cpu(&[1.0_f32, 7.0, 3.0, 4.0, 2.0, 6.0]);
13991        let graph = Arc::new(RwLock::new(Graph::new()));
13992        let (in_id, op_id) = {
13993            let mut g = graph.write().unwrap();
13994            let in_id = g.push(Node {
13995                op: Op::Const,
13996                inputs: vec![],
13997                shape: Shape::from_dims(&[2, 3]),
13998                dtype: DType::F32,
13999            });
14000            let op_id = g.push(Node {
14001                op: Op::ReduceMaxTo(Shape::from_dims(&[3])),
14002                inputs: vec![in_id],
14003                shape: Shape::from_dims(&[3]),
14004                dtype: DType::F32,
14005            });
14006            g.set_target_backend(op_id, BackendId::Cpu);
14007            (in_id, op_id)
14008        };
14009        let mut inputs = StorageCache::new();
14010        inputs.insert(in_id, Arc::new(RwLock::new(v)));
14011        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14012        let guard = result_arc.read().unwrap();
14013        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14014            panic!("expected Cpu storage");
14015        };
14016        assert_eq!(c.as_slice::<f32>().unwrap(), &[4.0, 7.0, 6.0]);
14017    }
14018
14019    /// E2E: Op::ReduceMaxTo F32 — keep-dim with 1 in the trailing axis.
14020    /// Mirrors the SoftmaxLastDim lowering's max-side shape: input
14021    /// [..., last] → [..., 1].
14022    #[test]
14023    fn pipelined_realize_reduce_max_to_f32_keepdim_trailing() {
14024        // Input [2, 3]: row maxes = [3, 6].
14025        let v = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14026        let graph = Arc::new(RwLock::new(Graph::new()));
14027        let (in_id, op_id) = {
14028            let mut g = graph.write().unwrap();
14029            let in_id = g.push(Node {
14030                op: Op::Const,
14031                inputs: vec![],
14032                shape: Shape::from_dims(&[2, 3]),
14033                dtype: DType::F32,
14034            });
14035            let op_id = g.push(Node {
14036                op: Op::ReduceMaxTo(Shape::from_dims(&[2, 1])),
14037                inputs: vec![in_id],
14038                shape: Shape::from_dims(&[2, 1]),
14039                dtype: DType::F32,
14040            });
14041            g.set_target_backend(op_id, BackendId::Cpu);
14042            (in_id, op_id)
14043        };
14044        let mut inputs = StorageCache::new();
14045        inputs.insert(in_id, Arc::new(RwLock::new(v)));
14046        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14047        let guard = result_arc.read().unwrap();
14048        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14049            panic!("expected Cpu storage");
14050        };
14051        assert_eq!(c.as_slice::<f32>().unwrap(), &[3.0, 6.0]);
14052    }
14053
14054    /// E2E: ReduceSumTo BF16 — tolerant compare via f32-acc.
14055    #[test]
14056    fn pipelined_realize_reduce_sum_to_bf16() {
14057        let v: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]
14058            .iter()
14059            .map(|x| half::bf16::from_f32(*x))
14060            .collect();
14061        let s = fuel_memory::from_slice_cpu(&v);
14062        let graph = Arc::new(RwLock::new(Graph::new()));
14063        let (in_id, op_id) = {
14064            let mut g = graph.write().unwrap();
14065            let in_id = g.push(Node {
14066                op: Op::Const,
14067                inputs: vec![],
14068                shape: Shape::from_dims(&[2, 3]),
14069                dtype: DType::BF16,
14070            });
14071            let op_id = g.push(Node {
14072                op: Op::ReduceSumTo(Shape::from_dims(&[3])),
14073                inputs: vec![in_id],
14074                shape: Shape::from_dims(&[3]),
14075                dtype: DType::BF16,
14076            });
14077            g.set_target_backend(op_id, BackendId::Cpu);
14078            (in_id, op_id)
14079        };
14080        let mut inputs = StorageCache::new();
14081        inputs.insert(in_id, Arc::new(RwLock::new(s)));
14082        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14083        let guard = result_arc.read().unwrap();
14084        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14085            panic!("expected Cpu storage");
14086        };
14087        let got: Vec<f32> = c
14088            .as_slice::<half::bf16>()
14089            .unwrap()
14090            .iter()
14091            .map(|v| v.to_f32())
14092            .collect();
14093        let want = [5.0_f32, 7.0, 9.0];
14094        for (g, w) in got.iter().zip(want.iter()) {
14095            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
14096        }
14097    }
14098
14099    /// E2E: Op::ConvTranspose2D — F32 spread test.
14100    /// x = [[1, 2], [3, 4]] shape [1,1,2,2], all-ones kernel
14101    /// shape [1,1,2,2], stride=1, padding=0, dilation=1, no bias.
14102    /// Expected output (3x3):
14103    ///   [[1,  3, 2],
14104    ///    [4, 10, 6],
14105    ///    [3,  7, 4]]
14106    #[test]
14107    fn pipelined_realize_conv_transpose2d_f32() {
14108        let x_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
14109        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
14110        let graph = Arc::new(RwLock::new(Graph::new()));
14111        let (x_id, w_id, c_id) = {
14112            let mut g = graph.write().unwrap();
14113            let x = g.push(Node {
14114                op: Op::Const,
14115                inputs: vec![],
14116                shape: Shape::from_dims(&[1, 1, 2, 2]),
14117                dtype: DType::F32,
14118            });
14119            let w = g.push(Node {
14120                op: Op::Const,
14121                inputs: vec![],
14122                shape: Shape::from_dims(&[1, 1, 2, 2]),
14123                dtype: DType::F32,
14124            });
14125            let c = g.push(Node {
14126                op: Op::Fused(
14127                    fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D,
14128                    fuel_graph::registry::FusedOpParams::ConvTranspose2D {
14129                        stride: (1, 1),
14130                        padding: (0, 0),
14131                        output_padding: (0, 0),
14132                        dilation: (1, 1),
14133                        groups: 1,
14134                    },
14135                ),
14136                inputs: vec![x, w],
14137                shape: Shape::from_dims(&[1, 1, 3, 3]),
14138                dtype: DType::F32,
14139            });
14140            g.set_target_backend(c, BackendId::Cpu);
14141            (x, w, c)
14142        };
14143        let mut inputs = StorageCache::new();
14144        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
14145        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
14146        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
14147        let guard = result_arc.read().unwrap();
14148        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14149            panic!("expected Cpu storage");
14150        };
14151        assert_eq!(
14152            c.as_slice::<f32>().unwrap(),
14153            &[1.0, 3.0, 2.0, 4.0, 10.0, 6.0, 3.0, 7.0, 4.0],
14154        );
14155    }
14156
14157    /// E2E: ConvTranspose2D F64 — same shape test.
14158    #[test]
14159    fn pipelined_realize_conv_transpose2d_f64() {
14160        let x_storage = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0]);
14161        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f64, 1.0, 1.0, 1.0]);
14162        let graph = Arc::new(RwLock::new(Graph::new()));
14163        let (x_id, w_id, c_id) = {
14164            let mut g = graph.write().unwrap();
14165            let x = g.push(Node {
14166                op: Op::Const,
14167                inputs: vec![],
14168                shape: Shape::from_dims(&[1, 1, 2, 2]),
14169                dtype: DType::F64,
14170            });
14171            let w = g.push(Node {
14172                op: Op::Const,
14173                inputs: vec![],
14174                shape: Shape::from_dims(&[1, 1, 2, 2]),
14175                dtype: DType::F64,
14176            });
14177            let c = g.push(Node {
14178                op: Op::Fused(
14179                    fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D,
14180                    fuel_graph::registry::FusedOpParams::ConvTranspose2D {
14181                        stride: (1, 1),
14182                        padding: (0, 0),
14183                        output_padding: (0, 0),
14184                        dilation: (1, 1),
14185                        groups: 1,
14186                    },
14187                ),
14188                inputs: vec![x, w],
14189                shape: Shape::from_dims(&[1, 1, 3, 3]),
14190                dtype: DType::F64,
14191            });
14192            g.set_target_backend(c, BackendId::Cpu);
14193            (x, w, c)
14194        };
14195        let mut inputs = StorageCache::new();
14196        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
14197        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
14198        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
14199        let guard = result_arc.read().unwrap();
14200        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14201            panic!("expected Cpu storage");
14202        };
14203        assert_eq!(
14204            c.as_slice::<f64>().unwrap(),
14205            &[1.0, 3.0, 2.0, 4.0, 10.0, 6.0, 3.0, 7.0, 4.0],
14206        );
14207    }
14208
14209    /// E2E: ConvTranspose2D BF16 — tolerant compare via f32-acc.
14210    #[test]
14211    fn pipelined_realize_conv_transpose2d_bf16() {
14212        let x: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0]
14213            .iter()
14214            .map(|v| half::bf16::from_f32(*v))
14215            .collect();
14216        let w: Vec<half::bf16> = [1.0_f32, 1.0, 1.0, 1.0]
14217            .iter()
14218            .map(|v| half::bf16::from_f32(*v))
14219            .collect();
14220        let x_storage = fuel_memory::from_slice_cpu(&x);
14221        let w_storage = fuel_memory::from_slice_cpu(&w);
14222        let graph = Arc::new(RwLock::new(Graph::new()));
14223        let (x_id, w_id, c_id) = {
14224            let mut g = graph.write().unwrap();
14225            let x = g.push(Node {
14226                op: Op::Const,
14227                inputs: vec![],
14228                shape: Shape::from_dims(&[1, 1, 2, 2]),
14229                dtype: DType::BF16,
14230            });
14231            let w = g.push(Node {
14232                op: Op::Const,
14233                inputs: vec![],
14234                shape: Shape::from_dims(&[1, 1, 2, 2]),
14235                dtype: DType::BF16,
14236            });
14237            let c = g.push(Node {
14238                op: Op::Fused(
14239                    fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D,
14240                    fuel_graph::registry::FusedOpParams::ConvTranspose2D {
14241                        stride: (1, 1),
14242                        padding: (0, 0),
14243                        output_padding: (0, 0),
14244                        dilation: (1, 1),
14245                        groups: 1,
14246                    },
14247                ),
14248                inputs: vec![x, w],
14249                shape: Shape::from_dims(&[1, 1, 3, 3]),
14250                dtype: DType::BF16,
14251            });
14252            g.set_target_backend(c, BackendId::Cpu);
14253            (x, w, c)
14254        };
14255        let mut inputs = StorageCache::new();
14256        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
14257        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
14258        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
14259        let guard = result_arc.read().unwrap();
14260        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14261            panic!("expected Cpu storage");
14262        };
14263        let got: Vec<f32> = c
14264            .as_slice::<half::bf16>()
14265            .unwrap()
14266            .iter()
14267            .map(|v| v.to_f32())
14268            .collect();
14269        let want = [1.0_f32, 3.0, 2.0, 4.0, 10.0, 6.0, 3.0, 7.0, 4.0];
14270        for (g, w) in got.iter().zip(want.iter()) {
14271            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
14272        }
14273    }
14274
14275    /// E2E: GQA-style matmul through the pipelined executor.
14276    /// lhs has 4 batch heads, rhs has 2; each rhs head is shared
14277    /// by 2 lhs heads. Output's batch dim follows lhs (4 heads).
14278    #[test]
14279    fn pipelined_realize_matmul_gqa() {
14280        // lhs [4, 1, 2]: heads 0..3 are [[1,2]], [[3,4]], [[5,6]], [[7,8]]
14281        // rhs [2, 2, 1]: heads 0,1 are [[1],[0]], [[0],[1]]
14282        // Expected out [4, 1, 1]: [[1]], [[3]], [[6]], [[8]]
14283        let lhs_storage =
14284            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]);
14285        let rhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
14286
14287        let graph = Arc::new(RwLock::new(Graph::new()));
14288        let (lhs_id, rhs_id, mm_id) = {
14289            let mut g = graph.write().unwrap();
14290            let lhs = g.push(Node {
14291                op: Op::Const,
14292                inputs: vec![],
14293                shape: Shape::from_dims(&[4, 1, 2]),
14294                dtype: DType::F32,
14295            });
14296            let rhs = g.push(Node {
14297                op: Op::Const,
14298                inputs: vec![],
14299                shape: Shape::from_dims(&[2, 2, 1]),
14300                dtype: DType::F32,
14301            });
14302            let mm = g.push(Node {
14303                op: Op::MatMul,
14304                inputs: vec![lhs, rhs],
14305                shape: Shape::from_dims(&[4, 1, 1]),
14306                dtype: DType::F32,
14307            });
14308            g.set_target_backend(mm, BackendId::Cpu);
14309            (lhs, rhs, mm)
14310        };
14311        let mut inputs = StorageCache::new();
14312        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
14313        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
14314
14315        let (result_arc, result_layout) =
14316            PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
14317        assert_eq!(result_layout.shape().dims(), &[4, 1, 1]);
14318
14319        let guard = result_arc.read().unwrap();
14320        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14321            panic!("expected Cpu storage");
14322        };
14323        assert_eq!(c.as_slice::<f32>().unwrap(), &[1.0, 3.0, 6.0, 8.0]);
14324    }
14325
14326    /// E2E: matmul with a transposed rhs — proves stage 3+4
14327    /// integration carries through the matmul path. The transpose
14328    /// is metadata-only; auto-Contiguize materializes the strided
14329    /// rhs before the matmul kernel sees it.
14330    #[test]
14331    fn pipelined_realize_matmul_with_transposed_rhs() {
14332        // lhs [[1, 2], [3, 4]], rhs original [[5, 6], [7, 8]]
14333        // rhs.T = [[5, 7], [6, 8]]
14334        // lhs @ rhs.T = [[1*5+2*6, 1*7+2*8], [3*5+4*6, 3*7+4*8]]
14335        //             = [[17, 23], [39, 53]]
14336        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
14337        let rhs_storage = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0, 7.0, 8.0]);
14338
14339        let graph = Arc::new(RwLock::new(Graph::new()));
14340        let (lhs_id, rhs_id, t_id, mm_id) = {
14341            let mut g = graph.write().unwrap();
14342            let lhs = g.push(Node {
14343                op: Op::Const,
14344                inputs: vec![],
14345                shape: Shape::from_dims(&[2, 2]),
14346                dtype: DType::F32,
14347            });
14348            let rhs = g.push(Node {
14349                op: Op::Const,
14350                inputs: vec![],
14351                shape: Shape::from_dims(&[2, 2]),
14352                dtype: DType::F32,
14353            });
14354            let t = g.push(Node {
14355                op: Op::Transpose,
14356                inputs: vec![rhs],
14357                shape: Shape::from_dims(&[2, 2]),
14358                dtype: DType::F32,
14359            });
14360            let mm = g.push(Node {
14361                op: Op::MatMul,
14362                inputs: vec![lhs, t],
14363                shape: Shape::from_dims(&[2, 2]),
14364                dtype: DType::F32,
14365            });
14366            g.set_target_backend(mm, BackendId::Cpu);
14367            (lhs, rhs, t, mm)
14368        };
14369        let _ = t_id;
14370        let mut inputs = StorageCache::new();
14371        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
14372        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
14373
14374        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
14375        let guard = result_arc.read().unwrap();
14376        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14377            panic!("expected Cpu storage");
14378        };
14379        assert_eq!(c.as_slice::<f32>().unwrap(), &[17.0, 23.0, 39.0, 53.0]);
14380    }
14381
14382    /// E2E: Const + Reshape — contiguous-input reshape is zero
14383    /// copy. The output Storage Arc is the input Arc; the layout
14384    /// is contiguous in the new shape.
14385    #[test]
14386    fn pipelined_realize_reshape_zero_copy_when_contiguous() {
14387        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14388        let graph = Arc::new(RwLock::new(Graph::new()));
14389        let (in_id, r_id) = {
14390            let mut g = graph.write().unwrap();
14391            let in_id = g.push(Node {
14392                op: Op::Const,
14393                inputs: vec![],
14394                shape: Shape::from_dims(&[2, 3]),
14395                dtype: DType::F32,
14396            });
14397            let r_id = g.push(Node {
14398                op: Op::Reshape(Shape::from_dims(&[3, 2])),
14399                inputs: vec![in_id],
14400                shape: Shape::from_dims(&[3, 2]),
14401                dtype: DType::F32,
14402            });
14403            (in_id, r_id)
14404        };
14405        let mut inputs = StorageCache::new();
14406        let in_arc = Arc::new(RwLock::new(storage));
14407        inputs.insert(in_id, Arc::clone(&in_arc));
14408
14409        let (result_arc, result_layout) =
14410            PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
14411
14412        // Zero copy — same Arc.
14413        assert!(
14414            Arc::ptr_eq(&result_arc, &in_arc),
14415            "contiguous reshape must zero-copy"
14416        );
14417        assert_eq!(result_layout.shape().dims(), &[3, 2]);
14418        assert!(result_layout.is_contiguous());
14419
14420        // Bytes are unchanged; just reinterpreted as [3, 2].
14421        let guard = result_arc.read().unwrap();
14422        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14423            panic!("expected Cpu storage");
14424        };
14425        assert_eq!(
14426            c.as_slice::<f32>().unwrap(),
14427            &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
14428        );
14429    }
14430
14431    /// E2E: Const + Transpose + Reshape — reshape on a strided
14432    /// input auto-contiguizes the bytes. Output Arc is fresh
14433    /// (NOT the input Arc); the bytes are the materialized
14434    /// transposed layout.
14435    #[test]
14436    fn pipelined_realize_reshape_materializes_when_strided() {
14437        // shape [2, 3]: 1 2 3 / 4 5 6
14438        // Transpose → [3, 2] strided
14439        // Reshape → [6] (forces materialization)
14440        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14441        let graph = Arc::new(RwLock::new(Graph::new()));
14442        let (in_id, t_id, r_id) = {
14443            let mut g = graph.write().unwrap();
14444            let in_id = g.push(Node {
14445                op: Op::Const,
14446                inputs: vec![],
14447                shape: Shape::from_dims(&[2, 3]),
14448                dtype: DType::F32,
14449            });
14450            let t_id = g.push(Node {
14451                op: Op::Transpose,
14452                inputs: vec![in_id],
14453                shape: Shape::from_dims(&[3, 2]),
14454                dtype: DType::F32,
14455            });
14456            let r_id = g.push(Node {
14457                op: Op::Reshape(Shape::from_dims(&[6])),
14458                inputs: vec![t_id],
14459                shape: Shape::from_dims(&[6]),
14460                dtype: DType::F32,
14461            });
14462            (in_id, t_id, r_id)
14463        };
14464        let _ = t_id;
14465        let mut inputs = StorageCache::new();
14466        let in_arc = Arc::new(RwLock::new(storage));
14467        inputs.insert(in_id, Arc::clone(&in_arc));
14468
14469        let (result_arc, result_layout) =
14470            PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
14471
14472        // Fresh Arc — auto-contiguize allocated new bytes.
14473        assert!(!Arc::ptr_eq(&result_arc, &in_arc));
14474        assert_eq!(result_layout.shape().dims(), &[6]);
14475        assert!(result_layout.is_contiguous());
14476
14477        // Materialized transposed bytes flattened: [1, 4, 2, 5, 3, 6].
14478        let guard = result_arc.read().unwrap();
14479        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14480            panic!("expected Cpu storage");
14481        };
14482        assert_eq!(
14483            c.as_slice::<f32>().unwrap(),
14484            &[1.0, 4.0, 2.0, 5.0, 3.0, 6.0]
14485        );
14486    }
14487
14488    /// E2E: Const + Transpose + SumDim — exercises stage 3
14489    /// (metadata-only Transpose, strided intermediate Layout) +
14490    /// stage 4 (auto-Contiguize before reduce kernel) end-to-end.
14491    /// The transpose makes the intermediate non-contiguous; the
14492    /// reduce wrapper would have failed in stage 2; with stage 4's
14493    /// auto-Contiguize, the kernel sees the materialized contiguous
14494    /// transposed bytes and produces the right answer.
14495    #[test]
14496    fn pipelined_realize_transpose_then_sum_dim_e2e() {
14497        // shape [2, 3]: rows are [1, 2, 3], [4, 5, 6]
14498        // After transpose: shape [3, 2], rows are [1, 4], [2, 5], [3, 6]
14499        // After SumDim(1): shape [3], values [5, 7, 9]
14500        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14501        let graph = Arc::new(RwLock::new(Graph::new()));
14502        let (in_id, t_id, sum_id) = {
14503            let mut g = graph.write().unwrap();
14504            let in_id = g.push(Node {
14505                op: Op::Const,
14506                inputs: vec![],
14507                shape: Shape::from_dims(&[2, 3]),
14508                dtype: DType::F32,
14509            });
14510            let t_id = g.push(Node {
14511                op: Op::Transpose,
14512                inputs: vec![in_id],
14513                shape: Shape::from_dims(&[3, 2]),
14514                dtype: DType::F32,
14515            });
14516            let sum_id = g.push(Node {
14517                op: Op::SumDim(1),
14518                inputs: vec![t_id],
14519                shape: Shape::from_dims(&[3]),
14520                dtype: DType::F32,
14521            });
14522            // Only the reduce kernel runs on the backend; the
14523            // transpose is metadata-only and doesn't need a target.
14524            g.set_target_backend(sum_id, BackendId::Cpu);
14525            (in_id, t_id, sum_id)
14526        };
14527        let _ = t_id;
14528        let mut inputs = StorageCache::new();
14529        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14530
14531        let (result_arc, result_layout) =
14532            PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
14533
14534        // The reduce output is contiguous (kernel-produced).
14535        assert_eq!(result_layout.shape().dims(), &[3]);
14536        assert!(result_layout.is_contiguous());
14537
14538        let guard = result_arc.read().unwrap();
14539        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14540            panic!("expected Cpu storage");
14541        };
14542        let typed: &[f32] = c.as_slice().unwrap();
14543        assert_eq!(typed, &[5.0, 7.0, 9.0]);
14544    }
14545
14546    /// E2E: Const + BroadcastTo + Add — broadcast intermediate
14547    /// auto-contiguizes for the Add kernel; the result is the
14548    /// expected sum.
14549    #[test]
14550    fn pipelined_realize_broadcast_then_add_e2e() {
14551        // shape [3]: [10, 20, 30]
14552        // BroadcastTo [2, 3]: [[10, 20, 30], [10, 20, 30]]
14553        // Plus shape [2, 3]: [[1, 2, 3], [4, 5, 6]]
14554        // Result: [[11, 22, 33], [14, 25, 36]]
14555        let bc_input = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
14556        let plus_input = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14557        let graph = Arc::new(RwLock::new(Graph::new()));
14558        let (bc_in_id, plus_in_id, b_id, add_id) = {
14559            let mut g = graph.write().unwrap();
14560            let bc_in = g.push(Node {
14561                op: Op::Const,
14562                inputs: vec![],
14563                shape: Shape::from_dims(&[3]),
14564                dtype: DType::F32,
14565            });
14566            let plus_in = g.push(Node {
14567                op: Op::Const,
14568                inputs: vec![],
14569                shape: Shape::from_dims(&[2, 3]),
14570                dtype: DType::F32,
14571            });
14572            let b = g.push(Node {
14573                op: Op::BroadcastTo(Shape::from_dims(&[2, 3])),
14574                inputs: vec![bc_in],
14575                shape: Shape::from_dims(&[2, 3]),
14576                dtype: DType::F32,
14577            });
14578            let add = g.push(Node {
14579                op: Op::Add,
14580                inputs: vec![b, plus_in],
14581                shape: Shape::from_dims(&[2, 3]),
14582                dtype: DType::F32,
14583            });
14584            g.set_target_backend(add, BackendId::Cpu);
14585            (bc_in, plus_in, b, add)
14586        };
14587        let _ = b_id;
14588        let mut inputs = StorageCache::new();
14589        inputs.insert(bc_in_id, Arc::new(RwLock::new(bc_input)));
14590        inputs.insert(plus_in_id, Arc::new(RwLock::new(plus_input)));
14591
14592        let (result_arc, _result_layout) =
14593            PipelinedExecutor::realize(graph, add_id, inputs).expect("realize");
14594        let guard = result_arc.read().unwrap();
14595        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14596            panic!("expected Cpu storage");
14597        };
14598        let typed: &[f32] = c.as_slice().unwrap();
14599        assert_eq!(typed, &[11.0, 22.0, 33.0, 14.0, 25.0, 36.0]);
14600    }
14601
14602    /// E2E: Const + SumDim — verifies that `OpParams::Reduce`
14603    /// flows from the graph (input shape via `op_to_op_params`)
14604    /// through compile_one and reaches the reduce kernel.
14605    #[test]
14606    fn pipelined_realize_sum_dim() {
14607        // shape [2, 3]; reduce dim 1 → output shape [2]
14608        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14609        let graph = Arc::new(RwLock::new(Graph::new()));
14610        let (in_id, sum_id) = {
14611            let mut g = graph.write().unwrap();
14612            let in_id = g.push(Node {
14613                op: Op::Const,
14614                inputs: vec![],
14615                shape: Shape::from_dims(&[2, 3]),
14616                dtype: DType::F32,
14617            });
14618            let sum_id = g.push(Node {
14619                op: Op::SumDim(1),
14620                inputs: vec![in_id],
14621                shape: Shape::from_dims(&[2]),
14622                dtype: DType::F32,
14623            });
14624            g.set_target_backend(sum_id, BackendId::Cpu);
14625            (in_id, sum_id)
14626        };
14627        let mut inputs = StorageCache::new();
14628        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14629
14630        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
14631        let guard = result_arc.read().unwrap();
14632        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14633            let typed: &[f32] = c.as_slice().unwrap();
14634            assert_eq!(typed, &[6.0, 15.0]);
14635        }
14636    }
14637
14638    /// E2E: SumAll on a rank-3 input, exercising the all-dims branch
14639    /// of `op_to_op_params` (every dim reduced, rank-0 output).
14640    #[test]
14641    fn pipelined_realize_sum_all_rank3() {
14642        let data: Vec<f32> = (1..=24).map(|x| x as f32).collect();
14643        let storage = fuel_memory::from_slice_cpu(&data);
14644        let graph = Arc::new(RwLock::new(Graph::new()));
14645        let (in_id, sum_id) = {
14646            let mut g = graph.write().unwrap();
14647            let in_id = g.push(Node {
14648                op: Op::Const,
14649                inputs: vec![],
14650                shape: Shape::from_dims(&[2, 3, 4]),
14651                dtype: DType::F32,
14652            });
14653            let sum_id = g.push(Node {
14654                op: Op::SumAll,
14655                inputs: vec![in_id],
14656                shape: Shape::from_dims(&[]),
14657                dtype: DType::F32,
14658            });
14659            g.set_target_backend(sum_id, BackendId::Cpu);
14660            (in_id, sum_id)
14661        };
14662        let mut inputs = StorageCache::new();
14663        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14664
14665        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
14666        let guard = result_arc.read().unwrap();
14667        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14668            let typed: &[f32] = c.as_slice().unwrap();
14669            // 1 + 2 + ... + 24 = 300
14670            assert_eq!(typed, &[300.0]);
14671        }
14672    }
14673
14674    /// E2E: MaxDim + MeanDim chained — verifies all four reduce
14675    /// OpKinds reach their wrappers via the OpParams plumbing.
14676    #[test]
14677    fn pipelined_realize_max_then_mean() {
14678        // shape [2, 3], MaxDim(1) → [2], MeanDim(0) → []
14679        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 9.0, 3.0, 4.0, 2.0, 8.0]);
14680        let graph = Arc::new(RwLock::new(Graph::new()));
14681        let (in_id, mean_id) = {
14682            let mut g = graph.write().unwrap();
14683            let in_id = g.push(Node {
14684                op: Op::Const,
14685                inputs: vec![],
14686                shape: Shape::from_dims(&[2, 3]),
14687                dtype: DType::F32,
14688            });
14689            let max_id = g.push(Node {
14690                op: Op::MaxDim(1),
14691                inputs: vec![in_id],
14692                shape: Shape::from_dims(&[2]),
14693                dtype: DType::F32,
14694            });
14695            let mean_id = g.push(Node {
14696                op: Op::MeanDim(0),
14697                inputs: vec![max_id],
14698                shape: Shape::from_dims(&[]),
14699                dtype: DType::F32,
14700            });
14701            g.set_target_backend(max_id, BackendId::Cpu);
14702            g.set_target_backend(mean_id, BackendId::Cpu);
14703            (in_id, mean_id)
14704        };
14705        let mut inputs = StorageCache::new();
14706        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14707
14708        let (result_arc, _) = PipelinedExecutor::realize(graph, mean_id, inputs).expect("realize");
14709        let guard = result_arc.read().unwrap();
14710        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14711            let typed: &[f32] = c.as_slice().unwrap();
14712            // MaxDim(1) on [[1,9,3],[4,2,8]] = [9, 8]; MeanDim(0) = 8.5
14713            assert_eq!(typed, &[8.5]);
14714        }
14715    }
14716
14717    /// E2E: Sigmoid + Silu — exercises two of the more compositional
14718    /// new unary kernels through the pipelined executor. Verifies
14719    /// the additional `op_to_op_kind` mappings reach the right
14720    /// dispatch wrappers.
14721    #[test]
14722    fn pipelined_realize_sigmoid_then_silu() {
14723        let storage = fuel_memory::from_slice_cpu(&[0.0_f32, 1.0, -1.0]);
14724        let graph = Arc::new(RwLock::new(Graph::new()));
14725        let (in_id, sig_id, silu_id) = {
14726            let mut g = graph.write().unwrap();
14727            let in_id = g.push(Node {
14728                op: Op::Const,
14729                inputs: vec![],
14730                shape: Shape::from_dims(&[3]),
14731                dtype: DType::F32,
14732            });
14733            let sig_id = g.push(Node {
14734                op: Op::Sigmoid,
14735                inputs: vec![in_id],
14736                shape: Shape::from_dims(&[3]),
14737                dtype: DType::F32,
14738            });
14739            // Silu of the sigmoid output — chains to confirm cache flow.
14740            let silu_id = g.push(Node {
14741                op: Op::Silu,
14742                inputs: vec![sig_id],
14743                shape: Shape::from_dims(&[3]),
14744                dtype: DType::F32,
14745            });
14746            g.set_target_backend(sig_id, BackendId::Cpu);
14747            g.set_target_backend(silu_id, BackendId::Cpu);
14748            (in_id, sig_id, silu_id)
14749        };
14750        let _ = sig_id;
14751        let mut inputs = StorageCache::new();
14752        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14753
14754        let (result_arc, _) = PipelinedExecutor::realize(graph, silu_id, inputs).expect("realize");
14755        let guard = result_arc.read().unwrap();
14756        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14757            let typed: &[f32] = c.as_slice().unwrap();
14758            // sigmoid(0) = 0.5; silu(0.5) = 0.5 * sigmoid(0.5) ≈ 0.3112
14759            assert!((typed[0] - 0.5 * (1.0 / (1.0 + (-0.5_f32).exp()))).abs() < 1e-6);
14760        }
14761    }
14762
14763    /// E2E: chained unary ops — Const + Sqr + Sqrt should be a noop
14764    /// for non-negative inputs. Exercises the cache reuse path.
14765    #[test]
14766    fn pipelined_realize_chained_unary_sqr_then_sqrt() {
14767        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 4.0, 9.0]);
14768        let graph = Arc::new(RwLock::new(Graph::new()));
14769        let (in_id, sqrt_id) = {
14770            let mut g = graph.write().unwrap();
14771            let in_id = g.push(Node {
14772                op: Op::Const,
14773                inputs: vec![],
14774                shape: Shape::from_dims(&[3]),
14775                dtype: DType::F32,
14776            });
14777            let sqr_id = g.push(Node {
14778                op: Op::Sqr,
14779                inputs: vec![in_id],
14780                shape: Shape::from_dims(&[3]),
14781                dtype: DType::F32,
14782            });
14783            let sqrt_id = g.push(Node {
14784                op: Op::Sqrt,
14785                inputs: vec![sqr_id],
14786                shape: Shape::from_dims(&[3]),
14787                dtype: DType::F32,
14788            });
14789            g.set_target_backend(sqr_id, BackendId::Cpu);
14790            g.set_target_backend(sqrt_id, BackendId::Cpu);
14791            (in_id, sqrt_id)
14792        };
14793        let mut inputs = StorageCache::new();
14794        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14795
14796        let (result_arc, _) = PipelinedExecutor::realize(graph, sqrt_id, inputs).expect("realize");
14797        let guard = result_arc.read().unwrap();
14798        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14799            let typed: &[f32] = c.as_slice().unwrap();
14800            // sqrt(sqr(x)) == |x| == x for non-negative inputs.
14801            assert_eq!(typed, &[1.0, 4.0, 9.0]);
14802        }
14803    }
14804
14805    /// Multi-stage pipelined: Const + Const + Add + Add (chain of
14806    /// two adds). Tests that work items are processed in topo order
14807    /// and intermediate results are cached and reused.
14808    #[test]
14809    fn pipelined_realize_chained_adds() {
14810        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
14811        let b_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
14812        let c_storage = fuel_memory::from_slice_cpu(&[100.0_f32, 200.0]);
14813
14814        let graph = Arc::new(RwLock::new(Graph::new()));
14815        let (a_id, b_id, c_id, ab_id, abc_id) = {
14816            let mut g = graph.write().unwrap();
14817            let a = g.push(Node {
14818                op: Op::Const,
14819                inputs: vec![],
14820                shape: Shape::from_dims(&[2]),
14821                dtype: DType::F32,
14822            });
14823            let b = g.push(Node {
14824                op: Op::Const,
14825                inputs: vec![],
14826                shape: Shape::from_dims(&[2]),
14827                dtype: DType::F32,
14828            });
14829            let c = g.push(Node {
14830                op: Op::Const,
14831                inputs: vec![],
14832                shape: Shape::from_dims(&[2]),
14833                dtype: DType::F32,
14834            });
14835            let ab = g.push(Node {
14836                op: Op::Add,
14837                inputs: vec![a, b],
14838                shape: Shape::from_dims(&[2]),
14839                dtype: DType::F32,
14840            });
14841            let abc = g.push(Node {
14842                op: Op::Add,
14843                inputs: vec![ab, c],
14844                shape: Shape::from_dims(&[2]),
14845                dtype: DType::F32,
14846            });
14847            g.set_target_backend(ab, BackendId::Cpu);
14848            g.set_target_backend(abc, BackendId::Cpu);
14849            (a, b, c, ab, abc)
14850        };
14851
14852        let mut inputs = StorageCache::new();
14853        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
14854        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
14855        inputs.insert(c_id, Arc::new(RwLock::new(c_storage)));
14856
14857        let (result_arc, _) = PipelinedExecutor::realize(graph, abc_id, inputs).expect("realize");
14858        // Suppress unused warning for the intermediate id.
14859        let _ = ab_id;
14860
14861        let guard = result_arc.read().unwrap();
14862        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14863            let typed: &[f32] = c.as_slice().unwrap();
14864            // (1+10) + 100 = 111;  (2+20) + 200 = 222.
14865            assert_eq!(typed, &[111.0, 222.0]);
14866        }
14867    }
14868
14869    /// E2E: triu(diagonal=0) on a 3×3 matrix.
14870    /// Input:  [1 2 3 / 4 5 6 / 7 8 9]
14871    /// Output: [1 2 3 / 0 5 6 / 0 0 9]
14872    #[test]
14873    fn pipelined_realize_triu_3x3_diag0() {
14874        let storage =
14875            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
14876        let graph = Arc::new(RwLock::new(Graph::new()));
14877        let (in_id, out_id) = {
14878            let mut g = graph.write().unwrap();
14879            let in_id = g.push(Node {
14880                op: Op::Const,
14881                inputs: vec![],
14882                shape: Shape::from_dims(&[3, 3]),
14883                dtype: DType::F32,
14884            });
14885            let out_id = g.push(Node {
14886                op: Op::Triu { diagonal: 0 },
14887                inputs: vec![in_id],
14888                shape: Shape::from_dims(&[3, 3]),
14889                dtype: DType::F32,
14890            });
14891            g.set_target_backend(out_id, BackendId::Cpu);
14892            (in_id, out_id)
14893        };
14894        let mut inputs = StorageCache::new();
14895        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14896        let (result_arc, _) = PipelinedExecutor::realize(graph, out_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 out: &[f32] = c.as_slice().unwrap();
14902        assert_eq!(out, &[1.0, 2.0, 3.0, 0.0, 5.0, 6.0, 0.0, 0.0, 9.0,]);
14903    }
14904
14905    /// E2E: tril(diagonal=0) on a 3×3 matrix — the canonical causal mask.
14906    /// Output: [1 0 0 / 4 5 0 / 7 8 9]
14907    #[test]
14908    fn pipelined_realize_tril_3x3_diag0_causal_mask() {
14909        let storage =
14910            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
14911        let graph = Arc::new(RwLock::new(Graph::new()));
14912        let (in_id, out_id) = {
14913            let mut g = graph.write().unwrap();
14914            let in_id = g.push(Node {
14915                op: Op::Const,
14916                inputs: vec![],
14917                shape: Shape::from_dims(&[3, 3]),
14918                dtype: DType::F32,
14919            });
14920            let out_id = g.push(Node {
14921                op: Op::Tril { diagonal: 0 },
14922                inputs: vec![in_id],
14923                shape: Shape::from_dims(&[3, 3]),
14924                dtype: DType::F32,
14925            });
14926            g.set_target_backend(out_id, BackendId::Cpu);
14927            (in_id, out_id)
14928        };
14929        let mut inputs = StorageCache::new();
14930        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14931        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
14932        let guard = result_arc.read().unwrap();
14933        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14934            panic!("expected Cpu storage");
14935        };
14936        let out: &[f32] = c.as_slice().unwrap();
14937        assert_eq!(out, &[1.0, 0.0, 0.0, 4.0, 5.0, 0.0, 7.0, 8.0, 9.0,]);
14938    }
14939
14940    /// E2E: log_softmax over a 2×3 input. Rows are [1,2,3] and [3,2,1].
14941    /// log_softmax(row) = row - max - log(sum exp(row - max)).
14942    /// Row 0: max=3, exp(-2)+exp(-1)+exp(0) = 0.135+0.368+1.0 = 1.503;
14943    ///        log(1.503) ≈ 0.4076; out = [1-3-0.4076, 2-3-0.4076, 3-3-0.4076]
14944    ///                              = [-2.4076, -1.4076, -0.4076]
14945    /// Row 1 is row 0 reversed: [-0.4076, -1.4076, -2.4076].
14946    #[test]
14947    fn pipelined_realize_log_softmax_last_dim() {
14948        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 3.0, 2.0, 1.0]);
14949        let graph = Arc::new(RwLock::new(Graph::new()));
14950        let (in_id, out_id) = {
14951            let mut g = graph.write().unwrap();
14952            let in_id = g.push(Node {
14953                op: Op::Const,
14954                inputs: vec![],
14955                shape: Shape::from_dims(&[2, 3]),
14956                dtype: DType::F32,
14957            });
14958            let out_id = g.push(Node {
14959                op: Op::LogSoftmaxLastDim,
14960                inputs: vec![in_id],
14961                shape: Shape::from_dims(&[2, 3]),
14962                dtype: DType::F32,
14963            });
14964            g.set_target_backend(out_id, BackendId::Cpu);
14965            (in_id, out_id)
14966        };
14967        let mut inputs = StorageCache::new();
14968        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14969        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
14970        let guard = result_arc.read().unwrap();
14971        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14972            panic!("expected Cpu storage");
14973        };
14974        let out: &[f32] = c.as_slice().unwrap();
14975        let expected = [
14976            -2.407_606,
14977            -1.4076059,
14978            -0.40760595_f32,
14979            -0.40760595,
14980            -1.4076059,
14981            -2.407_606,
14982        ];
14983        for (a, b) in out.iter().zip(expected.iter()) {
14984            assert!((a - b).abs() < 1e-5, "log_softmax mismatch: {a} vs {b}");
14985        }
14986        // The exp() of the output should sum to 1 per row.
14987        for row in out.chunks(3) {
14988            let sum: f32 = row.iter().map(|x| x.exp()).sum();
14989            assert!(
14990                (sum - 1.0).abs() < 1e-5,
14991                "softmax(log_softmax) row sum != 1: {sum}"
14992            );
14993        }
14994    }
14995
14996    // --- side-effect roots + destructive cleanup (9c Phase B) -----
14997
14998    /// Side-effect roots get merged into the realize walk even when
14999    /// not reachable from the user's targets. The production trigger
15000    /// is `Op::Release` (emitted by `ResidencyEvictionRule`); this
15001    /// test uses that exact shape.
15002    ///
15003    /// Graph: Const(a) + Const(b) → Add (user target); separate
15004    /// Const(c) → Release(c) (side-effect root, not reachable from
15005    /// Add). After realize_many on `[add]`, the Add should be in the
15006    /// output AND the Release should have fired (verified by the
15007    /// fact that realize succeeded — Op::Release in the walk used to
15008    /// fail compilation pre-Phase B+).
15009    #[test]
15010    fn pipelined_realize_merges_op_release_side_effect_root() {
15011        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
15012        let b = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
15013        let c = fuel_memory::from_slice_cpu(&[100.0_f32, 200.0]);
15014        let graph = Arc::new(RwLock::new(Graph::new()));
15015        let (a_id, b_id, c_id, add_id, release_id) = {
15016            let mut g = graph.write().unwrap();
15017            let a = g.push(Node {
15018                op: Op::Const,
15019                inputs: vec![],
15020                shape: Shape::from_dims(&[2]),
15021                dtype: DType::F32,
15022            });
15023            let b = g.push(Node {
15024                op: Op::Const,
15025                inputs: vec![],
15026                shape: Shape::from_dims(&[2]),
15027                dtype: DType::F32,
15028            });
15029            // c is NOT reachable from add; its Release IS marked as
15030            // a side-effect root.
15031            let c = g.push(Node {
15032                op: Op::Const,
15033                inputs: vec![],
15034                shape: Shape::from_dims(&[2]),
15035                dtype: DType::F32,
15036            });
15037            let add = g.push(Node {
15038                op: Op::Add,
15039                inputs: vec![a, b],
15040                shape: Shape::from_dims(&[2]),
15041                dtype: DType::F32,
15042            });
15043            // Production shape: Op::Release on c, marked as
15044            // side-effect root so it fires even though no graph
15045            // node reads its output.
15046            let release = g.push(Node {
15047                op: Op::Release,
15048                inputs: vec![c],
15049                shape: Shape::from_dims(&[0]),
15050                dtype: DType::F32,
15051            });
15052            g.set_target_backend(add, BackendId::Cpu);
15053            g.set_target_backend(release, BackendId::Cpu);
15054            g.add_side_effect_root(release);
15055            (a, b, c, add, release)
15056        };
15057        let mut inputs = StorageCache::new();
15058        inputs.insert(a_id, Arc::new(RwLock::new(a)));
15059        inputs.insert(b_id, Arc::new(RwLock::new(b)));
15060        let c_arc = Arc::new(RwLock::new(c));
15061        let c_arc_external = Arc::clone(&c_arc);
15062        inputs.insert(c_id, c_arc);
15063
15064        // Only `add` is requested. The Release on c is a side-effect
15065        // root that must still fire.
15066        let out = PipelinedExecutor::realize_many(graph, &[add_id], inputs).expect("realize_many");
15067        assert_eq!(out.len(), 1);
15068        let add_guard = out[0].0.read().unwrap();
15069        let fuel_memory::BackendStorage::Cpu(arr) = &add_guard.inner else {
15070            panic!()
15071        };
15072        assert_eq!(arr.as_slice::<f32>().unwrap(), &[11.0, 22.0]);
15073
15074        // The Release's destructive_input cleanup dropped the
15075        // cache's Arc to c. The only Arc to c that survives is the
15076        // external one this test holds — confirms the eviction
15077        // actually freed the cache's reference.
15078        assert_eq!(
15079            Arc::strong_count(&c_arc_external),
15080            1,
15081            "Op::Release should evict the cache's Arc to its source; \
15082             only the test's external clone should remain",
15083        );
15084        let _ = release_id;
15085    }
15086
15087    /// `compile_one` emits a `WorkItemKind::ReleaseMarker` for
15088    /// `Op::Release` with `destructive_input = Some(0)`. Verify
15089    /// the WorkItem shape via a direct compile_one call.
15090    #[test]
15091    fn compile_one_emits_release_marker_with_destructive_input() {
15092        let graph_rc = Arc::new(RwLock::new(Graph::new()));
15093        let (src_id, release_id) = {
15094            let mut g = graph_rc.write().unwrap();
15095            let src = g.push(Node {
15096                op: Op::Const,
15097                inputs: vec![],
15098                shape: Shape::from_dims(&[2]),
15099                dtype: DType::F32,
15100            });
15101            let release = g.push(Node {
15102                op: Op::Release,
15103                inputs: vec![src],
15104                shape: Shape::from_dims(&[0]),
15105                dtype: DType::F32,
15106            });
15107            g.set_target_backend(release, BackendId::Cpu);
15108            (src, release)
15109        };
15110        let g = graph_rc.read().unwrap();
15111        let bindings = crate::dispatch::global_bindings();
15112        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
15113        let item = compile_one(
15114            &g,
15115            release_id,
15116            &mut layout_cache,
15117            &bindings,
15118            &SymEnv::default(),
15119        )
15120        .expect("compile_one Op::Release");
15121        assert!(matches!(item.kind, WorkItemKind::ReleaseMarker));
15122        assert_eq!(item.destructive_input, Some(0));
15123        assert_eq!(item.inputs, vec![src_id]);
15124        assert_eq!(
15125            item.elem_count, 0,
15126            "Release output is the zero-element marker"
15127        );
15128    }
15129
15130    // --- Op::Move (executor-unification Session 1, gap 13) --------
15131
15132    /// `compile_one` emits a `WorkItemKind::Move` for `Op::Move` with
15133    /// `destructive_input = Some(0)` and a resolved transfer kernel
15134    /// (binding-table lookup at `(OpKind::Copy, [dt, dt], source
15135    /// backend)` — Move shares Op::Copy's data-movement kernel).
15136    #[test]
15137    fn compile_one_emits_move_with_destructive_input() {
15138        let graph_rc = Arc::new(RwLock::new(Graph::new()));
15139        let (src_id, move_id) = {
15140            let mut g = graph_rc.write().unwrap();
15141            let src = g.push(Node {
15142                op: Op::Const,
15143                inputs: vec![],
15144                shape: Shape::from_dims(&[2]),
15145                dtype: DType::F32,
15146            });
15147            let mv = g.push(Node {
15148                op: Op::Move {
15149                    target: DeviceLocation::Cpu,
15150                },
15151                inputs: vec![src],
15152                shape: Shape::from_dims(&[2]),
15153                dtype: DType::F32,
15154            });
15155            g.set_target_backend(mv, BackendId::Cpu);
15156            (src, mv)
15157        };
15158        let g = graph_rc.read().unwrap();
15159        let bindings = crate::dispatch::global_bindings();
15160        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
15161        let item = compile_one(
15162            &g,
15163            move_id,
15164            &mut layout_cache,
15165            &bindings,
15166            &SymEnv::default(),
15167        )
15168        .expect("compile_one Op::Move");
15169        assert!(matches!(
15170            item.kind,
15171            WorkItemKind::Move {
15172                target_location: DeviceLocation::Cpu
15173            },
15174        ));
15175        assert_eq!(item.destructive_input, Some(0), "Move destroys its source");
15176        assert_eq!(item.inputs, vec![src_id]);
15177        assert!(
15178            item.compiled.is_some(),
15179            "Move resolves a transfer kernel at (OpKind::Copy, [dt, dt], source backend)",
15180        );
15181    }
15182
15183    // --- runtime fused op (JIT-adopted Tier-2 kernel) --------------
15184
15185    /// `compile_one` resolves an `Op::Fused(fid, Runtime)` node with
15186    /// `fid.is_runtime()` from the runtime-kernel sidecar (never the
15187    /// binding table): `WorkItemKind::Kernel`, `compiled.op ==
15188    /// OpKind::RuntimeFused`, and the kernel pointer is exactly the one
15189    /// `adopt_runtime_fused` bound.
15190    #[test]
15191    fn compile_one_resolves_runtime_fused_from_the_sidecar() {
15192        fn sentinel_kernel(
15193            _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
15194            _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
15195            _layouts: &[Layout],
15196            _params: &crate::kernel::OpParams,
15197        ) -> Result<()> {
15198            Ok(())
15199        }
15200        // A region shape unique to this test (process-global sidecar; see
15201        // runtime_fused_pathfinder's tests for the collision rationale).
15202        let region = fuel_graph::jit::PatternNode::Op {
15203            op: fuel_graph::jit::OpTag::Exp,
15204            attrs: fuel_graph::jit::OpAttrs::default(),
15205            operands: vec![fuel_graph::jit::PatternNode::Op {
15206                op: fuel_graph::jit::OpTag::Sub,
15207                attrs: fuel_graph::jit::OpAttrs::default(),
15208                operands: vec![
15209                    fuel_graph::jit::PatternNode::Bind { index: 0 },
15210                    fuel_graph::jit::PatternNode::Bind { index: 1 },
15211                ],
15212            }],
15213        };
15214        let rid = crate::runtime_fused_kernels::adopt_runtime_fused(
15215            "test::compile_one::exp_sub",
15216            region,
15217            sentinel_kernel as crate::kernel::KernelRef,
15218            vec![DType::F32, DType::F32, DType::F32],
15219            BackendId::Cpu,
15220        )
15221        .expect("registrable region");
15222
15223        let graph_rc = Arc::new(RwLock::new(Graph::new()));
15224        let fused_id = {
15225            let mut g = graph_rc.write().unwrap();
15226            let s = Shape::from_dims(&[4]);
15227            let a = g.push(Node {
15228                op: Op::Const,
15229                inputs: vec![],
15230                shape: s.clone(),
15231                dtype: DType::F32,
15232            });
15233            let b = g.push(Node {
15234                op: Op::Const,
15235                inputs: vec![],
15236                shape: s.clone(),
15237                dtype: DType::F32,
15238            });
15239            let fused = g.push(Node {
15240                op: Op::Fused(
15241                    rid,
15242                    fuel_graph::registry::FusedOpParams::Runtime {
15243                        scalars: Vec::new(),
15244                    },
15245                ),
15246                inputs: vec![a, b],
15247                shape: s,
15248                dtype: DType::F32,
15249            });
15250            // The arm emitter pins the backend; mirror that here.
15251            g.set_target_backend(fused, BackendId::Cpu);
15252            fused
15253        };
15254        let g = graph_rc.read().unwrap();
15255        let bindings = crate::dispatch::global_bindings();
15256        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
15257        let item = compile_one(
15258            &g,
15259            fused_id,
15260            &mut layout_cache,
15261            &bindings,
15262            &SymEnv::default(),
15263        )
15264        .expect("compile_one runtime fused op");
15265        assert!(matches!(item.kind, WorkItemKind::Kernel));
15266        let compiled = item.compiled.expect("resolved a kernel");
15267        assert_eq!(compiled.op, fuel_ir::dispatch::OpKind::RuntimeFused);
15268        assert_eq!(compiled.backend, BackendId::Cpu);
15269        assert!(
15270            std::ptr::fn_addr_eq(compiled.kernel, sentinel_kernel as crate::kernel::KernelRef),
15271            "the kernel pointer is exactly the adopted one",
15272        );
15273        assert!(
15274            layout_cache.contains_key(&fused_id),
15275            "output layout cached for consumers"
15276        );
15277    }
15278
15279    /// The dtype belt-and-suspenders guard: an `Op::Fused(runtime)` node
15280    /// whose per-operand dtypes disagree with the adopted kernel's tuple is
15281    /// a typed error, not a silent wrong-kernel dispatch.
15282    #[test]
15283    fn compile_one_rejects_runtime_fused_dtype_mismatch() {
15284        fn noop_kernel(
15285            _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
15286            _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
15287            _layouts: &[Layout],
15288            _params: &crate::kernel::OpParams,
15289        ) -> Result<()> {
15290            Ok(())
15291        }
15292        let region = fuel_graph::jit::PatternNode::Op {
15293            op: fuel_graph::jit::OpTag::Log,
15294            attrs: fuel_graph::jit::OpAttrs::default(),
15295            operands: vec![fuel_graph::jit::PatternNode::Op {
15296                op: fuel_graph::jit::OpTag::Maximum,
15297                attrs: fuel_graph::jit::OpAttrs::default(),
15298                operands: vec![
15299                    fuel_graph::jit::PatternNode::Bind { index: 0 },
15300                    fuel_graph::jit::PatternNode::Bind { index: 1 },
15301                ],
15302            }],
15303        };
15304        // Adopted for F32 operands…
15305        let rid = crate::runtime_fused_kernels::adopt_runtime_fused(
15306            "test::compile_one::log_maximum",
15307            region,
15308            noop_kernel as crate::kernel::KernelRef,
15309            vec![DType::F32, DType::F32, DType::F32],
15310            BackendId::Cpu,
15311        )
15312        .expect("registrable region");
15313
15314        let graph_rc = Arc::new(RwLock::new(Graph::new()));
15315        let fused_id = {
15316            let mut g = graph_rc.write().unwrap();
15317            let s = Shape::from_dims(&[4]);
15318            // …but the node's operands are F64.
15319            let a = g.push(Node {
15320                op: Op::Const,
15321                inputs: vec![],
15322                shape: s.clone(),
15323                dtype: DType::F64,
15324            });
15325            let b = g.push(Node {
15326                op: Op::Const,
15327                inputs: vec![],
15328                shape: s.clone(),
15329                dtype: DType::F64,
15330            });
15331            let fused = g.push(Node {
15332                op: Op::Fused(
15333                    rid,
15334                    fuel_graph::registry::FusedOpParams::Runtime {
15335                        scalars: Vec::new(),
15336                    },
15337                ),
15338                inputs: vec![a, b],
15339                shape: s,
15340                dtype: DType::F64,
15341            });
15342            g.set_target_backend(fused, BackendId::Cpu);
15343            fused
15344        };
15345        let g = graph_rc.read().unwrap();
15346        let bindings = crate::dispatch::global_bindings();
15347        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
15348        let err = match compile_one(
15349            &g,
15350            fused_id,
15351            &mut layout_cache,
15352            &bindings,
15353            &SymEnv::default(),
15354        ) {
15355            Ok(_) => panic!("dtype mismatch must be a typed error"),
15356            Err(e) => e,
15357        };
15358        // Post-fold, the dtype tuple IS the binding key: a mismatch is the
15359        // same honest `NoBackendForOp` miss as an absent kernel — reported
15360        // with the `RuntimeFused` diagnostic op tag, never a wrong-kernel bind.
15361        assert!(
15362            matches!(
15363                err,
15364                fuel_ir::Error::NoBackendForOp {
15365                    op: fuel_ir::dispatch::OpKind::RuntimeFused,
15366                    ..
15367                }
15368            ),
15369            "a dtype mismatch is an honest binding miss: {err}",
15370        );
15371    }
15372
15373    /// A runtime fused node carrying live `Runtime { scalars }` compiles with
15374    /// `OpParams::JitScalars` — the launch channel for the kernel's trailing
15375    /// `p{i}` args. (A param-free node keeps `OpParams::None`, covered by
15376    /// `compile_one_resolves_runtime_fused_from_the_sidecar`.)
15377    #[test]
15378    fn compile_one_maps_runtime_scalars_to_jit_scalars() {
15379        fn noop_kernel(
15380            _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
15381            _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
15382            _layouts: &[Layout],
15383            _params: &crate::kernel::OpParams,
15384        ) -> Result<()> {
15385            Ok(())
15386        }
15387        // Unique slot-template region (process-global sidecar).
15388        let region = fuel_graph::jit::PatternNode::Op {
15389            op: fuel_graph::jit::OpTag::Floor,
15390            attrs: fuel_graph::jit::OpAttrs::default(),
15391            operands: vec![fuel_graph::jit::PatternNode::Op {
15392                op: fuel_graph::jit::OpTag::MulScalar,
15393                attrs: fuel_graph::jit::OpAttrs::default(), // open slot
15394                operands: vec![fuel_graph::jit::PatternNode::Bind { index: 0 }],
15395            }],
15396        };
15397        let rid = crate::runtime_fused_kernels::adopt_runtime_fused(
15398            "test::compile_one::floor_mul_scalar",
15399            region,
15400            noop_kernel as crate::kernel::KernelRef,
15401            vec![DType::F32, DType::F32],
15402            BackendId::Cpu,
15403        )
15404        .expect("slot template registrable");
15405
15406        let graph_rc = Arc::new(RwLock::new(Graph::new()));
15407        let fused_id = {
15408            let mut g = graph_rc.write().unwrap();
15409            let s = Shape::from_dims(&[4]);
15410            let x = g.push(Node {
15411                op: Op::Const,
15412                inputs: vec![],
15413                shape: s.clone(),
15414                dtype: DType::F32,
15415            });
15416            let fused = g.push(Node {
15417                op: Op::Fused(
15418                    rid,
15419                    fuel_graph::registry::FusedOpParams::Runtime {
15420                        scalars: vec![3.5, -1.25],
15421                    },
15422                ),
15423                inputs: vec![x],
15424                shape: s,
15425                dtype: DType::F32,
15426            });
15427            g.set_target_backend(fused, BackendId::Cpu);
15428            fused
15429        };
15430        let g = graph_rc.read().unwrap();
15431        let bindings = crate::dispatch::global_bindings();
15432        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
15433        let item = compile_one(
15434            &g,
15435            fused_id,
15436            &mut layout_cache,
15437            &bindings,
15438            &SymEnv::default(),
15439        )
15440        .expect("compile_one runtime fused op with scalars");
15441        let compiled = item.compiled.expect("resolved a kernel");
15442        assert!(
15443            matches!(
15444                &compiled.op_params,
15445                crate::kernel::OpParams::JitScalars { scalars } if scalars == &vec![3.5, -1.25]
15446            ),
15447            "Runtime scalars ride into OpParams::JitScalars, got {:?}",
15448            compiled.op_params,
15449        );
15450    }
15451
15452    /// Move-to-same-device is the degenerate case: per the legacy
15453    /// `GraphExecutor` contract (`Op::Copy | Op::Move` shared arm →
15454    /// `backend.copy_to`) it is a plain copy — fresh storage on the
15455    /// same device, data intact — and the source is still evicted
15456    /// afterward (destructive semantics don't depend on the devices
15457    /// differing).
15458    #[test]
15459    fn pipelined_op_move_same_device_is_plain_copy() {
15460        let src = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
15461        let graph = Arc::new(RwLock::new(Graph::new()));
15462        let (src_id, move_id) = {
15463            let mut g = graph.write().unwrap();
15464            let src = g.push(Node {
15465                op: Op::Const,
15466                inputs: vec![],
15467                shape: Shape::from_dims(&[4]),
15468                dtype: DType::F32,
15469            });
15470            let mv = g.push(Node {
15471                op: Op::Move {
15472                    target: DeviceLocation::Cpu,
15473                },
15474                inputs: vec![src],
15475                shape: Shape::from_dims(&[4]),
15476                dtype: DType::F32,
15477            });
15478            g.set_target_backend(mv, BackendId::Cpu);
15479            (src, mv)
15480        };
15481        let src_arc = Arc::new(RwLock::new(src));
15482        let src_arc_external = Arc::clone(&src_arc);
15483        let mut inputs = StorageCache::new();
15484        inputs.insert(src_id, src_arc);
15485
15486        let (out, layout) =
15487            PipelinedExecutor::realize(graph, move_id, inputs).expect("realize Op::Move");
15488        let guard = out.read().unwrap();
15489        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15490            panic!()
15491        };
15492        assert_eq!(
15493            c.as_slice::<f32>().unwrap(),
15494            &[1.0, 2.0, 3.0, 4.0],
15495            "Op::Move output should carry input's data to target",
15496        );
15497        assert!(layout.is_contiguous());
15498        drop(guard);
15499        assert!(
15500            !Arc::ptr_eq(&out, &src_arc_external),
15501            "same-device Move is a plain copy — fresh storage, not an alias",
15502        );
15503        // The realize loop's destructive_input cleanup dropped the
15504        // cache's Arc to the source; only the test's external clone
15505        // survives.
15506        assert_eq!(
15507            Arc::strong_count(&src_arc_external),
15508            1,
15509            "Op::Move should evict the cache's Arc to its source",
15510        );
15511    }
15512
15513    /// The multiple-consumer-source case: a Move must NOT strand
15514    /// another consumer of its source. `execution_plan` (via
15515    /// `derive_ordering`, keyed off `destructive_input`) pins the
15516    /// Move AFTER the sibling reader; the executor's post-Move cache
15517    /// eviction then can't break the reader. Mirrors the legacy
15518    /// `op_move_pinned_after_sibling_reader_via_derive_ordering`
15519    /// test in fuel-graph-router/tests/cross_device.rs.
15520    ///
15521    ///   a   = const [1, 2, 3, 4]
15522    ///   b   = relu(a)        (non-destructive sibling reader)
15523    ///   m   = move(a, Cpu)   (destructive — evicts a once run)
15524    ///   out = add(b, m)      → [2, 4, 6, 8]
15525    #[test]
15526    fn pipelined_op_move_multi_consumer_source_not_stranded() {
15527        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
15528        let graph = Arc::new(RwLock::new(Graph::new()));
15529        let (a_id, out_id) = {
15530            let mut g = graph.write().unwrap();
15531            let a = g.push(Node {
15532                op: Op::Const,
15533                inputs: vec![],
15534                shape: Shape::from_dims(&[4]),
15535                dtype: DType::F32,
15536            });
15537            let b = g.push(Node {
15538                op: Op::Relu,
15539                inputs: vec![a],
15540                shape: Shape::from_dims(&[4]),
15541                dtype: DType::F32,
15542            });
15543            let m = g.push(Node {
15544                op: Op::Move {
15545                    target: DeviceLocation::Cpu,
15546                },
15547                inputs: vec![a],
15548                shape: Shape::from_dims(&[4]),
15549                dtype: DType::F32,
15550            });
15551            let out = g.push(Node {
15552                op: Op::Add,
15553                inputs: vec![b, m],
15554                shape: Shape::from_dims(&[4]),
15555                dtype: DType::F32,
15556            });
15557            g.set_target_backend(b, BackendId::Cpu);
15558            g.set_target_backend(m, BackendId::Cpu);
15559            g.set_target_backend(out, BackendId::Cpu);
15560            (a, out)
15561        };
15562        let mut inputs = StorageCache::new();
15563        inputs.insert(a_id, Arc::new(RwLock::new(a)));
15564
15565        let (out, _) = PipelinedExecutor::realize(graph, out_id, inputs)
15566            .expect("realize add(relu(a), move(a))");
15567        let guard = out.read().unwrap();
15568        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15569            panic!()
15570        };
15571        assert_eq!(
15572            c.as_slice::<f32>().unwrap(),
15573            &[2.0, 4.0, 6.0, 8.0],
15574            "relu(a) must run before move(a) evicts a",
15575        );
15576    }
15577
15578    /// A Move whose source is itself in the realize target set must
15579    /// not evict it — the caller asked for the source's storage. The
15580    /// destructive cleanup's `target_set` gate covers Move exactly
15581    /// like Release.
15582    #[test]
15583    fn pipelined_op_move_source_in_target_set_not_evicted() {
15584        let a = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0]);
15585        let graph = Arc::new(RwLock::new(Graph::new()));
15586        let (a_id, move_id) = {
15587            let mut g = graph.write().unwrap();
15588            let a = g.push(Node {
15589                op: Op::Const,
15590                inputs: vec![],
15591                shape: Shape::from_dims(&[2]),
15592                dtype: DType::F32,
15593            });
15594            let mv = g.push(Node {
15595                op: Op::Move {
15596                    target: DeviceLocation::Cpu,
15597                },
15598                inputs: vec![a],
15599                shape: Shape::from_dims(&[2]),
15600                dtype: DType::F32,
15601            });
15602            g.set_target_backend(mv, BackendId::Cpu);
15603            (a, mv)
15604        };
15605        let a_arc = Arc::new(RwLock::new(a));
15606        let a_arc_external = Arc::clone(&a_arc);
15607        let mut inputs = StorageCache::new();
15608        inputs.insert(a_id, a_arc);
15609
15610        let out = PipelinedExecutor::realize_many(graph, &[move_id, a_id], inputs)
15611            .expect("realize_many [move, source]");
15612        assert_eq!(out.len(), 2);
15613        let mv_guard = out[0].0.read().unwrap();
15614        let fuel_memory::BackendStorage::Cpu(c) = &mv_guard.inner else {
15615            panic!()
15616        };
15617        assert_eq!(c.as_slice::<f32>().unwrap(), &[5.0, 6.0]);
15618        assert!(
15619            Arc::ptr_eq(&out[1].0, &a_arc_external),
15620            "requested source must survive the Move's destructive cleanup",
15621        );
15622    }
15623
15624    // --- realize_many (Phase 7.6 step 9c Phase A) ----------------
15625
15626    /// realize_many on empty targets returns an empty Vec — no graph
15627    /// walk, no panic.
15628    #[test]
15629    fn pipelined_realize_many_empty_targets() {
15630        let graph = Arc::new(RwLock::new(Graph::new()));
15631        let inputs = StorageCache::new();
15632        let out = PipelinedExecutor::realize_many(graph, &[], inputs).expect("realize_many");
15633        assert!(out.is_empty());
15634    }
15635
15636    /// realize_many with two independent target chains. Each chain's
15637    /// output is in the cache; the shared topo walk realizes both.
15638    /// Verifies parallel chain handling + return order matches input.
15639    #[test]
15640    fn pipelined_realize_many_two_independent_targets() {
15641        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
15642        let rhs = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
15643        let graph = Arc::new(RwLock::new(Graph::new()));
15644        let (lhs_id, rhs_id, add_id, mul_id) = {
15645            let mut g = graph.write().unwrap();
15646            let lhs = g.push(Node {
15647                op: Op::Const,
15648                inputs: vec![],
15649                shape: Shape::from_dims(&[3]),
15650                dtype: DType::F32,
15651            });
15652            let rhs = g.push(Node {
15653                op: Op::Const,
15654                inputs: vec![],
15655                shape: Shape::from_dims(&[3]),
15656                dtype: DType::F32,
15657            });
15658            let add = g.push(Node {
15659                op: Op::Add,
15660                inputs: vec![lhs, rhs],
15661                shape: Shape::from_dims(&[3]),
15662                dtype: DType::F32,
15663            });
15664            let mul = g.push(Node {
15665                op: Op::Mul,
15666                inputs: vec![lhs, rhs],
15667                shape: Shape::from_dims(&[3]),
15668                dtype: DType::F32,
15669            });
15670            g.set_target_backend(add, BackendId::Cpu);
15671            g.set_target_backend(mul, BackendId::Cpu);
15672            (lhs, rhs, add, mul)
15673        };
15674        let mut inputs = StorageCache::new();
15675        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs)));
15676        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs)));
15677
15678        // Pass mul first to confirm return order matches targets order
15679        // (not graph order — graph order would put add first).
15680        let out = PipelinedExecutor::realize_many(graph, &[mul_id, add_id], inputs)
15681            .expect("realize_many");
15682        assert_eq!(out.len(), 2);
15683
15684        let mul_guard = out[0].0.read().unwrap();
15685        let fuel_memory::BackendStorage::Cpu(c) = &mul_guard.inner else {
15686            panic!()
15687        };
15688        assert_eq!(c.as_slice::<f32>().unwrap(), &[10.0, 40.0, 90.0]);
15689
15690        let add_guard = out[1].0.read().unwrap();
15691        let fuel_memory::BackendStorage::Cpu(c) = &add_guard.inner else {
15692            panic!()
15693        };
15694        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 22.0, 33.0]);
15695    }
15696
15697    /// realize_many with the same NodeId twice — caller asking for
15698    /// the same output twice. Both outputs are the same Arc (cheap).
15699    #[test]
15700    fn pipelined_realize_many_duplicate_target_returns_same_arc() {
15701        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
15702        let graph = Arc::new(RwLock::new(Graph::new()));
15703        let (in_id, neg_id) = {
15704            let mut g = graph.write().unwrap();
15705            let in_id = g.push(Node {
15706                op: Op::Const,
15707                inputs: vec![],
15708                shape: Shape::from_dims(&[3]),
15709                dtype: DType::F32,
15710            });
15711            let neg = g.push(Node {
15712                op: Op::Neg,
15713                inputs: vec![in_id],
15714                shape: Shape::from_dims(&[3]),
15715                dtype: DType::F32,
15716            });
15717            g.set_target_backend(neg, BackendId::Cpu);
15718            (in_id, neg)
15719        };
15720        let mut inputs = StorageCache::new();
15721        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
15722
15723        let out = PipelinedExecutor::realize_many(graph, &[neg_id, neg_id], inputs)
15724            .expect("realize_many");
15725        assert_eq!(out.len(), 2);
15726        assert!(
15727            Arc::ptr_eq(&out[0].0, &out[1].0),
15728            "duplicate target should share the same storage Arc",
15729        );
15730    }
15731
15732    /// realize_many with shared upstream nodes evaluates the shared
15733    /// chunk exactly once. Two targets `f = a + b` and `g = (a + b) * a`
15734    /// — `a + b` is computed once.
15735    #[test]
15736    fn pipelined_realize_many_shared_subgraph_evaluates_once() {
15737        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
15738        let b_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
15739        let graph = Arc::new(RwLock::new(Graph::new()));
15740        let (a_id, b_id, add_id, mul_id) = {
15741            let mut g = graph.write().unwrap();
15742            let a = g.push(Node {
15743                op: Op::Const,
15744                inputs: vec![],
15745                shape: Shape::from_dims(&[3]),
15746                dtype: DType::F32,
15747            });
15748            let b = g.push(Node {
15749                op: Op::Const,
15750                inputs: vec![],
15751                shape: Shape::from_dims(&[3]),
15752                dtype: DType::F32,
15753            });
15754            let add = g.push(Node {
15755                op: Op::Add,
15756                inputs: vec![a, b],
15757                shape: Shape::from_dims(&[3]),
15758                dtype: DType::F32,
15759            });
15760            let mul = g.push(Node {
15761                op: Op::Mul,
15762                inputs: vec![add, a],
15763                shape: Shape::from_dims(&[3]),
15764                dtype: DType::F32,
15765            });
15766            g.set_target_backend(add, BackendId::Cpu);
15767            g.set_target_backend(mul, BackendId::Cpu);
15768            (a, b, add, mul)
15769        };
15770        let mut inputs = StorageCache::new();
15771        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
15772        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
15773
15774        let out = PipelinedExecutor::realize_many(graph, &[add_id, mul_id], inputs)
15775            .expect("realize_many");
15776        assert_eq!(out.len(), 2);
15777
15778        let add_guard = out[0].0.read().unwrap();
15779        let fuel_memory::BackendStorage::Cpu(c) = &add_guard.inner else {
15780            panic!()
15781        };
15782        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 22.0, 33.0]);
15783
15784        let mul_guard = out[1].0.read().unwrap();
15785        let fuel_memory::BackendStorage::Cpu(c) = &mul_guard.inner else {
15786            panic!()
15787        };
15788        // (a + b) * a = [11*1, 22*2, 33*3] = [11, 44, 99].
15789        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 44.0, 99.0]);
15790    }
15791
15792    /// E2E: masked_fill with -inf — the attention masking pattern.
15793    /// x = [1, 2, 3, 4]; mask = [0, 1, 0, 1]; value = -1000.
15794    /// out = [1, -1000, 3, -1000].
15795    #[test]
15796    fn pipelined_realize_masked_fill_attention_pattern() {
15797        let x_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
15798        let mut mask_storage = fuel_memory::from_slice_cpu(&[0u8, 1, 0, 1]);
15799        mask_storage.dtype = DType::Bool; // GAP-168(c): a Bool mask, not U8 bytes
15800        let graph = Arc::new(RwLock::new(Graph::new()));
15801        let (x_id, mask_id, out_id) = {
15802            let mut g = graph.write().unwrap();
15803            let x = g.push(Node {
15804                op: Op::Const,
15805                inputs: vec![],
15806                shape: Shape::from_dims(&[4]),
15807                dtype: DType::F32,
15808            });
15809            let mask = g.push(Node {
15810                op: Op::Const,
15811                inputs: vec![],
15812                shape: Shape::from_dims(&[4]),
15813                dtype: DType::Bool,
15814            });
15815            let out = g.push(Node {
15816                op: Op::MaskedFill {
15817                    value: fuel_ir::Scalar::F32(-1000.0),
15818                },
15819                inputs: vec![x, mask],
15820                shape: Shape::from_dims(&[4]),
15821                dtype: DType::F32,
15822            });
15823            g.set_target_backend(out, BackendId::Cpu);
15824            (x, mask, out)
15825        };
15826        let mut inputs = StorageCache::new();
15827        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
15828        inputs.insert(mask_id, Arc::new(RwLock::new(mask_storage)));
15829        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
15830        let guard = result_arc.read().unwrap();
15831        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15832            panic!("expected Cpu storage");
15833        };
15834        let out: &[f32] = c.as_slice().unwrap();
15835        assert_eq!(out, &[1.0, -1000.0, 3.0, -1000.0]);
15836    }
15837
15838    // ---- WriteSlice (Phase 7.6 step 9c E.3.2) -------------------------------
15839
15840    /// E2E: pipelined realize of `Op::WriteSlice` writing a [1, 3, 2]
15841    /// source slab into a [4, 3, 2] destination at axis-0 row 2 — the
15842    /// canonical KV-cache append shape.
15843    #[test]
15844    fn pipelined_realize_write_slice_kv_cache_append() {
15845        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 24]);
15846        let src_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
15847        let graph = Arc::new(RwLock::new(Graph::new()));
15848        let (dest_id, src_id, ws_id) = {
15849            let mut g = graph.write().unwrap();
15850            let dest = g.push(Node {
15851                op: Op::Const,
15852                inputs: vec![],
15853                shape: Shape::from_dims(&[4, 3, 2]),
15854                dtype: DType::F32,
15855            });
15856            let src = g.push(Node {
15857                op: Op::Const,
15858                inputs: vec![],
15859                shape: Shape::from_dims(&[1, 3, 2]),
15860                dtype: DType::F32,
15861            });
15862            let ws = g.push(Node {
15863                op: Op::WriteSlice {
15864                    ranges: vec![(2, 3), (0, 3), (0, 2)],
15865                    dyn_offset: None,
15866                },
15867                inputs: vec![dest, src],
15868                shape: Shape::from_dims(&[4, 3, 2]), // adopts dest shape
15869                dtype: DType::F32,
15870            });
15871            g.set_target_backend(ws, BackendId::Cpu);
15872            (dest, src, ws)
15873        };
15874        let mut inputs = StorageCache::new();
15875        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
15876        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
15877        let (result_arc, _) = PipelinedExecutor::realize(graph, ws_id, inputs).expect("realize");
15878        let guard = result_arc.read().unwrap();
15879        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15880            panic!("expected Cpu storage");
15881        };
15882        let out: &[f32] = c.as_slice().unwrap();
15883        let expected = [
15884            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,
15885            6.0, // row 2 = source
15886            0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
15887        ];
15888        assert_eq!(out, &expected);
15889    }
15890
15891    /// E2E: pipelined realize of `Op::WriteSlice` adopts the
15892    /// destination's Storage Arc as the output slot (in-place
15893    /// alias) — the resulting Arc points to the SAME bytes the
15894    /// destination was constructed from.
15895    #[test]
15896    fn pipelined_realize_write_slice_aliases_dest_storage() {
15897        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
15898        let src_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
15899        let graph = Arc::new(RwLock::new(Graph::new()));
15900        let (dest_id, src_id, ws_id, dest_arc_external) = {
15901            let mut g = graph.write().unwrap();
15902            let dest = g.push(Node {
15903                op: Op::Const,
15904                inputs: vec![],
15905                shape: Shape::from_dims(&[3, 2]),
15906                dtype: DType::F32,
15907            });
15908            let src = g.push(Node {
15909                op: Op::Const,
15910                inputs: vec![],
15911                shape: Shape::from_dims(&[1, 2]),
15912                dtype: DType::F32,
15913            });
15914            let ws = g.push(Node {
15915                op: Op::WriteSlice {
15916                    ranges: vec![(1, 2), (0, 2)],
15917                    dyn_offset: None,
15918                },
15919                inputs: vec![dest, src],
15920                shape: Shape::from_dims(&[3, 2]),
15921                dtype: DType::F32,
15922            });
15923            g.set_target_backend(ws, BackendId::Cpu);
15924            let arc = Arc::new(RwLock::new(dest_storage));
15925            (dest, src, ws, arc)
15926        };
15927        let mut inputs = StorageCache::new();
15928        inputs.insert(dest_id, Arc::clone(&dest_arc_external));
15929        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
15930        let (result_arc, _) = PipelinedExecutor::realize(graph, ws_id, inputs).expect("realize");
15931        // Bytes were written into the same Arc the caller held —
15932        // the WriteSlice op aliases dest's Storage Arc, not allocates
15933        // a fresh buffer.
15934        assert!(
15935            Arc::ptr_eq(&result_arc, &dest_arc_external),
15936            "WriteSlice output Arc must be the same Arc as the destination's"
15937        );
15938        let guard = dest_arc_external.read().unwrap();
15939        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15940            panic!("expected Cpu storage");
15941        };
15942        let out: &[f32] = c.as_slice().unwrap();
15943        assert_eq!(out, &[0.0, 0.0, 10.0, 20.0, 0.0, 0.0]);
15944    }
15945
15946    // ---- WriteSlice dynamic offset (Phase D symbolic extents) ---------------
15947
15948    /// E2E: pipelined realize of `Op::WriteSlice` with a runtime start
15949    /// offset (`dyn_offset`) resolved through a per-pass `SymEnv`. The
15950    /// width-2 source slab lands at the bound offset (3), not the static
15951    /// `ranges[0].0` placeholder (0) — the persistent-decode KV-cache
15952    /// write at a per-token `cached_len`.
15953    #[test]
15954    fn pipelined_realize_write_slice_dynamic_offset() {
15955        use fuel_ir::{DynScalar, SymId};
15956        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
15957        let src_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0]);
15958        let graph = Arc::new(RwLock::new(Graph::new()));
15959        let sym = SymId(0);
15960        let (dest_id, src_id, ws_id) = {
15961            let mut g = graph.write().unwrap();
15962            let dest = g.push(Node {
15963                op: Op::Const,
15964                inputs: vec![],
15965                shape: Shape::from_dims(&[6]),
15966                dtype: DType::F32,
15967            });
15968            let src = g.push(Node {
15969                op: Op::Const,
15970                inputs: vec![],
15971                shape: Shape::from_dims(&[2]),
15972                dtype: DType::F32,
15973            });
15974            let ws = g.push(Node {
15975                // ranges[0] = (0, 2): the start is a placeholder (ignored —
15976                // overridden by dyn_offset); only the width (2) is read.
15977                op: Op::WriteSlice {
15978                    ranges: vec![(0, 2)],
15979                    dyn_offset: Some((0, DynScalar::Sym(sym))),
15980                },
15981                inputs: vec![dest, src],
15982                shape: Shape::from_dims(&[6]),
15983                dtype: DType::F32,
15984            });
15985            g.set_target_backend(ws, BackendId::Cpu);
15986            (dest, src, ws)
15987        };
15988        let mut inputs = StorageCache::new();
15989        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
15990        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
15991
15992        // Bind cached_len = 3: the slab must land at indices [3, 4].
15993        let mut env = SymEnv::new();
15994        env.bind(sym, 3).unwrap();
15995
15996        let (result_arc, _) = PipelinedExecutor::realize_with_env(graph, ws_id, inputs, env)
15997            .expect("realize_with_env");
15998        let guard = result_arc.read().unwrap();
15999        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16000            panic!("expected Cpu storage");
16001        };
16002        let out: &[f32] = c.as_slice().unwrap();
16003        assert_eq!(
16004            out,
16005            &[0.0, 0.0, 0.0, 7.0, 8.0, 0.0],
16006            "slab must land at the SymEnv-bound offset 3, not the static placeholder 0",
16007        );
16008    }
16009
16010    /// Increment 2a — the data-determined bind seam. After
16011    /// `Op::NonZeroIndices` realizes, the executor reads its runtime count
16012    /// from bundle slot 1 and PUBLISHES it into the produced `SymEnv` under
16013    /// `count_sym`. This is the first op to bind a *data-determined* symbol
16014    /// mid-realize (all prior binds are host-known before realize) — the
16015    /// keystone capability for SSM decode / MoE sparsity / MLA KV.
16016    #[test]
16017    fn pipelined_realize_nonzero_indices_publishes_count() {
16018        use fuel_ir::SymId;
16019        use fuel_ir::storage::{OutputViewSpec, compose_bundle};
16020        // flat [0,1,0,1,1,0] → 3 nonzeros at 1,3,4; capacity 6.
16021        let x_storage = fuel_memory::from_slice_cpu(&[0.0_f32, 1.0, 0.0, 1.0, 1.0, 0.0]);
16022        let graph = Arc::new(RwLock::new(Graph::new()));
16023        let count_sym = SymId(0);
16024        let (x_id, nzi_id) = {
16025            let mut g = graph.write().unwrap();
16026            let x = g.push(Node {
16027                op: Op::Const,
16028                inputs: vec![],
16029                shape: Shape::from_dims(&[2, 3]),
16030                dtype: DType::F32,
16031            });
16032            let capacity = 6usize;
16033            let idx_shape = Shape::from_dims(&[capacity]);
16034            let cnt_shape = Shape::from_dims(&[1]);
16035            let specs = vec![
16036                OutputViewSpec {
16037                    dtype: DType::U32,
16038                    shape: idx_shape.clone(),
16039                    layout: Layout::contiguous(idx_shape.clone()),
16040                    name: Some("indices"),
16041                },
16042                OutputViewSpec {
16043                    dtype: DType::U32,
16044                    shape: cnt_shape.clone(),
16045                    layout: Layout::contiguous(cnt_shape),
16046                    name: Some("count"),
16047                },
16048            ];
16049            let (_bytes, views) = compose_bundle(&specs).unwrap();
16050            let nzi = g.push(Node {
16051                op: Op::NonZeroIndices { count_sym },
16052                inputs: vec![x],
16053                shape: idx_shape,
16054                dtype: DType::U32,
16055            });
16056            g.set_output_views(nzi, Arc::from(views.into_boxed_slice()))
16057                .unwrap();
16058            g.set_target_backend(nzi, BackendId::Cpu);
16059            (x, nzi)
16060        };
16061        let mut inputs = StorageCache::new();
16062        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
16063
16064        let (_arc, _layout, produced) =
16065            PipelinedExecutor::realize_with_env_producing(graph, nzi_id, inputs, SymEnv::new())
16066                .expect("realize_with_env_producing");
16067
16068        assert_eq!(
16069            produced.get(count_sym),
16070            Some(3),
16071            "the executor must publish the data-determined nonzero count into the SymEnv",
16072        );
16073    }
16074
16075    /// A `dyn_offset` whose symbol is unbound in the `SymEnv` surfaces a
16076    /// typed error at realize (never a panic).
16077    #[test]
16078    fn pipelined_realize_write_slice_dynamic_offset_unbound_errors() {
16079        use fuel_ir::{DynScalar, SymId};
16080        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
16081        let src_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0]);
16082        let graph = Arc::new(RwLock::new(Graph::new()));
16083        let (dest_id, src_id, ws_id) = {
16084            let mut g = graph.write().unwrap();
16085            let dest = g.push(Node {
16086                op: Op::Const,
16087                inputs: vec![],
16088                shape: Shape::from_dims(&[6]),
16089                dtype: DType::F32,
16090            });
16091            let src = g.push(Node {
16092                op: Op::Const,
16093                inputs: vec![],
16094                shape: Shape::from_dims(&[2]),
16095                dtype: DType::F32,
16096            });
16097            let ws = g.push(Node {
16098                op: Op::WriteSlice {
16099                    ranges: vec![(0, 2)],
16100                    dyn_offset: Some((0, DynScalar::Sym(SymId(0)))),
16101                },
16102                inputs: vec![dest, src],
16103                shape: Shape::from_dims(&[6]),
16104                dtype: DType::F32,
16105            });
16106            g.set_target_backend(ws, BackendId::Cpu);
16107            (dest, src, ws)
16108        };
16109        let mut inputs = StorageCache::new();
16110        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
16111        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
16112        // Empty env — the symbol is unbound.
16113        let result = PipelinedExecutor::realize_with_env(graph, ws_id, inputs, SymEnv::new());
16114        assert!(
16115            result.is_err(),
16116            "unbound dyn_offset symbol must surface a typed error, not a panic",
16117        );
16118    }
16119
16120    /// A runtime offset whose resolved slab runs past the destination
16121    /// capacity errors at realize (never an out-of-bounds write).
16122    #[test]
16123    fn pipelined_realize_write_slice_dynamic_offset_out_of_capacity_errors() {
16124        use fuel_ir::{DynScalar, SymId};
16125        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
16126        let src_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0]);
16127        let graph = Arc::new(RwLock::new(Graph::new()));
16128        let sym = SymId(0);
16129        let (dest_id, src_id, ws_id) = {
16130            let mut g = graph.write().unwrap();
16131            let dest = g.push(Node {
16132                op: Op::Const,
16133                inputs: vec![],
16134                shape: Shape::from_dims(&[6]),
16135                dtype: DType::F32,
16136            });
16137            let src = g.push(Node {
16138                op: Op::Const,
16139                inputs: vec![],
16140                shape: Shape::from_dims(&[2]),
16141                dtype: DType::F32,
16142            });
16143            let ws = g.push(Node {
16144                op: Op::WriteSlice {
16145                    ranges: vec![(0, 2)],
16146                    dyn_offset: Some((0, DynScalar::Sym(sym))),
16147                },
16148                inputs: vec![dest, src],
16149                shape: Shape::from_dims(&[6]),
16150                dtype: DType::F32,
16151            });
16152            g.set_target_backend(ws, BackendId::Cpu);
16153            (dest, src, ws)
16154        };
16155        let mut inputs = StorageCache::new();
16156        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
16157        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
16158        // offset 5 + width 2 = 7 > capacity 6.
16159        let mut env = SymEnv::new();
16160        env.bind(sym, 5).unwrap();
16161        let result = PipelinedExecutor::realize_with_env(graph, ws_id, inputs, env);
16162        assert!(
16163            result.is_err(),
16164            "resolved slab past destination capacity must surface a typed error",
16165        );
16166    }
16167
16168    /// Regression for the PipelinedExecutor ordering-integration session.
16169    ///
16170    /// Graph: `x = Const`, `step_x = Step(x)`, `y = SigmoidInplace(x)`.
16171    /// `Step` and `SigmoidInplace` are both readers of `x`; `Step` is
16172    /// non-destructive, `SigmoidInplace` mutates `x`'s storage. The
16173    /// correct semantic is for `Step` to read PRE-mutation bytes.
16174    ///
16175    /// Pre-this-session (raw `topo_order_multi`): the two are siblings
16176    /// in topo order and the tie-break is unspecified — `SigmoidInplace`
16177    /// could run first, making `step_x` see post-sigmoid bytes
16178    /// (`[1, 1, 1, 1]` because every sigmoid output is positive).
16179    ///
16180    /// Post-this-session: `execution_plan` consults `derive_ordering`,
16181    /// which pins `SigmoidInplace` AFTER every other reader of `x`.
16182    /// `step_x` deterministically sees `x` and is `[1, 0, 1, 0]`.
16183    #[test]
16184    fn pipelined_inplace_with_multiple_readers_orders_correctly() {
16185        use fuel_ir::Shape;
16186        let data = [1.0_f32, -2.0, 3.0, -4.0];
16187        let src_storage = fuel_memory::from_slice_cpu(&data);
16188
16189        let graph = Arc::new(RwLock::new(Graph::new()));
16190        let (x_id, step_id, sig_id) = {
16191            let mut g = graph.write().unwrap();
16192            let x = g.push(Node {
16193                op: Op::Const,
16194                inputs: vec![],
16195                shape: Shape::from_dims(&[4]),
16196                dtype: DType::F32,
16197            });
16198            let step = g.push(Node {
16199                op: Op::Step,
16200                inputs: vec![x],
16201                shape: Shape::from_dims(&[4]),
16202                dtype: DType::F32,
16203            });
16204            let sig = g.push(Node {
16205                op: Op::SigmoidInplace,
16206                inputs: vec![x],
16207                shape: Shape::from_dims(&[4]),
16208                dtype: DType::F32,
16209            });
16210            g.set_target_backend(step, BackendId::Cpu);
16211            g.set_target_backend(sig, BackendId::Cpu);
16212            (x, step, sig)
16213        };
16214
16215        let mut cache = StorageCache::new();
16216        cache.insert(x_id, Arc::new(RwLock::new(src_storage)));
16217
16218        let results = PipelinedExecutor::realize_many(graph, &[step_id, sig_id], cache)
16219            .expect("realize_many");
16220
16221        // step_x must reflect pre-mutation x: sign of [1, -2, 3, -4] →
16222        // [1, 0, 1, 0]. If the executor ran SigmoidInplace first, step
16223        // would see all-positive sigmoid outputs and produce [1, 1, 1, 1].
16224        let step_guard = results[0].0.read().unwrap();
16225        let fuel_memory::BackendStorage::Cpu(c) = &step_guard.inner else {
16226            panic!("expected Cpu storage for step output");
16227        };
16228        let step_out: &[f32] = c.as_slice().expect("f32 cast");
16229        assert_eq!(
16230            step_out,
16231            &[1.0_f32, 0.0, 1.0, 0.0],
16232            "Step must run before SigmoidInplace; got post-mutation bytes"
16233        );
16234        drop(step_guard);
16235
16236        // SigmoidInplace's output Arc IS the mutated cache entry — bytes
16237        // approximate sigmoid([1, -2, 3, -4]).
16238        let sig_guard = results[1].0.read().unwrap();
16239        let fuel_memory::BackendStorage::Cpu(c) = &sig_guard.inner else {
16240            panic!("expected Cpu storage for sigmoid output");
16241        };
16242        let sig_out: &[f32] = c.as_slice().expect("f32 cast");
16243        let sig_ref = [
16244            1.0_f32 / (1.0 + (-1.0_f32).exp()),
16245            1.0_f32 / (1.0 + (2.0_f32).exp()),
16246            1.0_f32 / (1.0 + (-3.0_f32).exp()),
16247            1.0_f32 / (1.0 + (4.0_f32).exp()),
16248        ];
16249        for (got, want) in sig_out.iter().zip(sig_ref.iter()) {
16250            assert!((got - want).abs() < 1e-6, "sigmoid: got {got}, want {want}");
16251        }
16252    }
16253
16254    /// Regression for the PipelinedExecutor ordering-integration session.
16255    ///
16256    /// Canonical residual-connection pattern:
16257    ///   `x = Const`, `y = ReluInplace(x)`, `z = Add(y, x)`.
16258    ///
16259    /// Pre-this-session: `derive_ordering` was never run, so the cycle
16260    /// (Add must precede ReluInplace per ordering edge; Add must follow
16261    /// ReluInplace per data-flow edge through y) was undetected. The
16262    /// executor produced `z = relu(x) + relu(x) = [2, 0, 6, 0]` —
16263    /// silently wrong.
16264    ///
16265    /// Post-this-session: `insert_safety_copies` runs before
16266    /// `execution_plan`, inserts `Op::Copy(x) → x_safe`, rewires Add's
16267    /// `x` input to `x_safe`. Result: `z = relu(x) + x = [2, -2, 6, -4]`.
16268    #[test]
16269    fn pipelined_residual_connection_inserts_safety_copy() {
16270        use fuel_ir::Shape;
16271        let data = [1.0_f32, -2.0, 3.0, -4.0];
16272        let src_storage = fuel_memory::from_slice_cpu(&data);
16273
16274        let graph = Arc::new(RwLock::new(Graph::new()));
16275        let (x_id, _y_id, z_id) = {
16276            let mut g = graph.write().unwrap();
16277            let x = g.push(Node {
16278                op: Op::Const,
16279                inputs: vec![],
16280                shape: Shape::from_dims(&[4]),
16281                dtype: DType::F32,
16282            });
16283            let y = g.push(Node {
16284                op: Op::ReluInplace,
16285                inputs: vec![x],
16286                shape: Shape::from_dims(&[4]),
16287                dtype: DType::F32,
16288            });
16289            let z = g.push(Node {
16290                op: Op::Add,
16291                inputs: vec![y, x],
16292                shape: Shape::from_dims(&[4]),
16293                dtype: DType::F32,
16294            });
16295            g.set_target_backend(y, BackendId::Cpu);
16296            g.set_target_backend(z, BackendId::Cpu);
16297            (x, y, z)
16298        };
16299
16300        let mut cache = StorageCache::new();
16301        cache.insert(x_id, Arc::new(RwLock::new(src_storage)));
16302
16303        let (result_arc, _) = PipelinedExecutor::realize(graph, z_id, cache)
16304            .expect("realize z — insert_safety_copies must break the cycle");
16305
16306        let guard = result_arc.read().unwrap();
16307        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16308            panic!("expected Cpu storage");
16309        };
16310        let got: &[f32] = c.as_slice().expect("f32 cast");
16311        assert_eq!(
16312            got,
16313            &[2.0_f32, -2.0, 6.0, -4.0],
16314            "Add must read pre-mutation x via the inserted safety copy"
16315        );
16316    }
16317
16318    // ------------------------------------------------------------------
16319    // Item 3 end-to-end: SelectiveScan through the bundled-output
16320    // PipelinedExecutor path. The producer allocates bundled
16321    // (y_bytes + last_state_bytes), the kernel writes both slots,
16322    // and the bundled-tuple builder returns each via Op::View.
16323    // ------------------------------------------------------------------
16324
16325    fn cpu_const_f32(
16326        graph: &Arc<RwLock<Graph>>,
16327        cache: &mut StorageCache,
16328        data: &[f32],
16329        dims: &[usize],
16330    ) -> NodeId {
16331        let id = {
16332            let mut g = graph.write().unwrap();
16333            g.push(Node {
16334                op: Op::Const,
16335                inputs: vec![],
16336                shape: Shape::from_dims(dims),
16337                dtype: DType::F32,
16338            })
16339        };
16340        cache.insert(id, Arc::new(RwLock::new(fuel_memory::from_slice_cpu(data))));
16341        id
16342    }
16343
16344    /// `selective_scan_bundled` realizes both `y` and `last_state` in
16345    /// a single `realize_many` pass; the Views project the same
16346    /// producer's bundled Storage Arc and the numerics match the
16347    /// hand-computed single-step kernel test (b=1,s=1,d=1,k=1).
16348    #[test]
16349    fn pipelined_realize_selective_scan_bundled_produces_y_and_last_state() {
16350        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16351        let mut cache = StorageCache::new();
16352
16353        let u_id = cpu_const_f32(&graph, &mut cache, &[3.0], &[1, 1, 1]);
16354        let delta_id = cpu_const_f32(&graph, &mut cache, &[1.0], &[1, 1, 1]);
16355        let a_id = cpu_const_f32(&graph, &mut cache, &[-1.0], &[1, 1]);
16356        let b_id = cpu_const_f32(&graph, &mut cache, &[2.0], &[1, 1, 1]);
16357        let c_id = cpu_const_f32(&graph, &mut cache, &[0.5], &[1, 1, 1]);
16358
16359        let (y_id, last_state_id) = {
16360            let u_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), u_id);
16361            let delta_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), delta_id);
16362            let a_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), a_id);
16363            let b_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), b_id);
16364            let c_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), c_id);
16365            let (y, last_state) = u_t
16366                .selective_scan_bundled(&delta_t, &a_t, &b_t, &c_t, /* delta_softplus */ false)
16367                .expect("selective_scan_bundled");
16368            (y.id(), last_state.id())
16369        };
16370        // Set target_backend on the producer (View nodes inherit it).
16371        {
16372            let mut g = graph.write().unwrap();
16373            let producer = g.node(y_id).inputs[0];
16374            g.set_target_backend(producer, BackendId::Cpu);
16375        }
16376
16377        let outputs =
16378            PipelinedExecutor::realize_many(Arc::clone(&graph), &[y_id, last_state_id], cache)
16379                .expect("realize_many");
16380        let (y_arc, y_layout) = outputs[0].clone();
16381        let (last_state_arc, last_state_layout) = outputs[1].clone();
16382
16383        // Both Views project the same bundled producer Storage Arc.
16384        assert!(
16385            Arc::ptr_eq(&y_arc, &last_state_arc),
16386            "y and last_state Views project the SAME bundled producer Storage",
16387        );
16388
16389        // Hand-computed numerics (single-step recurrence):
16390        // h[0,0,0] = exp(1.0 * -1.0) * 0 + 1.0 * 2.0 * 3.0 = 6.0
16391        // y[0,0,0] = h * c = 6.0 * 0.5 = 3.0
16392        // last_state[0,0,0] = h = 6.0
16393        let guard = y_arc.read().unwrap();
16394        let fuel_memory::BackendStorage::Cpu(c_bytes) = &guard.inner else {
16395            panic!("expected Cpu storage");
16396        };
16397        let typed: &[f32] = c_bytes.as_slice().expect("f32 cast");
16398        assert_eq!(y_layout.start_offset(), 0);
16399        let y_value = typed[y_layout.start_offset()];
16400        assert!((y_value - 3.0).abs() < 1e-5, "y expected 3.0 got {y_value}");
16401        assert_eq!(
16402            last_state_layout.start_offset(),
16403            1,
16404            "slot 1 byte_offset 4 / sizeof(f32) = 1",
16405        );
16406        let ls_value = typed[last_state_layout.start_offset()];
16407        assert!(
16408            (ls_value - 6.0).abs() < 1e-5,
16409            "last_state expected 6.0 got {ls_value}"
16410        );
16411    }
16412
16413    /// E2E (row 172 item 2): TopKLastDim f32 on CPU through the bundled
16414    /// two-slot output. Row 0 has a NaN and tied values, row 1 distinct values;
16415    /// k = 3. The `values` View reads slot 0 and the `indices` View slot 1 of the
16416    /// SAME bundled storage (the indices slot starts 4-byte aligned).
16417    #[test]
16418    fn pipelined_realize_top_k_last_dim_bundled_values_and_indices() {
16419        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16420        let mut cache = StorageCache::new();
16421        let x_id = cpu_const_f32(
16422            &graph,
16423            &mut cache,
16424            &[1.0, 5.0, f32::NAN, 5.0, 2.0, 3.0, 3.0, 3.0, -1.0, 9.0],
16425            &[2, 5],
16426        );
16427        let (v_id, i_id) = {
16428            let x = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), x_id);
16429            let (v, i) = x.top_k_last_dim(3).expect("top_k_last_dim");
16430            (v.id(), i.id())
16431        };
16432        {
16433            let mut g = graph.write().unwrap();
16434            let producer = g.node(v_id).inputs[0];
16435            g.set_target_backend(producer, BackendId::Cpu);
16436        }
16437        let outputs = PipelinedExecutor::realize_many(Arc::clone(&graph), &[v_id, i_id], cache)
16438            .expect("realize_many");
16439        let (arc, v_layout) = outputs[0].clone();
16440        let (_, i_layout) = outputs[1].clone();
16441        let guard = arc.read().unwrap();
16442        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16443            panic!("expected Cpu storage");
16444        };
16445        let bytes = c.bytes();
16446        let vo = v_layout.start_offset() * 4;
16447        let io = i_layout.start_offset() * 4;
16448        let vals: Vec<f32> = bytes[vo..vo + 24]
16449            .chunks(4)
16450            .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
16451            .collect();
16452        let idx: Vec<u32> = bytes[io..io + 24]
16453            .chunks(4)
16454            .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
16455            .collect();
16456        assert_eq!(idx, vec![2, 1, 3, 4, 0, 1], "NaN first, ties by index");
16457        assert!(vals[0].is_nan());
16458        assert_eq!(&vals[1..], &[5.0, 5.0, 9.0, 3.0, 3.0]);
16459    }
16460
16461    /// E2E (row 172 item 2 step B): MatMulTopK f32 on CPU. Distinct matmul
16462    /// results, so the selection does not depend on accumulation order; the
16463    /// values and indices equal a hand matmul + top-2.
16464    #[test]
16465    fn pipelined_realize_matmul_top_k_f32() {
16466        // a [1, 2, 3], b [1, 3, 4]; row r of the result = a[r] @ b.
16467        let a = [1.0_f32, 2.0, 3.0, -1.0, 0.5, 2.0];
16468        let b = [
16469            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,
16470        ];
16471        let mut want_v = Vec::new();
16472        let mut want_i = Vec::new();
16473        for r in 0..2 {
16474            let row: Vec<f32> = (0..4)
16475                .map(|j| (0..3).map(|q| a[r * 3 + q] * b[q * 4 + j]).sum())
16476                .collect();
16477            let mut idx: Vec<usize> = (0..4).collect();
16478            idx.sort_by(|&x, &y| row[y].partial_cmp(&row[x]).unwrap());
16479            for &i in &idx[..2] {
16480                want_v.push(row[i]);
16481                want_i.push(i as u32);
16482            }
16483        }
16484        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16485        let mut cache = StorageCache::new();
16486        let a_id = cpu_const_f32(&graph, &mut cache, &a, &[1, 2, 3]);
16487        let b_id = cpu_const_f32(&graph, &mut cache, &b, &[1, 3, 4]);
16488        let (v_id, i_id) = {
16489            let at = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), a_id);
16490            let bt = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), b_id);
16491            let (v, i) = at.matmul_top_k(&bt, 2).expect("matmul_top_k");
16492            (v.id(), i.id())
16493        };
16494        {
16495            let mut g = graph.write().unwrap();
16496            let producer = g.node(v_id).inputs[0];
16497            g.set_target_backend(producer, BackendId::Cpu);
16498        }
16499        let outputs = PipelinedExecutor::realize_many(Arc::clone(&graph), &[v_id, i_id], cache)
16500            .expect("realize_many");
16501        let (arc, v_layout) = outputs[0].clone();
16502        let (_, i_layout) = outputs[1].clone();
16503        let guard = arc.read().unwrap();
16504        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16505            panic!("expected Cpu storage");
16506        };
16507        let bytes = c.bytes();
16508        let (vo, io) = (v_layout.start_offset() * 4, i_layout.start_offset() * 4);
16509        let vals: Vec<f32> = bytes[vo..vo + 16]
16510            .chunks(4)
16511            .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
16512            .collect();
16513        let idx: Vec<u32> = bytes[io..io + 16]
16514            .chunks(4)
16515            .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
16516            .collect();
16517        assert_eq!(idx, want_i);
16518        assert_eq!(vals, want_v);
16519    }
16520
16521    // ---- Ordering-defect repros (MLA decode multi-round WriteSlice) -----
16522
16523    /// DIAGNOSTIC (not a repro by itself): a plain single-hop view chain
16524    /// `S = Slice(X); K = Relu(S)` competing with a SECOND destructive
16525    /// WriteSlice on `X` (`Y = WriteSlice(X, ...)`) within one
16526    /// `realize_many` call. `collect_alias_set` adds `S` to `X`'s alias
16527    /// set (Slice IS `is_view_op`), so `derive_ordering` pins `Y` after
16528    /// `S`'s reader `K` directly. This form is expected to STAY GREEN —
16529    /// recorded here as the control that isolates the Reshape-specific
16530    /// gap exercised by the next test.
16531    #[test]
16532    fn pipelined_write_slice_round2_plain_slice_reader_not_stranded() {
16533        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16534        let mut cache = StorageCache::new();
16535
16536        let b_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16537        let src1_id = cpu_const_f32(&graph, &mut cache, &[1.0, 2.0], &[2]);
16538        let src2_id = cpu_const_f32(&graph, &mut cache, &[99.0, 98.0], &[2]);
16539
16540        let (k_id, y_id) = {
16541            let mut g = graph.write().unwrap();
16542            let x_id = g.push(Node {
16543                op: Op::WriteSlice {
16544                    ranges: vec![(0, 2)],
16545                    dyn_offset: None,
16546                },
16547                inputs: vec![b_id, src1_id],
16548                shape: Shape::from_dims(&[4]),
16549                dtype: DType::F32,
16550            });
16551            let s_id = g.push(Node {
16552                op: Op::Slice {
16553                    dim: 0,
16554                    start: 0,
16555                    len: 2,
16556                },
16557                inputs: vec![x_id],
16558                shape: Shape::from_dims(&[2]),
16559                dtype: DType::F32,
16560            });
16561            let k_id = g.push(Node {
16562                op: Op::Relu,
16563                inputs: vec![s_id],
16564                shape: Shape::from_dims(&[2]),
16565                dtype: DType::F32,
16566            });
16567            // Round 2 OVERLAPS round 1's [0,2) range so a wrong-order
16568            // execution would be numerically visible in K's output.
16569            let y_id = g.push(Node {
16570                op: Op::WriteSlice {
16571                    ranges: vec![(0, 2)],
16572                    dyn_offset: None,
16573                },
16574                inputs: vec![x_id, src2_id],
16575                shape: Shape::from_dims(&[4]),
16576                dtype: DType::F32,
16577            });
16578            g.set_target_backend(x_id, BackendId::Cpu);
16579            g.set_target_backend(k_id, BackendId::Cpu);
16580            g.set_target_backend(y_id, BackendId::Cpu);
16581            (k_id, y_id)
16582        };
16583
16584        let plan = fuel_graph::opt::execution_plan(&graph.read().unwrap(), &[k_id, y_id]);
16585        eprintln!("[diagnostic plain-slice] execution_plan = {:?}", plan,);
16586
16587        let outputs = PipelinedExecutor::realize_many(Arc::clone(&graph), &[k_id, y_id], cache)
16588            .expect("realize_many: plain slice reader must not error");
16589        let (k_arc, _) = &outputs[0];
16590        let guard = k_arc.read().unwrap();
16591        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16592            panic!("expected Cpu storage");
16593        };
16594        let out: &[f32] = c.as_slice().unwrap();
16595        assert_eq!(
16596            out,
16597            &[1.0, 2.0],
16598            "K = relu(slice(X,0,2)) must read PRE-round-2 bytes; got {:?}",
16599            out,
16600        );
16601    }
16602
16603    /// CRITICAL SUSPECT #2 repro: `Op::Reshape`/`Op::Contiguize` compile
16604    /// to `WorkItemKind::ContiguizeOf`, which zero-copy ADOPTS the
16605    /// input's Storage Arc when the input is contiguous at offset 0 —
16606    /// but `Op::Reshape` is NOT in `collect_alias_set`'s alias-extending
16607    /// predicate (only `Op::is_view_op` + `Op::View{..}`). So for
16608    /// `X = write_slice(B, src1); S = X.slice(0, 0, 2) [offset-0
16609    /// contiguous]; R = S.reshape([2]); K = relu(R); Y =
16610    /// write_slice(X, src2)`, `collect_alias_set(X)` stops at `{X, S}`
16611    /// — `R` never enters the alias set, so `derive_ordering` never
16612    /// scans `R`'s consumers (`K`) for pinning against `Y`. `K` and `Y`
16613    /// become simultaneously "ready" once `R` completes, and
16614    /// `execution_plan`'s stable tiebreak (smaller `topo_order_multi`
16615    /// position wins) can schedule `Y` (destructive) BEFORE `K` — `K`
16616    /// then dereferences `R`'s adopted Arc (== `X`'s Arc, mutated
16617    /// in-place by `Y`) and silently reads POST-`Y` bytes. No error;
16618    /// wrong numbers.
16619    #[test]
16620    fn pipelined_write_slice_reshape_adopted_arc_reader_reads_pre_write_bytes() {
16621        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16622        let mut cache = StorageCache::new();
16623
16624        let b_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16625        let src1_id = cpu_const_f32(&graph, &mut cache, &[1.0, 2.0], &[2]);
16626        let src2_id = cpu_const_f32(&graph, &mut cache, &[99.0, 98.0], &[2]);
16627
16628        let (x_id, k_id, y_id) = {
16629            let mut g = graph.write().unwrap();
16630            let x_id = g.push(Node {
16631                op: Op::WriteSlice {
16632                    ranges: vec![(0, 2)],
16633                    dyn_offset: None,
16634                },
16635                inputs: vec![b_id, src1_id],
16636                shape: Shape::from_dims(&[4]),
16637                dtype: DType::F32,
16638            });
16639            let s_id = g.push(Node {
16640                // OFFSET-0 contiguous prefix slice — ContiguizeOf's
16641                // zero-copy fast path requires this at execute time.
16642                op: Op::Slice {
16643                    dim: 0,
16644                    start: 0,
16645                    len: 2,
16646                },
16647                inputs: vec![x_id],
16648                shape: Shape::from_dims(&[2]),
16649                dtype: DType::F32,
16650            });
16651            let r_id = g.push(Node {
16652                op: Op::Reshape(Shape::from_dims(&[2])),
16653                inputs: vec![s_id],
16654                shape: Shape::from_dims(&[2]),
16655                dtype: DType::F32,
16656            });
16657            let k_id = g.push(Node {
16658                op: Op::Relu,
16659                inputs: vec![r_id],
16660                shape: Shape::from_dims(&[2]),
16661                dtype: DType::F32,
16662            });
16663            // Round 2 OVERLAPS round 1's [0,2) range (not the [2,4)
16664            // tail) so a wrong-order execution is numerically visible
16665            // in K's output — a disjoint round 2 would corrupt bytes
16666            // K never reads, masking the defect.
16667            let y_id = g.push(Node {
16668                op: Op::WriteSlice {
16669                    ranges: vec![(0, 2)],
16670                    dyn_offset: None,
16671                },
16672                inputs: vec![x_id, src2_id],
16673                shape: Shape::from_dims(&[4]),
16674                dtype: DType::F32,
16675            });
16676            g.set_target_backend(x_id, BackendId::Cpu);
16677            g.set_target_backend(k_id, BackendId::Cpu);
16678            g.set_target_backend(y_id, BackendId::Cpu);
16679            (x_id, k_id, y_id)
16680        };
16681        let _ = x_id;
16682
16683        let plan = fuel_graph::opt::execution_plan(&graph.read().unwrap(), &[k_id, y_id]);
16684        eprintln!(
16685            "[diagnostic reshape-adopted-arc] execution_plan = {:?}",
16686            plan,
16687        );
16688
16689        let outputs = PipelinedExecutor::realize_many(Arc::clone(&graph), &[k_id, y_id], cache)
16690            .expect("realize_many");
16691        let (k_arc, _) = &outputs[0];
16692        let guard = k_arc.read().unwrap();
16693        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16694            panic!("expected Cpu storage");
16695        };
16696        let out: &[f32] = c.as_slice().unwrap();
16697        // K = relu(reshape(slice(X,0,2))) must read PRE-round-2 bytes:
16698        // relu([1.0, 2.0]) = [1.0, 2.0]. Round 2 overwrites the SAME
16699        // [0,2) range with [99.0, 98.0] — if Y (round 2) runs before K
16700        // (the ordering defect), K instead observes [99.0, 98.0].
16701        assert_eq!(
16702            out,
16703            &[1.0, 2.0],
16704            "K must read PRE-round-2 bytes through the adopted Arc; got {:?} \
16705             (post-round-2 corruption if this fails)",
16706            out,
16707        );
16708    }
16709
16710    /// The MLA-decode shape from `rebind_latent_cache_fresh_graph`'s doc
16711    /// (`fuel-core/src/lazy_deepseek2.rs`): layer L's post-append buffer
16712    /// `X_L_N` (round N) is read TWICE within one realize call — once
16713    /// (non-destructively) through a Slice+Reshape "attention math" view
16714    /// chain whose result becomes an ancestor of layer L+1's round-N
16715    /// write, and again as the DESTINATION of layer L's round-(N+1)
16716    /// append. Reproduces the same Reshape-adoption gap as
16717    /// `pipelined_write_slice_reshape_adopted_arc_reader_reads_pre_write_bytes`
16718    /// at 2-layer scale, confirming the defect is not an artifact of the
16719    /// single-hop minimal form.
16720    #[test]
16721    fn pipelined_write_slice_mla_two_layer_round2_reshape_reader_not_stranded() {
16722        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16723        let mut cache = StorageCache::new();
16724
16725        let b_l_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16726        let src_l_n_id = cpu_const_f32(&graph, &mut cache, &[1.0, 2.0], &[2]);
16727        let b_l1_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16728        let src_l_n1_id = cpu_const_f32(&graph, &mut cache, &[99.0, 98.0], &[2]);
16729
16730        let (x_l_n1_id, x_l1_n_id) = {
16731            let mut g = graph.write().unwrap();
16732            // Round N, layer L: append src_l_n into b_l.
16733            let x_l_n = g.push(Node {
16734                op: Op::WriteSlice {
16735                    ranges: vec![(0, 2)],
16736                    dyn_offset: None,
16737                },
16738                inputs: vec![b_l_id, src_l_n_id],
16739                shape: Shape::from_dims(&[4]),
16740                dtype: DType::F32,
16741            });
16742            // "Attention math" for round N at layer L: read the filled
16743            // prefix, reshape (head-split-style hop), then a kernel.
16744            let s_l_n = g.push(Node {
16745                op: Op::Slice {
16746                    dim: 0,
16747                    start: 0,
16748                    len: 2,
16749                },
16750                inputs: vec![x_l_n],
16751                shape: Shape::from_dims(&[2]),
16752                dtype: DType::F32,
16753            });
16754            let rs_l_n = g.push(Node {
16755                op: Op::Reshape(Shape::from_dims(&[2])),
16756                inputs: vec![s_l_n],
16757                shape: Shape::from_dims(&[2]),
16758                dtype: DType::F32,
16759            });
16760            let r_l_n = g.push(Node {
16761                op: Op::Relu,
16762                inputs: vec![rs_l_n],
16763                shape: Shape::from_dims(&[2]),
16764                dtype: DType::F32,
16765            });
16766            // Round N, layer L+1: append the attention-math result.
16767            let x_l1_n = g.push(Node {
16768                op: Op::WriteSlice {
16769                    ranges: vec![(0, 2)],
16770                    dyn_offset: None,
16771                },
16772                inputs: vec![b_l1_id, r_l_n],
16773                shape: Shape::from_dims(&[4]),
16774                dtype: DType::F32,
16775            });
16776            // Round N+1, layer L: append into x_l_n directly (SAME node
16777            // s_l_n/rs_l_n/r_l_n read from) — OVERLAPPING range so a
16778            // wrong-order execution is numerically visible downstream.
16779            let x_l_n1 = g.push(Node {
16780                op: Op::WriteSlice {
16781                    ranges: vec![(0, 2)],
16782                    dyn_offset: None,
16783                },
16784                inputs: vec![x_l_n, src_l_n1_id],
16785                shape: Shape::from_dims(&[4]),
16786                dtype: DType::F32,
16787            });
16788            g.set_target_backend(x_l_n, BackendId::Cpu);
16789            g.set_target_backend(r_l_n, BackendId::Cpu);
16790            g.set_target_backend(x_l1_n, BackendId::Cpu);
16791            g.set_target_backend(x_l_n1, BackendId::Cpu);
16792            (x_l_n1, x_l1_n)
16793        };
16794
16795        let plan = fuel_graph::opt::execution_plan(&graph.read().unwrap(), &[x_l1_n_id, x_l_n1_id]);
16796        eprintln!("[diagnostic mla-2-layer] execution_plan = {:?}", plan);
16797
16798        let outputs =
16799            PipelinedExecutor::realize_many(Arc::clone(&graph), &[x_l1_n_id, x_l_n1_id], cache)
16800                .expect("realize_many");
16801        // outputs[0] = x_l1_n = write_slice(b_l1, relu(reshape(slice(x_l_n))))
16802        // Must reflect round-N's PRE-round-(N+1) bytes: relu([1,2]) = [1,2].
16803        let (x_l1_n_arc, _) = &outputs[0];
16804        let guard = x_l1_n_arc.read().unwrap();
16805        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16806            panic!("expected Cpu storage");
16807        };
16808        let out: &[f32] = c.as_slice().unwrap();
16809        assert_eq!(
16810            out,
16811            &[1.0, 2.0, 0.0, 0.0],
16812            "layer L+1's round-N append must reflect PRE-round-(N+1) attention \
16813             math output; got {:?} (post-round-(N+1) corruption if this fails)",
16814            out,
16815        );
16816    }
16817}